ArkTS Logger for HarmonyOS: Inspired by Flutter's Logger Package

linpengtenglinpengteng
4 min read

Introduction

In HarmonyOS application development, an efficient logging system is crucial for debugging and troubleshooting. While the native hilog interface provides comprehensive functionality, it presents several practical limitations:

  • Complex Data: Requires manual serialization of objects and collection types

  • Log Filtering: Lacks capability for runtime dynamic log level adjustment

  • Local Storage: No built-in log file management or rotation mechanism

  • Cloud Reporting: Missing ready-to-use cloud logging solution

During my experience developing Flutter Apps, I worked with Flutter's logger library whose elegant design left a deep impression. Inspired by this, I developed a similar logging solution for HarmonyOS (logger) featuring:

  • Support for multiple data types including primitives, objects, Classes, Maps, Sets with JSON serialization

  • Customizable logging behaviors like dynamic filtering, local file I/O (with automatic periodic cleanup), and cloud reporting

  • Compatibility with HarmonyOS Next API12+

  • Stack trace information output

Preparation

  1. Register an OHPM Account, Visit the OpenHarmony Package Manager to create your OHPM account.

  2. Go to [Profile → Security Management] to add your OHPM public key:

     # ssh-keygen creates public/private key pair - NOTE: passphrase MUST NOT be omitted!!!
     # --------------------------------------------------------------
       ssh-keygen -m PEM -t RSA -b 4096 -f ~/.ssh_ohpm/id_rsa_publish
       Generating public/private RSA key pair.
       Enter passphrase (empty for no passphrase):
    
  3. Go to [Profile] Copy the publish code and configure publish_id on your local device

       # your_publish_id: the publishing code you copied
       # ----------------------------------------------
       ohpm config set publish_id your_publish_id
    

Development Explanation

APIPurposeDetailed Description
FilterLog filteringControls which logs should be recorded, supports log level filtering (DEBUG/INFO/WARN/ERROR) etc.
OutputLog output stream managementDefines final log output destinations and behaviors, such as console, local files, network reporting, multiple output source combinations
PrinterLog content formattingHandles log visual presentation, including text formatting (colors/indentation/borders), structured output, stack tracing
LoggerLog trigger entry pointProvides developer-facing logging interface with multiple level methods (debug, info, warn, error etc.)
APIInherits FromPurposeDetailed Description
SafeFilterFilterBasic log filteringFundamental log level filtering (DEBUG, INFO, WARN, ERROR)
SafeWriteFileOutputOutputFilesystem log outputSupports automatic log directory creation (daily), log file rotation, exception recovery mechanism, and uses AsyncMutex to optimize high-frequency write/read operations
SafeConsoleOutputOutputConsole log outputCompatible with DevEco Studio console, supports color differentiation and highlighting
SafeMultiOutputOutputMulti-destination outputSupports multiple output sources with configurable output weights
SafeSimplePrinterPrinterMinimalist log formatSingle-line text output without decorations (no timestamps/borders), ideal for high-frequency debug logs
SafePrettyPrinterPrinterBeautified formatted outputMulti-line formatted output with borders, auto-aligned key-value pairs, supports stack trace display and complex object tree visualization
SafeHybridPrinterPrinterHybrid strategy printerUses different printing strategies for different log levels with customizable level mapping
SafeLoggerLoggerDeveloper interfaceProvides logging API for developers with multiple level methods (debug, info, warn, error, etc.)

Common APIs

CategoryMethodDescriptionReturn Type
Custom OptionsresetCustomize log configurationPromise<void>
LoggingdebugLog DEBUG level messagePromise<void>
infoLog INFO level messagePromise<void>
warnLog WARN level messagePromise<void>
errorLog ERROR level messagePromise<void>
fatalLog FATAL level (highest) messagePromise<void>
File ReadingreadAsRequestFileRead latest log file (full path)`Promise<IRequestFile
readAsRequestFilesRead recent log files (full paths)`Promise<IRequestFile[]
readAsArrayBufferRead latest log file (binary data)`Promise<IArrayBuffer
readAsArrayBuffersRead recent log files (binary data)`Promise<IArrayBuffer[]
readAsStringRead latest log file (text content)`Promise<IString
readAsStringsRead recent log files (text content)`Promise<IString[]
Event ListenersaddWriteListenerRegister log write event listenervoid
removeWriteListenerRemove log write event listenervoid
Log CleanupclearHistoryClear expired log filesPromise<void>
clearAllClear all log files (including current)Promise<void>
Log InspectionisEmptyCheck if log files are empty (non-existent)Promise<boolean>

Source code / Repository

Github logger
OpenHarmony logger

Welcome to give a Star 👍

0
Subscribe to my newsletter

Read articles from linpengteng directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

linpengteng
linpengteng

Programmer (Harmony、Flutter、Web、Go)