### Install humanlog manually Source: https://www.danieleteti.it/loggerpro Install the humanlog tool by downloading the pre-compiled binary zip file from GitHub releases and adding it to your system's PATH. ```bash # Download humanlog__windows_amd64.zip from GitHub releases, unzip, put # humanlog.exe on PATH. Or via Scoop: ``` -------------------------------- ### Install humanlog using Scoop Source: https://www.danieleteti.it/loggerpro Install the humanlog tool, a Go binary for pretty-printing and filtering logfmt logs, using the Scoop package manager. Ensure the 'extras' bucket is added first. ```bash # Scoop scoop bucket add extras scoop install humanlog ``` -------------------------------- ### Install LoggerPro using BOSS Source: https://www.danieleteti.it/loggerpro Use BOSS to install LoggerPro. This command initializes BOSS if needed and then installs the LoggerPro package from its GitHub repository. Commit the generated boss.json and boss-lock.json files, and add the modules directory to .gitignore. ```bash boss init boss install github.com/danieleteti/loggerpro ``` -------------------------------- ### ExeWatch Integration Setup Source: https://www.danieleteti.it/loggerpro Includes the necessary units for integrating LoggerPro with ExeWatch. The appender handles SDK initialization automatically. ```delphi uses LoggerPro, LoggerPro.Builder, LoggerPro.ExeWatchAppender; ``` -------------------------------- ### Install ripgrep using Scoop Source: https://www.danieleteti.it/loggerpro Install the ripgrep command-line tool on Windows using the Scoop package manager. This is an alternative to using winget or manual installation. ```bash # Option B: Scoop scoop install ripgrep ``` -------------------------------- ### Configure LoggerPro with JSON and VCL ListView Source: https://www.danieleteti.it/loggerpro This example shows initializing LoggerPro with a JSON configuration and adding a VCL ListView appender for live log display. It includes settings for max log lines and shutdown handling. ```delphi uses LoggerPro, LoggerPro.Builder; procedure TMainForm.FormCreate(Sender: TObject); begin FLog := LoggerProBuilderFromJSONFile('loggerpro.json') .WriteToVCLListView(ListViewLogs) .WithMaxLogLines(1000) .Done .Build; end; procedure TMainForm.FormDestroy(Sender: TObject); begin FLog.Shutdown; // before the form - and the ListView - are freed FLog := nil; end; ``` -------------------------------- ### Minimum Appender Configuration Source: https://www.danieleteti.it/loggerpro The absolute minimum configuration requires an 'appenders' array with at least one appender type. This example shows a basic Console appender setup. ```json { "appenders": [ { "type": "Console" } ] } ``` -------------------------------- ### Install ripgrep manually Source: https://www.danieleteti.it/loggerpro Install the ripgrep command-line tool by downloading the pre-compiled binary zip file from GitHub releases and adding it to your system's PATH. ```bash # Option C: download ripgrep-*.zip from GitHub releases, unzip, put rg.exe on PATH ``` -------------------------------- ### LogFmt Example Output Source: https://www.danieleteti.it/loggerpro An example of a log line formatted using the LogFmt standard, which uses key=value pairs separated by spaces. Values are quoted if they contain spaces or special characters. ```logfmt time=2026-04-18T12:30:45.123Z threadid=7932 type=INFO msg="order placed" tag=ORDERS order_id=42 amount=99.95 paid=true ``` -------------------------------- ### Install ripgrep using winget Source: https://www.danieleteti.it/loggerpro Install the ripgrep command-line tool on Windows using the Windows Package Manager (winget). This is one of several methods for installing ripgrep. ```bash # Option A: winget (Windows 10/11) winget install BurntSushi.ripgrep.MSVC ``` -------------------------------- ### Configure LoggerPro with JSON and UI Callback Source: https://www.danieleteti.it/loggerpro Example of initializing LoggerPro with a JSON configuration file and adding a UI callback appender for status bar updates. The callback is synchronized to the main thread. ```delphi uses LoggerPro, LoggerPro.Builder; Log := LoggerProBuilderFromJSONFile('loggerpro.json') .WriteToCallback .WithCallback( procedure(const aLogItem: TLogItem; const aFormattedMessage: string) begin // The callback appender marshals to the main thread for us. StatusBar1.SimpleText := aFormattedMessage; end) .WithSynchronizeToMainThread(True) .Done .Build; ``` -------------------------------- ### Quick Start with LoggerPro Builder API Source: https://www.danieleteti.it/loggerpro Demonstrates basic usage of the LoggerPro Builder API for configuring file and console appenders, logging messages with different levels, adding contextual properties, and handling exceptions. Ensure to call Log.Shutdown before application exit. ```delphi uses LoggerPro, LoggerPro.Builder; var Log: ILogWriter; begin Log := LoggerProBuilder .WithDefaultTag('MYAPP') .WriteToFile .WithLogsFolder('logs') .WithMaxBackupFiles(5) .WithMaxFileSizeInKB(10000) .Done .WriteToConsole .Done .Build; Log.Info('Application started'); Log.Debug('Processing item %d', [42], 'WORKER'); Log.Error('Connection failed', 'DATABASE'); // Contextual logging Log.WithProperty('user_id', 42) .WithProperty('session', 'abc123') .Info('User logged in', 'auth'); // Exception logging try // ... code ... except on E: Exception do Log.LogException(E, 'Operation failed', 'error'); end; // Explicit shutdown before exit Log.Shutdown; end; ``` -------------------------------- ### Initialize LoggerPro from JSON File Source: https://www.danieleteti.it/loggerpro Use LoggerProFromJSONFile for the simplest setup, loading all configuration from a JSON file. This is suitable for most common logging scenarios. ```delphi uses LoggerPro; // 1. Pure JSON → ILogWriter (simplest, covers most cases) Log := LoggerProFromJSONFile('loggerpro.json'); ``` -------------------------------- ### Getting Current Log File Name with SimpleFileAppender Source: https://www.danieleteti.it/loggerpro This example shows how to obtain the name of the current log file when using a TLoggerProSimpleFileAppender. This is useful for tasks like uploading or emailing the log file. ```pascal uses LoggerPro, LoggerPro.Builder, LoggerPro.FileAppender; var lAppender: TLoggerProSimpleFileAppender; Log: ILogWriter; begin lAppender := TLoggerProSimpleFileAppender.Create; Log := LoggerProBuilder .WriteToAppender(lAppender) .Build; Log.Info('Message'); UploadLogFile(lAppender.GetCurrentLogFileName); end; ``` -------------------------------- ### Fluent Chain with JSON Base for ExeWatch Appender Source: https://www.danieleteti.it/loggerpro Combine a loggerpro.json configuration file with code-side setup for ExeWatch. This approach centralizes console/file/HTML configurations in the JSON file while keeping sensitive SDK secrets in code, sourced from vaults or environment variables. ```pascal uses LoggerPro, LoggerPro.Builder, LoggerPro.ExeWatchAppender; Log := WithExeWatch( LoggerProBuilderFromJSONFile('loggerpro.json')) .WithAPIKey(LoadFromVault('ew_api_key')) .WithCustomerId(CurrentTenant) .WithAppVersion(GetFileVersion) .Done .Build; ``` -------------------------------- ### Structured Logging with LogFmt Source: https://www.danieleteti.it/loggerpro Example of querying logs using LogFmt syntax, suitable for Grafana Loki. This approach is recommended for development, container stdout, and lower volume production logs. ```logfmt {app="myapp"} | logfmt | type="ERROR" | order_id="42" ``` -------------------------------- ### Fallback Log Searching with Select-String Source: https://www.danieleteti.it/loggerpro Utilize Select-String for log searching when no installations are permitted. It supports pattern matching and context retrieval. ```powershell # Errors for tag ORDERS Select-String -Path logs\myapp*.log -Pattern "type=ERROR.*tag=ORDERS" ``` ```powershell # Context block around a match (2 lines before/after) Select-String -Path logs\*.log -Pattern "order_id=42\b" -Context 2,2 ``` -------------------------------- ### Pure JSON Configuration for ExeWatch and Console Appenders Source: https://www.danieleteti.it/loggerpro Leverages the auto-register pattern for a completely configuration-driven setup without extra registration calls. This JSON defines both console output and ExeWatch appender settings. ```json { "configVersion": 1, "appenders": [ { "type": "Console" }, { "type": "ExeWatch", "apiKey": "ew_win_xxxxxx", "customerId": "Acme Corp", "appVersion": "2.3.1", "anonymizeDeviceId": false } ] } ``` -------------------------------- ### Getting Current Log File Names with FileAppender Source: https://www.danieleteti.it/loggerpro Demonstrates how to retrieve log file names using TLoggerProFileAppender, which supports one file per tag. You can get the file name for a specific tag or all currently active log files. ```pascal var lAppender: TLoggerProFileAppender; begin lAppender := TLoggerProFileAppender.Create; // Get file for a specific tag lFileName := lAppender.GetCurrentLogFileName('ORDERS'); // Or all current log files lAllFiles := lAppender.GetAllCurrentLogFileNames; end; ``` -------------------------------- ### Loading LoggerPro Configuration from JSON File Source: https://www.danieleteti.it/loggerpro This snippet demonstrates how to initialize LoggerPro by loading its configuration directly from a specified JSON file, utilizing the auto-registration pattern. ```pascal uses LoggerPro, LoggerPro.ExeWatchAppender; Log := LoggerProFromJSONFile('loggerpro.json'); ``` -------------------------------- ### Log to Rotated File (Simple) Source: https://www.danieleteti.it/loggerpro Logs to a file in the EXE directory with default rotation settings (5 backups of 1MB). ```json { "appenders": [ { "type": "File" } ] } ``` -------------------------------- ### Loading Configuration from File or Resources Source: https://www.danieleteti.it/loggerpro Load LoggerPro configuration from an on-disk JSON file if it exists, otherwise fall back to a default configuration embedded in resources. Ensure the 'System.IOUtils' unit is included for file operations. ```pascal uses System.IOUtils; if TFile.Exists('loggerpro.json') then Log := LoggerProFromJSONFile('loggerpro.json') else Log := LoggerProFromJSONString(LoadDefaultConfigFromResources); ``` -------------------------------- ### Imperative Configuration for ExeWatch Appender Source: https://www.danieleteti.it/loggerpro This is the most straightforward method when configuration values are readily available in config objects. It directly instantiates the ExeWatch appender. ```pascal Log := LoggerProBuilder .WriteToAppender(NewExeWatchAppender( 'ew_win_xxxxxx', 'Acme Corp', '2.3.1')) .Build; ``` -------------------------------- ### Fluent Builder Configuration for ExeWatch Appender Source: https://www.danieleteti.it/loggerpro Use this method when API keys, customer IDs, and versions are known at compile time or available as simple global variables. It allows for a chained, readable configuration. ```pascal Log := WithExeWatch(LoggerProBuilder) .WithAPIKey('ew_win_xxxxxx') .WithCustomerId('Acme Corp') .WithAppVersion('2.3.1') .WithAnonymizeDeviceId(False) // True = per-install ID (GDPR-friendly) .Done .WriteToConsole.WithColors.Done // mirror to the console too .Build; ``` -------------------------------- ### Configure LoggerPro with JSON and FMX Memo Source: https://www.danieleteti.it/loggerpro Demonstrates initializing LoggerPro with JSON configuration and appending logs to an FMX TMemo using the cross-platform WriteToStrings appender. Configurable with max lines and clear on startup. ```delphi FLog := LoggerProBuilderFromJSONFile('loggerpro.json') .WriteToStrings(MemoLog.Lines) .WithMaxLogLines(500) .WithClearOnStartup(True) .Done .Build; ``` -------------------------------- ### Log to Console (Default) Source: https://www.danieleteti.it/loggerpro Logs to the console with default color settings (Midnight scheme). ```json { "appenders": [ { "type": "Console" } ] } ``` -------------------------------- ### Combined Console and File Logging Source: https://www.danieleteti.it/loggerpro Sets up both a colored console logger and a rotated file logger with different minimum levels for each. ```json { "minimumLevel": "Debug", "appenders": [ { "type": "Console", "colors": true, "colorScheme": "Midnight" }, { "type": "File", "logsFolder": "logs", "minimumLevel": "Info" } ] } ``` -------------------------------- ### Log to Console (Custom Color Scheme) Source: https://www.danieleteti.it/loggerpro Logs to the console using a specified color scheme like 'Nord'. ```json { "appenders": [ { "type": "Console", "colorScheme": "Nord" } ] } ``` -------------------------------- ### Configuring FileBySource Appender Source: https://www.danieleteti.it/loggerpro Set up LoggerPro to organize logs into per-source subfolders using the FileBySource appender. This is ideal for multi-tenant applications. Rotation is based on day and size, with automatic deletion of old files. ```delphi uses LoggerPro.Builder; Log := LoggerProBuilder .WriteToFileBySource .WithLogsFolder('logs') .WithMaxFileSizeInKB(5000) .WithRetainDays(30) .WithDefaultSource('default') .Done .Build; // Source comes from the context Log.Info('Order placed', 'ORDERS', [ LogParam.S('source', 'ClientA'), LogParam.I('order_id', 42) ]); // → logs/ClientA/ClientA.ORDERS.20260418.00.log ``` -------------------------------- ### Live Tailing Logs with Get-Content -Wait Source: https://www.danieleteti.it/loggerpro Use PowerShell's Get-Content -Wait for live tailing log files. Note that this method does not follow LoggerPro's daily/size rotation. ```powershell Get-Content logs\myapp.20260418.log -Wait -Tail 20 ``` -------------------------------- ### Log to Rotated File (Customized) Source: https://www.danieleteti.it/loggerpro Logs to a specified folder with custom file naming, backup count, and size limits. ```json { "appenders": [ { "type": "File", "logsFolder": "C:/ProgramData/MyApp/logs", "fileBaseName": "myapp", "maxBackupFiles": 30, "maxFileSizeInKB": 5000 } ] } ``` -------------------------------- ### Log to Console (Level Badges) Source: https://www.danieleteti.it/loggerpro Enables level badges for faster scanning in the console output. ```json { "appenders": [ { "type": "Console", "colors": true, "colorScheme": "GinBadge" } ] } ``` -------------------------------- ### Log to Console (Specific Scheme) Source: https://www.danieleteti.it/loggerpro Configures the console appender to use a specific color scheme, such as 'Nord'. ```json { "appenders": [ { "type": "Console", "colors": true, "colorScheme": "Nord" } ] } ``` -------------------------------- ### Configuring HTML Live Log Viewer Source: https://www.danieleteti.it/loggerpro Configure LoggerPro to output logs to a self-contained HTML file. This viewer includes a sticky filter bar, row coloring, context rendering, export options, and live tailing capabilities. ```delphi uses LoggerPro, LoggerPro.Builder; Log := LoggerProBuilder .WriteToHTMLFile .WithLogsFolder('logs') .WithFileBaseName('myapp') .WithTitle('MyApp - Operations Log') .WithMaxFileSizeInKB(1000) .WithMaxBackupFiles(10) .Done .Build; ``` -------------------------------- ### Build LoggerPro with JSON Base and Code Appenders Source: https://www.danieleteti.it/loggerpro Use LoggerProBuilderFromJSONFile to load base configuration from JSON and then chain additional appenders programmatically. Call .Build to finalize the logger. ```delphi uses LoggerPro, LoggerPro.Builder; // 2. JSON base + more appenders from code (the "mixed" pattern) Log := LoggerProBuilderFromJSONFile('loggerpro.json') .WriteToCallback .WithCallback(MyProc) .Done .Build; // you call .Build yourself ``` -------------------------------- ### Console Appender with Optional Fields Source: https://www.danieleteti.it/loggerpro Configures the console appender with additional options like a custom prefix and UTF-8 output. ```json { "appenders": [ { "type": "Console", "colors": true, "colorScheme": "Nord", "prefix": "MYAPP", // shows as [MYAPP] before each line "utf8Output": true // safe output in Docker / Windows consoles } ] } ``` -------------------------------- ### DLL-Safe Initialization Source: https://www.danieleteti.it/loggerpro Initializes LoggerPro safely within a DLL context to prevent deadlocks. Ensure to call GLog.Shutdown before DLL unload if flushing is critical. ```delphi library MyPlugin; uses LoggerPro, LoggerPro.Builder; var GLog: ILogWriter; begin // Safe during DLL_PROCESS_ATTACH GLog := LoggerProBuilder .WriteToFile.Done .Build; GLog.Info('DLL loaded successfully'); end. ``` -------------------------------- ### Configure Console Colors via Code Source: https://www.danieleteti.it/loggerpro Sets the console color scheme programmatically using LoggerPro's builder API. ```delphi uses LoggerPro, LoggerPro.Builder; Log := LoggerProBuilder .WriteToConsole .WithColorScheme(LogColorSchemes.Midnight) // or .Nord / .Matrix / ... .Done .Build; ``` -------------------------------- ### LoggerPro Configuration Schema Source: https://www.danieleteti.it/loggerpro Defines the structure for LoggerPro configuration, including global settings and appender definitions. Use this to set up logging behavior, such as minimum severity levels and output destinations. ```json { "configVersion": 1, "minimumLevel": "Debug", "defaultMinimumLevel": "Warning", "defaultTag": "myapp", "appenders": [ { "type": "Console", "colors": true, "colorScheme": "Midnight" }, { "type": "File", "logsFolder": "logs", "maxBackupFiles": 5, "minimumLevel": "Debug" }, { "type": "HTMLFile", "logsFolder": "logs", "title": "MyApp" } ] } ``` -------------------------------- ### Log to Console (Monochrome) Source: https://www.danieleteti.it/loggerpro Forces plain text output for the console appender, useful for tests or file redirection. ```json { "appenders": [ { "type": "Console", "colors": true, "colorScheme": "Monochrome" } ] } ``` -------------------------------- ### Initialize LoggerPro from JSON String Source: https://www.danieleteti.it/loggerpro Use LoggerProFromJSONString to initialize LoggerPro from a configuration string, useful for embedded configurations or dynamically generated settings. ```delphi uses LoggerPro; // 1b. Pure JSON from an embedded resource or a hand-assembled string Log := LoggerProFromJSONString(MyEmbeddedConfig); ``` -------------------------------- ### Log to Console (Opt-out of Colors) Source: https://www.danieleteti.it/loggerpro Disables console colors by setting 'colorScheme' to null, an empty string, or 'colors' to false. ```json { "appenders": [ { "type": "Console", "colorScheme": null } ] } ``` ```json { "appenders": [ { "type": "Console", "colorScheme": "" } ] } ``` ```json { "appenders": [ { "type": "Console", "colors": false } ] } ``` -------------------------------- ### UDP Syslog Configuration with Local Time Option Source: https://www.danieleteti.it/loggerpro Configure LoggerPro to send logs via UDP Syslog, including an option to use local time instead of the default UTC, which is mandated by RFC 5424 but often not expected by on-premise servers. ```pascal Log := LoggerProBuilder .WriteToUDPSyslog .WithHost('syslog.example.com') .WithPort(514) .WithApplication('MyApp') .WithUseLocalTime(True) // default: False (UTC) .Done .Build; ``` -------------------------------- ### ElasticSearch with Basic Authentication Source: https://www.danieleteti.it/loggerpro Configures LoggerPro to send logs to ElasticSearch using Basic Authentication. Requires specifying the URL and credentials. ```delphi // Basic Auth Log := LoggerProBuilder .WriteToElasticSearch .WithURL('https://elastic.example.com:9200/logs/_doc') .WithBasicAuth('username', 'password') .Done .Build; ``` -------------------------------- ### Pretty-print logs using humanlog Source: https://www.danieleteti.it/loggerpro Pipe log file content to the humanlog command to pretty-print and colorize the output. This is useful for human readability. ```powershell # Pretty-print a static log file Get-Content logs\myapp.20260418.log | humanlog ``` -------------------------------- ### Graceful Fallback Logger Implementation Source: https://www.danieleteti.it/loggerpro Implement a safe logger builder that catches configuration errors and falls back to a default console logger with informational level logging. This prevents application crashes due to misconfigurations. ```pascal uses LoggerPro, LoggerPro.Builder; function BuildLoggerSafe(const aConfigPath: string): ILogWriter; begin try Result := LoggerProFromJSONFile(aConfigPath); except on E: ELoggerProConfigError do begin Result := LoggerProBuilder .WriteToConsole.Done .WithMinimumLevel(TLogType.Info) .Build; Result.Warn( Format('Config fallback: %s', [E.Message]), 'CONFIG'); end; end; end; ``` -------------------------------- ### Ad-hoc Contextual Logging Source: https://www.danieleteti.it/loggerpro Enriches a single log call with key-value pairs using WithProperty. Useful for transient context specific to one message. ```delphi Log.WithProperty('order_id', 12345) .WithProperty('amount', 99.99) .Info('Order processed', 'orders'); ``` -------------------------------- ### Handling Schema Version Too New Error Source: https://www.danieleteti.it/loggerpro This error indicates that the configuration file uses a newer schema version than the current LoggerPro library supports. Update the LoggerPro library to a version compatible with the configuration schema. ```text configVersion 2 is newer than supported (max 1). Update LoggerPro. ``` -------------------------------- ### Log Messages at Different Levels Source: https://www.danieleteti.it/loggerpro Demonstrates logging messages at various severity levels, from Debug to Fatal. Each level corresponds to a specific TLogType. ```delphi Log.Debug('Detailed debug information'); // TLogType.Debug Log.Info('General information'); // TLogType.Info Log.Warn('Warning conditions'); // TLogType.Warning Log.Error('Error conditions'); // TLogType.Error Log.Fatal('Critical failures'); // TLogType.Fatal ``` -------------------------------- ### Configure LogFmt Renderer via Builder Source: https://www.danieleteti.it/loggerpro Enable the LogFmt renderer for console and file appenders using the LoggerPro Builder API. This approach allows for per-appender configuration of renderers. ```delphi uses LoggerPro, LoggerPro.Builder, LoggerPro.Renderers; Log := LoggerProBuilder .WriteToConsole .WithRenderer(TLogItemRendererLogFmt.Create) .Done .WriteToFile .WithRenderer(TLogItemRendererLogFmt.Create) .Done .Build; Log.Info('order placed', 'ORDERS', [ LogParam.I('order_id', 42), LogParam.F('amount', 99.95), LogParam.B('paid', True) ]); ``` -------------------------------- ### ElasticSearch with API Key Authentication Source: https://www.danieleteti.it/loggerpro Configures LoggerPro to send logs to ElasticSearch using an API Key. Requires specifying the host, port, index, and API key. ```delphi // API Key Log := LoggerProBuilder .WriteToElasticSearch .WithHost('https://elastic.example.com') .WithPort(9200) .WithIndex('app-logs') .WithAPIKey('your-api-key-here') .Done .Build; ``` -------------------------------- ### Configure LoggerPro with JSON and FireDAC Database Appender Source: https://www.danieleteti.it/loggerpro This snippet shows how to configure LoggerPro with a JSON base and add a FireDAC database appender. It specifies connection details, stored procedure name, and minimum logging level for the database. ```delphi uses LoggerPro, LoggerPro.Builder, LoggerPro.DBAppender.FireDAC; FLog := LoggerProBuilderFromJSONFile('loggerpro.json') .WriteToFireDAC .WithConnectionDefName('MAIN_DB') .WithStoredProcName('sp_insert_log') .WithMinimumLevel(TLogType.Warning) // DB only gets Warning+ .Done .Build; ``` -------------------------------- ### Write to Windows Event Log for Services Source: https://www.danieleteti.it/loggerpro Configures the logger for Windows Services, writing to the Event Log and a file. Requires passing the service instance. ```delphi procedure TMyService.ServiceCreate(Sender: TObject); begin FLog := LoggerProBuilder .WriteToWindowsEventLogForService(Self) .Done .WriteToFile .WithLogsFolder('C:\ProgramData\MyService\Logs') .Done .Build; end; ``` -------------------------------- ### Emit LogFmt Output Source: https://www.danieleteti.it/loggerpro Configure LoggerPro to use the LogFmt renderer for console output. This allows for structured logging output compatible with LogFmt. ```delphi .WriteToConsole.WithRenderer(TLogItemRendererLogFmt.Create).Done ``` -------------------------------- ### Per-Appender Minimum Level Configuration Source: https://www.danieleteti.it/loggerpro Configure different minimum logging levels for each appender independently of the root logger. This allows fine-grained control over message routing, ensuring only relevant messages reach specific destinations. ```json { "minimumLevel": "Debug", "appenders": [ { "type": "Console", "minimumLevel": "Debug" }, { "type": "File", "logsFolder": "logs", "minimumLevel": "Info" }, { "type": "Webhook", "url": "https://ops/alerts", "minimumLevel": "Error" } ] } ``` -------------------------------- ### Create Custom Console Color Scheme Source: https://www.danieleteti.it/loggerpro Defines a custom color scheme by modifying an existing one, such as changing tag and level colors. ```delphi var lScheme: TLogColorScheme; begin lScheme := LogColorSchemes.Midnight; lScheme.TagColor := FORE_YELLOW; lScheme.LevelColor[TLogType.Info] := STYLE_BRIGHT + FORE_WHITE; Log := LoggerProBuilder .WriteToConsole.WithColorScheme(lScheme).Done .Build; end; ``` -------------------------------- ### Ignore context keys using humanlog Source: https://www.danieleteti.it/loggerpro Use humanlog's '--ignore' option to hide specific context keys from the output, reducing noise and focusing on relevant information. ```powershell # Hide noisy context keys Get-Content logs\*.log | humanlog --ignore "threadid,time" ``` -------------------------------- ### Enable Pluggable Appenders in Delphi Source: https://www.danieleteti.it/loggerpro Include the necessary units in your Delphi project's uses clause to enable specific appenders like ExeWatch, WindowsEventLog, and ElasticSearch. This allows these appenders to be registered via their JSON factory configuration. ```delphi uses LoggerPro, LoggerPro.ExeWatchAppender, // enables "type": "ExeWatch" LoggerPro.WindowsEventLogAppender, // enables "type": "WindowsEventLog" LoggerPro.ElasticSearchAppender; // enables "type": "ElasticSearch" begin Log := LoggerProFromJSONFile('loggerpro.json'); end. ``` -------------------------------- ### Write to Windows Event Log for Regular Applications Source: https://www.danieleteti.it/loggerpro Configures the logger to write to the Windows Event Log for regular applications. Sets the source name and minimum logging level. ```delphi Log := LoggerProBuilder .WriteToWindowsEventLog .WithSourceName('MyApplication') .WithMinimumLevel(TLogType.Warning) .Done .Build; ``` -------------------------------- ### Application Shutdown Procedure for LoggerPro Source: https://www.danieleteti.it/loggerpro This procedure should be called in your application's finalization section to ensure all pending log messages are written before the application exits. It flushes the queue, stops the logger thread, and handles subsequent log calls gracefully. ```pascal procedure TMyApp.Finalize; begin Log.Shutdown; // Flush queue, stop thread Log := nil; end; ``` -------------------------------- ### Handling Unknown Field Error Source: https://www.danieleteti.it/loggerpro This error message indicates a typo in a configuration field. Verify the field name against the valid options for the specified appender type. ```text appenders[0] (type=Console): unknown field "colour". Valid fields: minimumLevel, colors, colorScheme, prefix, utf8Output. ``` -------------------------------- ### Globally Disabled Logging Configuration Source: https://www.danieleteti.it/loggerpro Effectively disable all logging by setting a high 'minimumLevel' (e.g., 'Fatal') when the 'appenders' array is empty. This ensures no messages are processed. ```json { "configVersion": 1, "minimumLevel": "Fatal", "appenders": [] } ``` -------------------------------- ### Sub-logger with Default Tag Source: https://www.danieleteti.it/loggerpro Creates a new logger instance that automatically prefixes all its messages with a specified tag. Useful for organizing logs by module or feature. ```delphi var OrderLog: ILogWriter; begin OrderLog := Log.WithDefaultTag('ORDERS'); OrderLog.Info('Processing started'); // tag = 'ORDERS' OrderLog.Warn('Stock low'); // tag = 'ORDERS' end; ``` -------------------------------- ### Pipe Delphi app output to humanlog Source: https://www.danieleteti.it/loggerpro Pipe the standard output of a Delphi console application directly to humanlog for real-time log processing and pretty-printing. Assumes the appender is configured for logfmt. ```powershell # Pipe directly from your Delphi app's stdout (console appender + logfmt) .\MyApp.exe | humanlog ``` -------------------------------- ### Clone LoggerPro Repository Source: https://www.danieleteti.it/loggerpro Clone the LoggerPro repository to contribute or test unreleased features. Ensure to add the root folder and 'contrib' to your Delphi Library Path. Note that the master branch may be unstable. ```bash git clone https://github.com/danieleteti/loggerpro.git ``` -------------------------------- ### Exception Logging Source: https://www.danieleteti.it/loggerpro Logs exceptions using Log.LogException. Overloads allow logging the exception only, with a message, or with a message and a tag. ```delphi try // Code that may raise except on E: Exception do begin Log.LogException(E); Log.LogException(E, 'Database query failed'); Log.LogException(E, 'Query failed', 'db'); end; end; ``` -------------------------------- ### Log to Windows Event Log from a Windows Service Source: https://www.danieleteti.it/loggerpro Configure LoggerPro to log to the Windows Event Log specifically for a Windows Service. Pass the TService instance to the WriteToWindowsEventLogForService method to ensure correct logging behavior in service environments. ```delphi FLog := LoggerProBuilder .WriteToWindowsEventLogForService(Self).Done .Build; ``` -------------------------------- ### Enable UTF-8 Console Output in Docker Source: https://www.danieleteti.it/loggerpro Configure LoggerPro to write UTF-8 bytes directly to stdout, bypassing Delphi's locale conversion. This is essential for correct UTF-8 output in Docker containers. ```delphi .WriteToConsole.WithUTF8Output.Done ``` -------------------------------- ### Empty Appenders Array Configuration Source: https://www.danieleteti.it/loggerpro An empty 'appenders' array results in a 'black hole' logger, which is useful for integration tests where logging is not required. ```json { "configVersion": 1, "appenders": [] } ``` -------------------------------- ### Logger with Persistent Context Source: https://www.danieleteti.it/loggerpro Creates a logger instance that automatically includes a set of key-value pairs with every log message. Ideal for request-specific or session-specific context. ```delphi var RequestLog: ILogWriter; begin RequestLog := Log.WithDefaultContext([ LogParam.S('request_id', 'req-123'), LogParam.S('client_ip', '192.168.1.100') ]); RequestLog.Info('Request received'); // includes request_id, client_ip RequestLog.Info('Response sent'); // includes request_id, client_ip end; ``` -------------------------------- ### Log with Inline Structured Context Source: https://www.danieleteti.it/loggerpro Pass structured context directly within the logging call. This method allows for flexible logging of detailed information. ```delphi Log.Info('msg', 'tag', [LogParam.I('id', 42)]) ``` -------------------------------- ### Add Persistent Context to Logs Source: https://www.danieleteti.it/loggerpro Set default context that will be included with all subsequent log messages. Use WithDefaultContext to provide a list of properties that will be automatically added. ```delphi Log.WithDefaultContext([...]) ``` -------------------------------- ### Filter logs for errors using humanlog Source: https://www.danieleteti.it/loggerpro Use humanlog's filtering capabilities with the '--skip' option to display only log lines that do not match the specified criteria (e.g., show only errors). ```powershell # Filter: only errors (mini-expression language) Get-Content logs\*.log | humanlog --skip "type!=ERROR" ``` -------------------------------- ### Stack Trace Formatter Integration Source: https://www.danieleteti.it/loggerpro Configures LoggerPro to use a custom stack trace formatter, such as one from JCL, madExcept, or EurekaLog. This allows detailed exception information to be captured. ```delphi Log := LoggerProBuilder .WithStackTraceFormatter( function(E: Exception): string begin Result := JclLastExceptStackListToString; end) .WriteToFile.Done .Build; ``` -------------------------------- ### ElasticSearch with Bearer Token Authentication Source: https://www.danieleteti.it/loggerpro Configures LoggerPro to send logs to ElasticSearch using a Bearer Token (e.g., JWT, OAuth2). Requires specifying the URL and the token. ```delphi // Bearer Token (JWT, OAuth2) Log := LoggerProBuilder .WriteToElasticSearch .WithURL('https://elastic.example.com:9200/logs/_doc') .WithBearerToken('your-jwt-token') .Done .Build; ``` -------------------------------- ### Handling Unknown Appender Type Error Source: https://www.danieleteti.it/loggerpro This error occurs when an appender type is specified but its corresponding unit is not included in the 'uses' clause. Ensure all necessary appender units are registered. ```text appenders[1]: unknown type "ExeWatch". Currently registered types: console, elasticsearch, file, filebysource, htmlfile, jsonlfile, memory, outputdebugstring, simpleconsole, timerotatingfile, udpsyslog, webhook. If you want "ExeWatch", make sure the unit that registers it is in your `uses` clause (typically LoggerPro.ExeWatchAppender) - optional appenders self-register from their initialization section, so simply including the unit is enough. For custom factories use TLoggerProConfig.RegisterAppenderType. ``` -------------------------------- ### Structured Context Inline Logging Source: https://www.danieleteti.it/loggerpro Logs a message with structured context provided as an array of LogParam objects directly in the log call. Supports various data types. ```delphi Log.Info('Order completed', 'ORDERS', [ LogParam.I('order_id', 12345), LogParam.S('customer', 'John Doe'), LogParam.F('total', 299.99), LogParam.B('paid', True) ]); ``` -------------------------------- ### Query logs for a specific order ID using ripgrep Source: https://www.danieleteti.it/loggerpro Use ripgrep to search for log lines containing a specific order ID, regardless of the log level. The \b ensures a whole word match for the order ID. ```bash # One specific order, any log level rg "order_id=42\b" logs\myapp*.log ``` -------------------------------- ### Set LogFmt as Default Renderer Source: https://www.danieleteti.it/loggerpro Globally set the TLogItemRendererLogFmt as the default log item renderer for all appenders. This is a simpler alternative to configuring each appender individually. ```delphi LoggerPro.Renderers.gDefaultLogItemRenderer := TLogItemRendererLogFmt; ``` -------------------------------- ### Query errors for a user in the latest log file using ripgrep Source: https://www.danieleteti.it/loggerpro Use ripgrep in combination with PowerShell commands to find errors for a specific user within the most recently modified log file. ```powershell # Errors for a given user in the last file only rg "type=ERROR.*user_id=7" (Get-ChildItem logs\myapp*.log | Sort LastWriteTime -Desc | Select -First 1).FullName ``` -------------------------------- ### Add Ad-hoc Context to Logs Source: https://www.danieleteti.it/loggerpro Add temporary context to a specific log message using the WithProperty method. This is useful for logging unique details for a single event. ```delphi Log.WithProperty('key', value).Info('msg') ``` -------------------------------- ### Enabling UTF-8 Console Output Source: https://www.danieleteti.it/loggerpro Enable UTF-8 output for console loggers to correctly handle non-ASCII characters in Docker containers and Windows consoles. This ensures proper rendering of Unicode text. ```delphi Log := LoggerProBuilder .WriteToConsole .WithUTF8Output .Done .Build; ``` ```delphi // Also available for the plain (no-color) console appender Log := LoggerProBuilder .WriteToSimpleConsole .WithUTF8Output .Done .Build; ``` -------------------------------- ### Runtime Minimum Level Override Source: https://www.danieleteti.it/loggerpro Override the global minimum logging level at runtime by directly modifying the 'MinimumLevel' property of the logger. This provides a dynamic way to control logging verbosity. ```pascal Log.MinimumLevel := TLogType.Fatal; ``` -------------------------------- ### Minimum Level Filtering Configuration Source: https://www.danieleteti.it/loggerpro Sets a global minimum log level using LoggerProBuilder. Messages below this level are filtered out with zero overhead. The level can be changed at runtime. ```delphi Log := LoggerProBuilder .WithMinimumLevel(TLogType.Warning) // Debug and Info filtered .WriteToFile.Done .Build; Log.Debug('Not logged'); // Filtered - no TLogItem created Log.Info('Not logged'); // Filtered - no TLogItem created Log.Warn('Logged'); // OK ``` ```delphi Log.MinimumLevel := TLogType.Fatal; // effectively mute // Later Log.MinimumLevel := TLogType.Debug; // re-enable everything ``` -------------------------------- ### Query logs for errors using ripgrep Source: https://www.danieleteti.it/loggerpro Use ripgrep to find all log lines containing 'type=ERROR' in log files matching a pattern. This demonstrates basic filtering capabilities. ```bash # All errors rg "type=ERROR" logs\myapp*.log ``` -------------------------------- ### Keep specific log records using humanlog Source: https://www.danieleteti.it/loggerpro Use humanlog's '--keep' option to filter log lines, retaining only those that satisfy the given boolean expression (e.g., specific tag and type). ```powershell # Keep only matching records Get-Content logs\*.log | humanlog --keep "tag=ORDERS and type=ERROR" ``` -------------------------------- ### Registering Custom Appender Type Source: https://www.danieleteti.it/loggerpro Register a custom appender type with LoggerPro by providing a factory procedure and a list of allowed configuration fields. This allows custom appenders to be configured via JSON. ```pascal uses LoggerPro, LoggerPro.Config; procedure MyCustomFactory(const aBuilder: ILoggerProBuilder; const aConfig: TJSONObject); begin aBuilder.WriteToAppender(TMyCustomAppender.Create( aConfig.GetValue('endpoint').Value)); end; initialization TLoggerProConfig.RegisterAppenderType( 'MyCustom', MyCustomFactory, ['minimumLevel', 'endpoint']); // closed set of allowed fields ``` -------------------------------- ### Count errors per tag using ripgrep Source: https://www.danieleteti.it/loggerpro Use ripgrep to extract tags from log lines, then use PowerShell's Group-Object to count the occurrences of each tag, sorted by count in descending order. ```powershell # Count errors per tag rg -o "tag=\S+" logs\myapp*.log | Group-Object | Sort Count -Desc ``` -------------------------------- ### Handling Invalid Enum Value Error Source: https://www.danieleteti.it/loggerpro This error occurs when an invalid value is provided for an enumerated configuration field, such as 'colorScheme'. Refer to the valid values listed in the error message. ```text appenders[0] (type=Console): invalid colorScheme "NEON". Valid values: Default, Monochrome, GinBadge, GinMinimal, GinVibrant, Midnight, Nord, Matrix, Amber, Ocean, Cyberpunk. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.