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
Download theย
DFLoggerManager.pasย unitAdd it to your project's uses clause
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 messagesLog 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 infoAdvanced 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:
Fork the repository
Create a feature branch
Add tests for new functionality
Ensure all tests pass
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
