DFLoggerManager Library

DFLoggerManager Library

Jun 12, 2025

A robust, feature-rich logging utility for Pascal/Delphi applications with support for multiple output modes, log rotation, and flexible configuration.

๐Ÿš€ Features

  • Multiple Output Modes: File, Console, or Both simultaneously

  • Log Levels: Normal, Verbose, and Debug with intelligent filtering

  • Automatic Log Rotation: Prevents log files from growing too large

  • Fallback Mechanism: Automatic fallback to console when file logging fails

  • Formatted Logging: Support for formatted strings with parameters

  • Configurable: Customizable file sizes, backup counts, date formats, and more

  • Thread-Safe Design: Safe for use in multi-threaded applications

  • Memory Efficient: Proper resource management and cleanup

๐Ÿ“‹ Requirements

  • Lazarus/Free Pascalย orย Delphi

  • Dependencies: SysUtils, Classes, LazFileUtils, DateUtils

๐Ÿ”ง Installation

  1. Download theย DFLoggerManager.pasย unit

  2. Add it to your project's uses clause

  3. Include the unit path in your project settings

uses
  DFLoggerManager;

๐ŸŽฏ Quick Start

Basic Usage

program LogExample;

uses
  DFLoggerManager;

var
  Logger: TDFLoggerManager;
begin
  // Create logger instance
  Logger := TDFLoggerManager.Create(lmFile);
  try
    // Configure logger
    Logger.ModuleName := 'MyApp';
    Logger.LogLevel := llVerbose;
    Logger.LogDirectory := 'C:\MyApp\Logs';
    
    // Write different types of log messages
    Logger.WriteInfo('Application started successfully');
    Logger.WriteWarning('Configuration file not found, using defaults');
    Logger.WriteError('Database connection failed');
    Logger.WriteDebug('Variable X = 42');
    
    // Use formatted logging
    Logger.WriteLogF(ltInfo, 'User %s logged in from IP %s', ['John', '192.168.1.1']);
    
  finally
    Logger.Free;
  end;
end.

๐Ÿ“– Detailed Usage

Log Modes

// File logging only
Logger := TDFLoggerManager.Create(lmFile);

// Console logging only  
Logger := TDFLoggerManager.Create(lmConsole);

// Both file and console logging
Logger := TDFLoggerManager.Create(lmBoth);

Log Levels

LevelDescriptionIncludesllNormalStandard loggingNotify, Warning, Error, FatalllVerboseDetailed loggingNormal + InfollDebugFull loggingVerbose + Debug

Logger.LogLevel := llDebug;  // Show all log messages
Logger.LogLevel := llVerbose; // Show all except debug messages
Logger.LogLevel := llNormal;  // Show only important messages

Log Types

Logger.WriteNotify('System notification');     // General notifications
Logger.WriteInfo('Informational message');     // Information
Logger.WriteWarning('Warning message');        // Warnings
Logger.WriteError('Error occurred');           // Errors
Logger.WriteFatalError('Critical failure');    // Fatal errors
Logger.WriteDebug('Debug information');        // Debug info

Advanced Configuration

Logger := TDFLoggerManager.Create(lmFile);

// Configure module name (appears in log entries)
Logger.ModuleName := 'DatabaseModule';

// Set custom log directory
Logger.LogDirectory := 'D:\ApplicationLogs\MyApp';

// Configure log rotation
Logger.MaxLogFileSize := 5 * 1024 * 1024;  // 5 MB
Logger.MaxBackupFiles := 10;                // Keep 10 backup files

// Custom date/time format
Logger.DateTimeFormat := 'dd/mm/yyyy hh:nn:ss';

// Custom file extension
Logger.LogFileExtension := '.txt';

// Enable fallback to console if file logging fails
Logger.EnableFallback := True;
Logger.FallbackMode := lmConsole;

๐Ÿ“ File Structure

With default settings, your log files will be organized like this:

logs/
โ”œโ”€โ”€ MyApp.log           (current log file)
โ”œโ”€โ”€ MyApp-1.log         (most recent backup)
โ”œโ”€โ”€ MyApp-2.log         (older backup)
โ””โ”€โ”€ MyApp-3.log         (oldest backup)

๐Ÿ”„ Log Rotation

Log rotation happens automatically when:

  • Current log file exceedsย MaxLogFileSizeย (default: 10 MB)

  • Keepsย MaxBackupFilesย number of backups (default: 5)

  • Older backups are automatically deleted

๐Ÿ“ Log Format

Default log entry format:

[2024-06-12 14:30:15] MyApp - [INFO] User authentication successful
[2024-06-12 14:30:16] MyApp - [WARNING] Memory usage high: 85%
[2024-06-12 14:30:17] MyApp - [ERROR] Database query timeout

๐Ÿ› ๏ธ Configuration Properties

PropertyTypeDefaultDescriptionModuleNameString'Application'Module identifier in log entriesLogModeTLogModelmFileOutput mode (File/Console/Both)LogLevelTLogLevelllNormalMinimum log level to outputLogDirectoryString'./logs'Directory for log filesMaxLogFileSizeInt6410 MBMaximum size before rotationMaxBackupFilesInteger5Number of backup files to keepDateTimeFormatString'yyyy-mm-dd hh:nn:ss'Timestamp formatLogFileExtensionString'.log'Log file extensionEnableFallbackBooleanTrueEnable fallback mechanismFallbackModeTLogModelmConsoleFallback output mode

๐Ÿ”’ Thread Safety

DFLoggerManager is designed to be thread-safe. However, for high-concurrency applications, consider:

// Create one logger instance per thread, or
// Use a critical section for shared logger instances

var
  Logger: TDFLoggerManager;
  LoggerCS: TCriticalSection;

// In thread-safe logging procedure:
LoggerCS.Enter;
try
  Logger.WriteInfo('Thread-safe message');
finally
  LoggerCS.Leave;
end;

๐Ÿšจ Error Handling

The logger includes built-in error handling:

  • File Access Errors: Automatically falls back to console if enabled

  • Directory Creation: Creates directories automatically

  • Disk Space: Gracefully handles disk full scenarios

  • Permission Issues: Falls back to alternative logging methods

๐Ÿงช Testing

Example test cases:

procedure TestLogging;
var
  Logger: TDFLoggerManager;
begin
  Logger := TDFLoggerManager.Create(lmBoth);
  try
    Logger.ModuleName := 'TestModule';
    Logger.LogLevel := llDebug;
    
    // Test all log types
    Logger.WriteNotify('Test notification');
    Logger.WriteInfo('Test information');
    Logger.WriteWarning('Test warning');
    Logger.WriteError('Test error');
    Logger.WriteFatalError('Test fatal error');
    Logger.WriteDebug('Test debug message');
    
    // Test formatted logging
    Logger.WriteLogF(ltInfo, 'Test with parameters: %d, %s', [42, 'Hello']);
    
    WriteLn('All tests completed successfully!');
  finally
    Logger.Free;
  end;
end;

๐Ÿค Contributing

Contributions are welcome! Please:

  1. Fork the repository

  2. Create a feature branch

  3. Add tests for new functionality

  4. Ensure all tests pass

  5. Submit a pull request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ“ž Support

  • Issues: Report bugs or request features via GitHub Issues

  • Documentation: Check the wiki for advanced usage examples

  • Community: Join our discussions for help and tips

๐Ÿ”„ Version History

v2.0.0 (Current)

  • Complete rewrite with enhanced features

  • Added log rotation support

  • Improved error handling

  • Thread-safe design

  • Multiple output modes

v1.0.0 (Legacy)

  • Basic file and console logging

  • Simple log levels

  • Portuguese language support

๐Ÿ™ Acknowledgments

  • Thanks to the Free Pascal and Lazarus communities

  • Inspired by popular logging frameworks

  • Built with reliability and performance in mind


Made with โค๏ธ for the Pascal/Delphi community

https://github.com/delphifanforum/DFLoggerManager

Enjoy this post?

Buy DelphiFan Forum a coffee

More from DelphiFan Forum