Skip to content

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

License

Notifications You must be signed in to change notification settings

delphifanforum/DFLoggerManager

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

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

Level Description Includes
llNormal Standard logging Notify, Warning, Error, Fatal
llVerbose Detailed logging Normal + Info
llDebug Full logging Verbose + 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

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:

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

About

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

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages