LoggerPro for Delphi

repository·master·Indexed 18 days ago

https://github.com/danieleteti/loggerpro

A high-performance, asynchronous, and pluggable logging framework for Delphi developers (versions 10.2 to 13). It features structured logging, a fluent Builder API, and JSON-based configuration for runtime reshaping. LoggerPro supports cross-platform deployment (Windows, Linux, macOS, Android, iOS) and includes over 20 built-in appenders such as File, Console, HTTP, ElasticSearch, and Grafana Loki, with additional contrib appenders for Redis.

Tokens
3.1K
Snippets
8
Records
16
Agent score
64%

What's inside LoggerPro

  1. Overview of LoggerPro for Delphi

    master

    LoggerPro is a modern, asynchronous, and pluggable logging framework designed for Delphi applications. It is built to be non-blocking, ensuring zero impact on the application's hot path.

    Key features include:

    • Async by design: Non-blocking logging operations.
    • Pluggable architecture: Over 20 built-in appenders (e.g., File, Console, HTTP, ElasticSearch, Windows Event Log, Database, Grafana Loki via LogFmt).
    • Fluent Builder API: Provides a Serilog-style configuration experience.
    • JSON Configuration: Allows reshaping the logger at deploy time without requiring a rebuild.
    • Structured Logging: Supports first-class LogParam context.
    • Cross-platform support: Works on Windows, Linux, macOS, Android, and iOS.
    • Thread-safe and DLL-safe.

    Supported Delphi versions: 10.2 to 13.

  2. Key features in LoggerPro v2.1

    master

    Version 2.1 introduced several significant capabilities for developers:

    • JSON configuration: Reshape the logger at deploy time.
    • HTML live log viewer: A self-contained .html file with filters, search, export, and live tailing.
    • ExeWatch integration: Cloud observability via ExeWatch.
    • Pluggable appenders: Optional backends self-register via the uses clause.
    • LogFmt renderer: Spec-compliant key=value output for Loki, humanlog, and ripgrep.
    • FileBySource appender: Supports per-tenant subfolders with day+size rotation.
    • Runtime log level: Change the global gate on the fly using ILogWriter.MinimumLevel.
    • UTF-8 console output: Correct Unicode support for Docker and Windows consoles.
    • DLL-safe initialization: Fixes Windows Loader Lock deadlocks.
    • ElasticSearch authentication: Supports Basic, API Key, and Bearer Token.
    • UDP Syslog local time option.
    • GetCurrentLogFileName API: Available on file appenders.
  3. Install LoggerPro as a source-only library

    master

    LoggerPro is a source-only library. It does not require a design-time package or component installation. To use it, you must add the source directory to your IDE's Library Path.

    1. Extract the loggerpro-2.1.1.zip archive.
    2. Add the extracted loggerpro root folder to the IDE Library Path for every target platform you use (e.g., Win32, Win64) via: Tools > Options > Language > Delphi > Library.
    3. You can now use any LoggerPro unit by adding LoggerPro to your uses clause.
    uses
      LoggerPro;
  4. Use a precompiled runtime BPL for LoggerPro

    master

    If you prefer to use a precompiled runtime BPL instead of compiling the source files into every project, you can build the provided runtime-only package. This package is marked with {$RUNONLY}, so it does not need to be installed into the IDE.

    1. Locate the folder packages\d<XXX>\ where <XXX> corresponds to your RAD Studio version.
    2. Open loggerproRT.dproj.
    3. Build the project to generate the .bpl and .dcp files.
  5. Uninstall LoggerPro

    master

    Since LoggerPro has no external installer or registered IDE package, uninstallation is a manual process:

    1. Remove the loggerpro root folder entry from the IDE Library Path (Tools > Options > Language > Delphi > Library) for all platforms.
    2. If you built the optional runtime package, delete the generated loggerproRT*.bpl and loggerproRT*.dcp files from your output/BPL folders.
    3. Delete the extracted loggerpro folder from your local storage.
  6. How to use LoggerPro Contrib Appenders

    master

    The contrib folder contains appenders that require external dependencies and are not part of the core LoggerPro package. To use an appender from this folder, follow these three steps:

    1. Install dependencies: Install any external libraries required by the specific appender.
    2. Update Search Path: Add the contrib folder to your Delphi project's search path.
    3. Include Units: Add the relevant appender unit to your uses clause.
  7. Set up the SQL Server DB Appender

    master

    To use the DB Appender, you must prepare a SQL Server database with a stored procedure designed to receive log data as parameters. The stored procedure must accept parameters that match the log item structure.

    Example parameter schema:

    • @LogType (int)
    • @LogTag (nvarchar(25))
    • @LogMessage (nvarchar(4096))
    • @Timestamp (datetime)
    • @TID (int)

    After setting up the database, you must configure your database connection string within the LoggerProConfig unit.

    -- Example Stored Procedure Parameter Signature
    @LogType int,
    @LogTag nvarchar(25),
    @LogMessage nvarchar(4096),
    @Timestamp datetime,
    @TID int
  8. Initialize LoggerPro from a JSON configuration

    master

    You can fully configure an ILogWriter instance using a JSON file or a JSON string. This approach allows for zero-code configuration of log levels, default tags, and multiple appenders (Console, File, Webhook, etc.).

    Key Methods:

    • TLoggerProConfig.FromJSONFile(aFileName): Reads a UTF-8 JSON file and returns a configured logger.
    • TLoggerProConfig.FromJSONString(aJSON): Parses a JSON string and returns a configured logger.
    • TLoggerProConfig.BuilderFromJSONFile(aFileName): Returns an ILoggerProBuilder instead of a logger. Use this if you want to load most settings from JSON but manually add appenders that cannot be expressed in JSON (like callbacks or VCL components).
    • TLoggerProConfig.BuilderFromJSONString(aJSON): Returns an ILoggerProBuilder from a JSON string.
    // Load from a file
    Log := TLoggerProConfig.FromJSONFile('loggerpro.json');
    
    // Load from a string
    Log := TLoggerProConfig.FromJSONString('{"minimumLevel": "Info", "appenders": []}');
    
    // Load as a builder to add custom appenders manually
    Builder := TLoggerProConfig.BuilderFromJSONFile('loggerpro.json');
    Log := Builder.WriteToConsole.Done.Build;
  9. Use LoggerPro.RedisAppender to log to Redis

    master

    The LoggerPro.RedisAppender sends log messages to a Redis list.

    Dependencies:

    Required DelphiRedisClient units:

    • Redis.Client
    • Redis.Values
    • Redis.Command
    • Redis.Commons
    • Redis.NetLib.INDY
    • Redis.NetLib.Factory

    Implementation: To use it, include LoggerPro.RedisAppender in your uses clause and instantiate TLoggerProRedisAppender.Create within your BuildLogWriter call. The constructor accepts the Redis host, port, and a list length/limit parameter.

    uses
      LoggerPro,
      LoggerPro.RedisAppender;
    
    var
      Log: ILogWriter;
    begin
      Log := BuildLogWriter([
        TLoggerProRedisAppender.Create('localhost', 6379, 1000)
      ]);
    end;
  10. Configure the LoggerPro JSON schema

    master

    The root of the JSON configuration object supports the following fields:

    KeyTypeDescription
    configVersionIntegerSchema version. Current is 1. If missing, latest is assumed.
    minimumLevelStringGlobal minimum log level (e.g., Debug, Info, Warn, Error, Fatal).
    defaultMinimumLevelStringMinimum level for appenders that don't specify one.
    defaultTagStringThe default tag applied to all log entries.
    appendersArrayA list of appender configuration objects.

    Example JSON Structure:

    {
      "configVersion": 1,
      "minimumLevel": "Info",
      "defaultTag": "myapp",
      "appenders": [
        { "type": "Console", "colors": true, "colorScheme": "Midnight" },
        { "type": "File", "logsFolder": "logs", "maxBackupFiles": 5 }
      ]
    }
    {
      "configVersion": 1,
      "minimumLevel": "Info",
      "defaultTag": "myapp",
      "appenders": [
        {
          "type": "Console",
          "colors": true,
          "colorScheme": "Midnight"
        },
        {
          "type": "File",
          "logsFolder": "logs",
          "maxBackupFiles": 5
        }
      ]
    }
  11. Handle configuration errors with ELoggerProConfigError

    master

    When loading configurations via JSON, LoggerPro may raise ELoggerProConfigError. This error provides context about which appender failed and why. Errors are typically formatted as:

    • appenders[index] (type=type): message
    • appenders[index] (type=type): ExceptionClassName - message
  12. Register custom appender types

    master

    If you have a custom appender that cannot be described via standard JSON types (e.g., it requires a runtime object or a callback), you can register a factory to handle a specific type string in your JSON configuration.

    Method: TLoggerProConfig.RegisterAppenderType(aType, aFactory, aAllowedFields)

    • aType: The case-insensitive string used in the JSON "type" field.
    • aFactory: A TLoggerProAppenderFactory procedure. It receives the ILoggerProBuilder and the TJSONObject for that appender. You must call the appropriate WriteToXxx method on the builder, configure it, and call .Done.
    • aAllowedFields: An array of strings representing the valid JSON keys for this appender. This enables strict validation to catch typos in configuration files.
    // Example of registering a custom appender factory
    TLoggerProConfig.RegisterAppenderType(
      'MyCustomType', 
      procedure(const aBuilder: ILoggerProBuilder; const aConfig: TJSONObject) 
      begin
        aBuilder.WriteToConsole.WithPrefix('CUSTOM').Done;
      end, 
      ['prefix']
    );