Sign in Join

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

Catalog · How the catalog works

Random project

LogManager

Delphi/Object Pascal minimal library for logging that i created for use on my projects

View on GitHub

Anyone may press Interesting, signed in or not. It helps others find this project.

Member rating

No ratings yet.

Sign in to rate this project.

README

📝 LogManager

A lightweight, single-unit logging library for Free Pascal / Lazarus.


📖 Overview

LogManager is a drop-in Pascal unit that provides a single class, TLogManager, for writing timestamped log entries to a file or to the console. It supports:

  • 🎚️ Log levels (Normal, Verbose, Debug) that filter which messages are written
  • 🏷️ Log types (Notify, Info, Warning, Error, FatalError, Debug)
  • 🔄 Automatic log rotation once a log file reaches a configurable size (LogMaxSize, 10 MB by default)
  • 🛟 Fallback output to the console if writing to the log file fails
  • 🌍 Cross-platform paths via DirectorySeparator and LazFileUtils

📦 Requirements

Requirement Notes
Free Pascal Any recent 3.x compiler
LazUtils package Provides LazFileUtils (RenameFileUTF8). Ships with Lazarus.
RTL units SysUtils, Classes

🚀 Installation

  1. Copy logmanager.pas into your project (or add its folder to the unit search path).
  2. In Lazarus, add LazUtils as a required package: Project → Project Inspector → Add → New Requirement → LazUtils.
  3. Add LogManager to your uses clause. The unit sets {$mode objfpc}{$H+} itself, so it also builds with plain fpc.
pascal
uses
  LogManager;

⚡ Quick start

pascal
program Demo;

uses
  SysUtils, LogManager;

var
  Log: TLogManager;
begin
  Log := TLogManager.Create(lmFile);
  try
    Log.Module       := 'MyApp';              // file name will be MyApp.log
    // LogDirectory defaults to the application's directory
    Log.LogLevel     := llVerbose;
    Log.LogMaxSize   := 5 * 1024 * 1024;     // rotate at 5 MB (default 10 MB)
    Log.Fallback     := True;                 // fall back to console on file errors

    Log.WriteLog(ltInfo,    'Application started');
    Log.WriteLog(ltWarning, 'Config file not found, using defaults');
    Log.WriteLog(ltDebug,   'Not written: level is Verbose');
    Log.WriteLog(ltError,   'Could not connect to database');
  finally
    Log.Free;
  end;
end.

Resulting MyApp.log:

text
[20/10/2026 15:45:01]MyApp- [Info] Application started
[20/10/2026 15:45:01]MyApp- [Warning] Config file not found, using defaults
[20/10/2026 15:45:01]MyApp- [Error] Could not connect to database

The timestamp is produced by DateTimeToStr(Now), so its format follows the system locale.


⚙️ How it works

Architecture

text
             ┌──────────────────────┐
  WriteLog ─▶│  LogMode?            │
             └─────┬──────────┬─────┘
             lmFile│          │lmConsole
                   ▼          ▼
           WriteLogFile   WriteLogConsole ──▶ stdout
                   │
        ┌──────────┴───────────┐
        │ file ≥ LogMaxSize?   │
        └──┬────────────────┬──┘
        yes│                │no
           ▼                ▼
   rename to Module-N.log   load file, append entry
   start a fresh file       save file
           │
     on exception ──▶ Fallback? ──▶ WriteLogConsole

Log levels

The LogLevel property decides which log types actually get written:

Log type ↓ / Level → llNormal llVerbose llDebug
ltNotify ✅ ✅ ✅
ltInfo ❌ ✅ ✅
ltWarning ✅ ✅ ✅
ltError ✅ ✅ ✅
ltFatalError ✅ ✅ ✅
ltDebug ❌ ❌ ✅

llNormal is the default.

File output

  • Log file path: <LogDirectory>/<Module>.log. LogDirectory defaults to the directory of the running executable, resolved from ParamStr(0), which works on every platform. The directory is not created automatically.
  • On every write, the existing file is loaded into an internal TStringList, the new line is appended, and the file is saved back.
  • Entry format: [<timestamp>]<Module>- [<Type>] <message>

Log rotation

Before writing, the file size is checked. If it is ≥ LogMaxSize bytes (default 10 * 1024 * 1024 = 10,485,760 bytes, 10 MB):

  1. The current file is renamed to the first free name among <Module>-1.log, <Module>-2.log, … <Module>-2048.log.
  2. The new entry is written to a fresh <Module>.log.

Fallback

If an exception occurs while writing the log file and Fallback = True:

FallbackMode Behaviour
lmConsole (default) The message is written to the console instead
lmFile Nothing happens (the entry is dropped)

Console output

  • WriteLog with LogMode = lmConsole prints [<timestamp>]<Module>-<Type><message> via WriteLn.
  • WriteLogAndConsole prints a short, Portuguese-labelled line to the console and, when LogMode = lmFile, also writes the entry to the log file. Both respect LogLevel. In lmConsole mode each message is printed once.
    Type
    ltNotify
    ltInfo
    ltWarning
    ltError
    ltFatalError
    ltDebug

📚 API reference

Types

pascal
TLogMode  = (lmFile = 1, lmConsole = 2);
TLogType  = (ltNotify = 0, ltInfo = 1, ltWarning = 2, ltError = 3,
             ltFatalError = 4, ltDebug = 5);
TLogLevel = (llNormal = 0, llVerbose = 1, llDebug = 2);

TLogManager

Member Kind Description
Create(LogMode: TLogMode) constructor Creates the logger with the given output mode
Destroy destructor Frees the internal buffer (call Free as usual)
Module: String property Module name; used in each entry and as the log file name
LogDirectory: String property Directory where <Module>.log is written (default: the application's directory)
LogMaxSize: Int64 property Size in bytes at which the log file is rotated (default 10 MB = 10,485,760)
LogMode: TLogMode property lmFile or lmConsole
LogLevel: TLogLevel property Verbosity filter (default llNormal)
Fallback: Boolean property Enables fallback on file-write errors (default False)
FallbackMode: TLogMode property Where to send messages on fallback (default lmConsole)
WriteLog(LogType, AMessage) procedure Writes an entry to the configured output
WriteLogAndConsole(LogType, AMessage) procedure Echoes to the console and, in lmFile mode, also writes to the log file
LogTypeToString(LogType): String function ltError → 'Error', etc.
LogLevelToString(ILogLevel): String function Name of the given log level
LogLevelToStr: String function Name of the current LogLevel ('Desconhecido' if invalid)

📄 License

Distributed under the MIT License. See LICENSE for details.

© 2025 Rodrigo Peetz