Log4D is a log framework based on the popular Java logging framework Log4J. The information on CodeCentral describes the general architecture:

“It is a port of the log4j Java package to Delphi – runtime configurable logging with a hierarchy of categories, each individually controllable.

  • Categories form the basis of the hierarchy, logging messages sent to them based on the message’s priority, and sending them to defined appenders.
  • Appenders encapsulate a destination for logging messages, such as debugging output, a file, e-mail, etc. They can be attached to multiple categories and/or have multiple categories sending to them.
  • Layouts determine how the message is formatted for output, such as just the message, a pattern of several message fields, HTML table, XML, etc. These are associated with appenders.
  • Filters provide fine-grained acceptance of messages per appender. Object renderers let you log objects rather than just strings.
  • Configurators let you establish the hierarchy and associated appenders at runtime. Details can be kept in an .INI style file or in an XML document. Changes to the hierarchy do not require a recompile.

Adding logging to a program takes only a few lines.

Log4D includes ready to use log appender classes, including RollingFileAppender, ODSAppender (using OutputDebugString), and StreamAppender. For users of Internet Direct (Indy), it also offers SMTP and Socket (UDP) appender classes. Writing custom appender classes is easy.

Help files are available online at http://cc.embarcadero.com/item/16446.

The following example project creates a ODS appender. If you run it in the IDE, the log messages will appear in the ‘Event log’ window.

program Log4Dexample;

{$APPTYPE CONSOLE}

uses
  Log4D,
  SysUtils;

var
  Logger: TLogLogger;

begin
  try
    // basic configuration - creates a TLogODSAppender 
    // (ODS = OutputDebugString)
    TLogBasicConfigurator.Configure;

    // set the log level
    TLogLogger.GetRootLogger.Level := Trace;

    // create a named logger
    Logger := TLogLogger.GetLogger('exampleLogger');

    // write log messages
    Logger.Fatal('fatal output');
    Logger.Error('error output');
    Logger.Warn('warn output');
    Logger.Info('info output');
    Logger.Debug('debug output');
    Logger.Trace('trace output');

    ReadLn;

  except
    on E:Exception do
    begin
      Writeln(E.Classname, ': ', E.Message);
      ReadLn;
    end;
  end;
end.

Discover more from Habarisoft Blog

Subscribe to get the latest posts sent to your email.

2 thoughts on “Delphi and Free Pascal logging with the Log4D library

  1. Hi, thanks for this example it was helpful. I had to make a couple small changes to get this to compile though. “Trace” didn’t seem to be a supported level in the Log4D package I downloaded. So I had to take out the Logger.Trace line, and change GetRootLogger.level to All instead of Trace.

Leave a Reply

Your email address will not be published. Required fields are marked *