Logging in Pascal

Here’s the translation of the Go logging example to Pascal, formatted in Markdown suitable for Hugo:

Our example demonstrates logging in Pascal using the standard WriteLn procedure and a custom logging unit. Here’s the full source code:

program LoggingExample;

uses
  SysUtils, DateUtils;

type
  TCustomLogger = class
  private
    FPrefix: string;
  public
    constructor Create(APrefix: string);
    procedure Log(const AMessage: string);
  end;

constructor TCustomLogger.Create(APrefix: string);
begin
  FPrefix := APrefix;
end;

procedure TCustomLogger.Log(const AMessage: string);
begin
  WriteLn(Format('%s %s: %s', [FormatDateTime('yyyy/mm/dd hh:nn:ss', Now), FPrefix, AMessage]));
end;

var
  MyLogger: TCustomLogger;

begin
  // Simple logging using WriteLn
  WriteLn('standard logger');

  // Logging with timestamp
  WriteLn(Format('%s standard logger with time', [FormatDateTime('yyyy/mm/dd hh:nn:ss', Now)]));

  // Logging with microseconds (not directly supported, using milliseconds instead)
  WriteLn(Format('%s.%d with milliseconds', [FormatDateTime('yyyy/mm/dd hh:nn:ss', Now), MilliSecondOf(Now)]));

  // Custom logger with prefix
  MyLogger := TCustomLogger.Create('my:');
  MyLogger.Log('from mylogger');

  // Change prefix
  MyLogger.FPrefix := 'ohmy:';
  MyLogger.Log('from mylogger');

  // In Pascal, we don't have built-in JSON logging, but you can implement it yourself
  // or use third-party libraries for structured logging

  MyLogger.Free;
end.

To run the program, save it as logging_example.pas and compile it using a Pascal compiler like Free Pascal:

$ fpc logging_example.pas
$ ./logging_example

Sample output; the date and time emitted will depend on when the example ran:

standard logger
2023/08/22 10:45:16 standard logger with time
2023/08/22 10:45:16.904 with milliseconds
my: 2023/08/22 10:45:16: from mylogger
ohmy: 2023/08/22 10:45:16: from mylogger

This Pascal example demonstrates basic logging concepts:

  1. Simple logging using WriteLn.
  2. Adding timestamps to log messages.
  3. Creating a custom logger with a prefix.
  4. Changing the prefix of the custom logger.

Note that Pascal doesn’t have built-in structured logging or JSON output like the slog package in the original example. For such functionality, you would need to implement it yourself or use third-party libraries.

Also, Pascal doesn’t have microsecond precision for timestamps out of the box, so we used milliseconds instead. If you need microsecond precision, you’d need to use platform-specific functions or external libraries.

This example provides a starting point for logging in Pascal programs, which you can extend based on your specific needs.