Format-string driven terminal logging library for C++, C# and Java.
Licensed under the GNU Lesser General Public License v2.1 | Source: github.com/PenguineDavid/light-weight-logger
- Overview
- Design: Compile Once, Log Fast
- Format Specifier Reference
- Preset Format Styles
- C++ Implementation
- C# Implementation
- Java Implementation
- Cross-Port Comparison: Thread Safety and Platform Handling
- License
Logger is a lightweight, zero-dependency terminal logging library. Instead of a fixed set of log levels with hard-coded output, it gives you a format-string mini-language. You register named levels at runtime, attach a format string and an ANSI colour to each, and call log() / Log() with a level name and message.
Key properties:
- No third-party dependencies in any port
- Single-file drop-in for C++ (
Logger.hpp), two-file for C# and Java - Format strings are parsed once, at registration, not on every log call (see below)
- ANSI colour output via the
Colourconstants shipped with each port - Dynamic
%Spadding keeps level names column-aligned automatically as you register more levels - Source-location capture (
%F,%L,%f) available in all three ports, each using the cheapest mechanism its language offers - Date format switchable between AU (
DD/MM/YYYY) and US (MM/DD/YYYY) at runtime - A runtime-swappable output stream (
set_output_stream/SetOutputStream/setOutputStream) in all three ports, so output can be redirected to a file or in-memory buffer instead of the console
This is the main structural optimization in the current codebase, and it applies identically across all three ports.
add_format / AddFormat / addFormat walks the format string character by character exactly once, at registration time, and turns it into a list of LogToken objects (an enum tag plus, for literal text, the stored string). This compiled token list is what gets stored against the level name, not the raw format string.
log / Log never re-parses a format string. It just iterates the pre-compiled token list and switches on the token type, filling in the few tokens that need live data (time, date, milliseconds, thread id, source location). This means:
- Registering a level is O(length of format string), done once.
- Every subsequent
log()call for that level is O(number of tokens), with no string scanning, no branching on characters, and no re-detection of specifiers. - Adding more registered levels does not slow down logging on existing levels; only
%Spadding recalculates (max_name_length/_maxNameLength/maxNameLength), and that is an O(1) max comparison, not a rescan of every format.
If you are logging on a hot path, this is why: the cost you pay is in add_format, once, during setup. The cost at each log() call is just token dispatch and metadata formatting.
Note:
%F,%Land%fstill add per-call overhead relative to other tokens, because resolving the call site is inherently a runtime operation in all three languages. How much overhead differs a lot by port, see the comparison table below.
Every format string is a plain string in which any two-character sequence starting with % is treated as a specifier. All other characters are emitted verbatim. Specifiers are compiled left-to-right in a single pass at registration time.
| Specifier | Description |
|---|---|
%C |
Emit the ANSI colour code registered for this level. Use at the start of coloured regions. |
%G |
Emit ANSI grey (\033[90m). Typically used for metadata/secondary information. |
%c |
Emit ANSI reset (\033[0m). Required to close any colour region. |
| Specifier | Description |
|---|---|
%S |
Emit trailing spaces to align the level name column with the longest registered name. Recalculated automatically when new levels are added. |
%% |
Literal percent sign. |
| Specifier | Description |
|---|---|
%N |
Level name (the string you passed to add_format / AddFormat / addFormat). |
%M |
The log message passed to log() / Log(). |
%T |
Current wall-clock time: HH:MM:SS. |
%D |
Current date: DD/MM/YYYY (AU) or MM/DD/YYYY (US). Controlled by change_date_format. |
%ms |
Current milliseconds component (000-999). Three-character sequence: %, m, s. |
%Z |
System timezone name or abbreviation (e.g. AEST, PST, UTC). Resolution differs by port and OS, see below. |
%t |
Current thread ID. std::this_thread::get_id() in C++, Environment.CurrentManagedThreadId in C#, Thread.currentThread().threadId() in Java. |
| Specifier | Description |
|---|---|
%F |
Source file of the call site. |
%L |
Line number of the log() call. |
%f |
Function or method name at the call site. |
How each port resolves these is one of the bigger differences between them, covered in the comparison table.
The three format strings below are demonstrated in the example files. They are ordinary strings, copy, modify, or ignore them.
%C[%N]%c%S %G[%D %T %Z]%c -> %M
%C %N %c%S | %G%T %Z%c | %M
%G%D %T.%ms %Z%c %C<%N>%c%S %M %G(%F:%L)%c
// Compact -- just level and message, no timestamp
%C[%N]%c%S %M
// ISO-style with milliseconds
%G[%D %T.%ms]%c %C%N%c%S %M
// Thread-tagged for concurrent applications
%G[%T]%c [thread:%t] %C%N%c%S %M
// Full debug dump with source location
%C%N%c%S %M %G@ %F:%L in %f%c
Standard: C++20 | File: Logger.hpp | Namespace: Colour (ANSI constants)
Logger.hpp is header-only. Drop it anywhere on your include path and include it directly, no build system integration required.
#include "Logger.hpp"
int main()
{
Logger logger;
std::string fmt = "%C[%N]%c%S %G[%D %T %Z]%c -> %M";
logger.add_format("INFO", fmt, Colour::CYAN);
logger.add_format("SUCCESS", fmt, Colour::GREEN);
logger.add_format("WARN", fmt, Colour::YELLOW);
logger.add_format("ERROR", fmt, Colour::RED);
logger.log("INFO", "Initializing core subsystem components.");
logger.log("SUCCESS", "Database connection established smoothly.");
logger.log("WARN", "High memory usage detected on node cluster.");
logger.log("ERROR", "Failed to write to write-ahead log!");
}# GCC / Clang (Linux, macOS)
g++ -std=c++20 -o app main.cpp
# MSYS2 ucrt64 (Windows)
g++ -std=c++20 -o app.exe main.cppThe C++ port is written directly against POSIX where the standard library does not already abstract the platform away:
- Every time/date helper (
print_current_time,print_current_date,print_current_timezone) branches on_WIN32. On Windows it callslocaltime_s, on Linux and macOS it callslocaltime_r. Both are the reentrant, thread-safe variants oflocaltime, the difference is only in argument order between the two platform APIs, not in safety. %Ztimezone output comes straight fromstd::put_time(&tm_buf, "%Z"), which on glibc-based Linux already returns a short abbreviation (AEST,UTC), so there is no extra parsing needed on that platform, unlike the C# port.- Source location uses
std::source_location::current()as a default argument, resolved by the compiler at the call site rather than walked at runtime. This works identically on GCC and Clang under Linux and needs no debug symbols, no PDB-equivalent, and no stack introspection at all.
The whole Logger instance is guarded by a single std::mutex (output_mutex):
add_formattakesstd::lock_guard<std::mutex>before touchingformats,format_colours, ormax_name_length. Registering levels from multiple threads is safe.change_date_formattakes the same lock before touchingtime_format.logtakes the same lock for the entire call, covering both the map lookups and every character written tooutput_stream. Two threads logging at once cannot interleave their output, and a thread registering a new level cannot race with a thread mid-log.
This is the strictest of the three ports: one mutex, held for the full duration of any public method, no partially-protected state.
void add_format(const std::string& name, const std::string& format_string, std::string_view level_colour = Colour::WHITE)
Register a named log level. Calling again with the same name replaces the format string and colour. max_name_length is updated so %S padding stays consistent. Thread-safe.
void log(const std::string& format_name, const std::string& message, const std::source_location location = std::source_location::current())
Emit a log line. If format_name does not match a registered level, outputs [UNREGISTERED] followed by the message. Do not pass location, the compiler-supplied default captures the call site automatically. Thread-safe.
Switch date formatting. Accepts "au" (DD/MM/YYYY, default) or "us" (MM/DD/YYYY). Any other value is silently ignored. Thread-safe.
Redirect output to any std::ostream (a file stream, a std::stringstream, etc.). Thread-safe.
Colour::RESET // \033[0m
Colour::BLACK // \033[30m
Colour::RED // \033[31m
Colour::GREEN // \033[32m
Colour::YELLOW // \033[33m
Colour::BLUE // \033[34m
Colour::MAGENTA // \033[35m
Colour::CYAN // \033[36m
Colour::WHITE // \033[37m
Colour::GREY // \033[90mAll constants are constexpr std::string_view defined in namespace Colour.
All standard library:
| Header | Used for |
|---|---|
<iostream>, <string>, <unordered_map> |
Core I/O and storage |
<chrono>, <iomanip> |
Timestamp formatting |
<source_location> |
C++20. Required for %F, %L, %f |
<mutex> |
Locking for add_format, change_date_format, log |
<thread> |
%t (thread ID) |
<algorithm> |
std::max for max_name_length |
Runtime: .NET 8+ | Files: Logger.cs + Colour.cs | Namespace: include
Add both files to your project. No NuGet packages required.
using include;
Logger logger = new Logger();
string fmt = "%C[%N]%c%S %G[%D %T %Z]%c -> %M";
logger.AddFormat("INFO", fmt, Colour.CYAN);
logger.AddFormat("SUCCESS", fmt, Colour.GREEN);
logger.AddFormat("WARN", fmt, Colour.YELLOW);
logger.AddFormat("ERROR", fmt, Colour.RED);
logger.Log("INFO", "Initializing core subsystem components.");
logger.Log("SUCCESS", "Database connection established smoothly.");
logger.Log("WARN", "High memory usage detected on node cluster.");
logger.Log("ERROR", "Failed to write to write-ahead log!");<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>The C# port no longer walks a StackTrace at runtime. Log now takes three compiler-injected parameters:
public void Log(string formatName, string message,
[CallerFilePath] string filePath = "",
[CallerLineNumber] int lineNumber = 0,
[CallerMemberName] string memberName = "")CallerFilePath, CallerLineNumber and CallerMemberName are resolved by the compiler at the call site and baked in as literal arguments, there is no StackFrame allocation, no PDB lookup, and no dependency on Debug vs Release build configuration. %F, %L and %f are effectively free at runtime in this port now, which also means they work identically on Linux and macOS builds of .NET, where PDB-based stack walking used to be less reliable.
%T,%Dand%msall go throughDateTimeOffset, which is fully cross-platform and needs no OS branching.%Zis the one place the C# port still branches on OS, viaOperatingSystem.IsWindows():- On Windows,
TimeZoneInfo.Local.StandardName/DaylightNamereturn a long descriptive name (e.g. "AUS Eastern Standard Time"), so the port extracts just the capital letters to approximate an abbreviation. - On Linux and macOS,
TimeZoneInfo.Local.StandardNamealready returns the short IANA-style abbreviation directly, so it is written out as-is with no post-processing.
- On Windows,
This port is intentionally lighter-weight than the C++ and Java ports, and the asymmetry is worth knowing about:
AddFormatis not locked at all.FormatsandFormatColoursare plain instance dictionaries (not static, eachLoggerhas its own), and writes to them are unsynchronized. Register all your levels during startup, before any logging thread starts.Logtakeslock (_outputLock)only around the part that writes tokens to_outputStream. TheFormats.TryGetValuelookup and colour lookup happen just before the lock is taken.- In practice this means: once
AddFormatcalls have finished and no more levels are being registered, concurrentLogcalls are safe with respect to each other (output will not interleave), but aLogcall racing with anAddFormatcall is not protected.
Register a named log level against this Logger instance's own dictionaries. Calling again with the same name replaces the entry and recalculates _maxNameLength. Not thread-safe, call during initialization.
Overload that defaults levelColour to Colour.WHITE.
Emit a log line. %F, %L, %f are supplied via CallerFilePath/CallerLineNumber/CallerMemberName, resolved by the compiler, not at runtime. The output-writing portion is thread-safe.
Accepts "au" (DD/MM/YYYY) or "us" (MM/DD/YYYY). Any other value is silently ignored.
Redirect output to any TextWriter. Throws ArgumentNullException if stream is null.
Colour.RESET // \x1B[0m
Colour.BLACK // \x1B[30m
Colour.RED // \x1B[31m
Colour.GREEN // \x1B[32m
Colour.YELLOW // \x1B[33m
Colour.BLUE // \x1B[34m
Colour.MAGENTA // \x1B[35m
Colour.CYAN // \x1B[36m
Colour.WHITE // \x1B[37m
Colour.GREY // \x1B[90mAll constants are public const string on the Colour class in namespace include.
Minimum: Java 21 | Files: Logger.java + Colour.java | Package: include
Place both files under src/include/. Import them into any class that needs logging.
import include.Logger;
import include.Colour;
public class main {
public static void main(String[] args) {
Logger logger = new Logger();
String fmt = "%C[%N]%c%S %G[%D %T %Z]%c -> %M";
logger.addFormat("INFO", fmt, Colour.CYAN);
logger.addFormat("SUCCESS", fmt, Colour.GREEN);
logger.addFormat("WARN", fmt, Colour.YELLOW);
logger.addFormat("ERROR", fmt, Colour.RED);
logger.log("INFO", "Initializing core subsystem components.");
logger.log("SUCCESS", "Database connection established smoothly.");
logger.log("WARN", "High memory usage detected on node cluster.");
logger.log("ERROR", "Failed to write to write-ahead log!");
}
}# From the directory containing src/
javac -d out src/include/Colour.java src/include/Logger.java src/main.java
java -cp out mainThe Java port has moved from Thread.currentThread().getStackTrace() (which allocates and populates a full StackTraceElement[] for the entire call stack, every single log call) to StackWalker:
StackWalker.StackFrame source = StackWalker.getInstance().walk(frames -> frames
.filter(frame -> !frame.getClassName().equals(Logger.class.getName()))
.findFirst()
.orElse(null));StackWalker is lazy, it streams frames rather than materializing the whole stack up front, and stops as soon as findFirst() matches a frame outside Logger itself. This is both cheaper and more robust than the old fixed-index (getStackTrace()[2]) approach, since it does not break if internal call depth inside Logger ever changes.
Java's java.time API (ZonedDateTime, DateTimeFormatter) is platform-independent by design, so unlike the C++ and C# ports, the Java port has no OS branching at all for %T, %D, %ms, or %Z. %Z uses DateTimeFormatter.ofPattern("z", Locale.ROOT), which resolves the JVM's configured time zone abbreviation consistently across Linux, macOS, and Windows.
formatsandformatColoursare now plain instance fields (private final Map<...>), not static, so separateLoggerinstances no longer share state or contend with each other.addFormatsynchronizes onoutputLockwhile updatingformatColours,maxNameLength, andformats.logsynchronizes on the sameoutputLockfor the entire call, including theformats.get(formatName)lookup, theStackWalkerresolution, and everyoutputStream.printcall.
Because both mutation (addFormat) and use (log) share one lock, this port is safe to call from multiple threads at any time, including registering new levels while other threads are actively logging, which is stricter than the C# port and matches the C++ port's guarantees.
Register a named log level. Thread-safe via outputLock. Calling again with the same name replaces the entry and recalculates maxNameLength.
Overload that defaults levelColour to Colour.WHITE.
Emit a log line. Source location comes from StackWalker, filtered to the first frame outside Logger. Thread-safe.
Accepts "au" (DD/MM/YYYY) or "us" (MM/DD/YYYY). Uses "au".equals(type) null-safe comparison. Any other value is silently ignored.
Redirect output to any PrintWriter. Throws IllegalArgumentException if stream is null.
Colour.RESET // \033[0m
Colour.BLACK // \033[30m
Colour.RED // \033[31m
Colour.GREEN // \033[32m
Colour.YELLOW // \033[33m
Colour.BLUE // \033[34m
Colour.MAGENTA // \033[35m
Colour.CYAN // \033[36m
Colour.WHITE // \033[37m
Colour.GREY // \033[90mAll constants are public static final String on the Colour class in package include.
| Aspect | C++ | C# | Java |
|---|---|---|---|
| Level registration state | Instance fields, guarded by output_mutex |
Instance fields, unsynchronized | Instance fields, guarded by outputLock |
| Is registration thread-safe? | Yes | No, do it before spawning threads | Yes |
Is log/Log thread-safe? |
Yes, whole call locked | Partially, only the output-write section | Yes, whole call locked |
| Can you register while logging concurrently? | Yes | No | Yes |
| Source-location mechanism | std::source_location::current(), compiler default argument |
[CallerFilePath]/[CallerLineNumber]/[CallerMemberName], compiler-injected |
StackWalker, lazy stream, stops at first external frame |
| Source-location runtime cost | Effectively free | Effectively free | Cheap, but not free, still a stack walk |
%Z resolution |
std::put_time("%Z"), native abbreviation on Linux |
OS-branched: strip capitals on Windows, native abbreviation on Linux/macOS | DateTimeFormatter with Locale.ROOT, no OS branching needed |
| Linux-specific code path | localtime_r vs localtime_s behind _WIN32 |
OperatingSystem.IsWindows() branch for %Z only |
None needed, java.time is already portable |
If you need the strongest concurrency guarantees, the C++ and Java ports are equivalent and stricter than the C# port. If you are only ever registering levels once at startup before touching multiple threads, all three ports behave the same in practice.
This library is distributed under the GNU Lesser General Public License v2.1.
What LGPL v2.1 means in practice:
- You may use Light-Weight-Logger in a closed-source application without being required to open-source that application
- If you distribute a modified version of Light-Weight-Logger itself, those modifications must be released under LGPL v2.1
- You must provide a way for end users to re-link your application against a modified version of the library
- A copy of the licence text must accompany any distribution of the library
Copyright (C) 2026 David S
This library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this library. If not, see https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html#SEC1.