Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Catalog · How the catalog works
Anything · Lazarus or Delphi
Random projectRandom project

DFLoggerManager

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

View on GitHub

Member rating

No ratings yet.

Sign in to rate this project.

README

DFLoggerManager 📝

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
pascal
uses
  DFLoggerManager;

🎯 Quick Start

Basic Usage

pascal
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

pascal
// 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

Level Description Includes
llNormal Standard logging Notify, Warning, Error, Fatal
llVerbose Detailed logging Normal + Info
llDebug Full logging Verbose + Debug
pascal
Logger.LogLevel := llDebug;  // Show all log messages
Logger.LogLevel := llVerbose; // Show all except debug messages
Logger.LogLevel := llNormal;  // Show only important messages

Log Types

pascal
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

pascal
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:

pascal
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:

pascal
[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

Property Type Default Description
ModuleName String 'Application' Module identifier in log entries
LogMode TLogMode lmFile Output mode (File/Console/Both)
LogLevel TLogLevel llNormal Minimum log level to output
LogDirectory String './logs' Directory for log files
MaxLogFileSize Int64 10 MB Maximum size before rotation
MaxBackupFiles Integer 5 Number of backup files to keep
DateTimeFormat String 'yyyy-mm-dd hh:nn:ss' Timestamp format
LogFileExtension String '.log' Log file extension
EnableFallback Boolean True Enable fallback mechanism
FallbackMode TLogMode lmConsole Fallback output mode

🔒 Thread Safety

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

pascal
// 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:

pascal
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