This repository is StormByte Logger: stream logging for the StormByte C++ suite.
It depends directly on StormByte Base 3.0.0 and StormByte-BuildMaster >= 2.1.4. Public headers live under StormByte/logger/ and cover Log, ThreadedLog, header formats, hierarchical components, Scope facades, groups, colors, temporary formats, human-readable numbers, redaction, hex dumps, binary payloads, and owned text types that can cross a DLL / .so boundary (StormByte::Safe::String / WString, StormByte::Size, StormByte::ByteSize, StormByte::Safe::Binary).
The suite is split on purpose. Base, Buffer, Config, Crypto, Database, Multimedia, Network and System are other repositories. This one does not implement them.
| Module | Role | API |
|---|---|---|
| Base | Exceptions, Expected, serialization, UUID, concepts, safe text and pointers | /StormByte |
| Buffer | FIFO, SharedFIFO, Ring, Producer/Consumer and multi-stage pipelines | /StormByte-Buffer |
| Config | Human-readable text and versioned binary documents (groups, lists, raw bytes) | /StormByte-Config |
| Crypto | Hash, compress, encrypt, sign and key agreement — Crypto++ never leaves the private tree | /StormByte-Crypto |
| Database | One API over SQLite, PostgreSQL and MariaDB | /StormByte-Database |
| Multimedia | Decode, encode and containers without raw FFmpeg types; codecs enabled only if present | /StormByte-Multimedia |
| Logger | This repository | /StormByte-Logger |
| Network | Framed packets, Client/Server, IPv4/IPv6 TCP and Buffer pipelines (compress/encrypt) | /StormByte-Network |
| System | Processes, pipes and environment variables across Linux, Windows and macOS | /StormByte-System |
Other modules that take a std::shared_ptr<StormByte::Logger::Log> still compile: Scope returns StormByte::Safe::Shared<Log>, which converts to that shared_ptr and still frees on Base's heap. The print floor is chosen by the application, not by the library that logs.
StormByte::Logger::Level is the only severity type. It is used twice:
Order is least severe → most severe (this is not syslog):
| Level | Value | When to use |
|---|---|---|
| LowLevel | 0 | High-volume diagnostics: per-unit PTS/DTS, wait/wake, hopper chatter. Expect slowness if the floor is this low. |
| Debug | 1 | Useful but quieter: binds, reserves, work summaries, codec open. |
| Warning | 2 | Recoverable problems that did not fail the job. |
| Notice | 3 | Significant normal events: created, opened path, eof, closed. Keep this quiet. |
| Info | 4 | Job-level information, such as a completed operation. |
| Error | 5 | Error conditions. |
| Fatal | 6 | Unrecoverable errors. |
A message is emitted when message_level >= print_floor, or when its level is Warning, Error or Fatal.
Examples:
LevelToString(Level) returns the short name used in L ("LowLevel", "Debug", "Notice", …). The header pads the name to 8 characters.
Payload operator<< for ordinary filtered levels returns immediately below the floor. Warning, Error and Fatal remain enabled. Setting a Level, applying a manipulator, or writing std::endl is still forwarded so logger state stays consistent.
Enabled(Level) asks whether that level would pass the print floor (including the Warning/Error/Fatal exception). It does not open a line and does not consult throttle. Use it to skip building a payload. Throttle still runs later on PrepareLine if you do write.
Third constructor argument. Specifiers:
| Token | Meaning |
|---|---|
| L | Current message level, padded to 8 characters |
| T | Local timestamp dd/mm/YYYY HH:MM:SS |
| i | std::this_thread::get_id() |
| c | Component path for the current line (stack join or Scope sticky path) |
| g | Group for the current line, if any |
| %% | A literal % |
Default format is "[L] T". A typical multi-thread format is "[L] T" or "[L i] T". Components and groups are opt-in: use "[L] T c g" when you want them.
The formatted i value is reused within each thread. Scoped output skips ancestor searches when no component-specific format or color exists; later configuration changes still apply immediately.
The logger writes the header once per line, then the payload, then the newline manipulator.
A component format override can introduce c / g even when the general format does not contain them. Longest matching path wins; then the general format.
Needs a C++26 compiler, CMake 3.28 or newer, StormByte-BuildMaster >= 2.1.4, and StormByte Base 3.0.0. Configure downloads the matching Base release archive. There is no Base submodule. BuildMaster is the installed package when it is >= 2.1.4, otherwise the buildmaster submodule.
Shared vs static follows CMake BUILD_SHARED_LIBS (default ON). A plain configure builds the shared library. -DBUILD_SHARED_LIBS=OFF builds a static archive; on Windows the headers then do not use dllimport. The downloaded Base archive is the same mode.
A shared build keeps this library as its own .so / .dll. Under the LGPL that is usually the simpler way to ship: the user can replace that file. A static archive is folded into your binary. The LGPL still applies to this code; you must give the recipient a way to relink your product with a different build of this library. If that does not fit how you distribute the final product, a commercial license is available from the copyright holder (see License).
For an installed Base and Logger prefix, use the component finder:
The Logger finder is installed in share/cmake/Modules beside Base's finder. Include path: the public install prefix, headers as #include <StormByte/logger/….hxx>.
Headers are #include <StormByte/logger/….hxx>. Namespace root is StormByte::Logger.
operator<< unpacks those four owners when the element type derives from Log (Log and ThreadedLog). The call site does not dereference. *shared << still works. An empty owner does nothing and the expression still yields the pointer.
Log and ThreadedLog accept any std::ostream (std::cout, a file stream, a string stream). The stream must outlive the logger. The DLL never calls into that stream: each write and each manipulator (std::endl, std::flush, …) jumps back to OStreamWrite / OStreamManip, which are compiled into the module that constructed the logger.
For a custom sink that crosses a DLL boundary, use SinkFunction (StormByte::Safe::Function<void(const StormByte::Safe::String&)>) instead of passing an owning std::function or a raw callback context. Its context is released by the creator module. Sink invocation is part of a noexcept output path: callback failures do not escape the logging operator. StormByte::Exception may be thrown by a callback and is contained; other callback exceptions become StormByte::Status::Failure in Safe::Function.
Public logger facades and manipulators that carry Base-owned fields are declared MaybeSafe; optional fields use StormByte::Safe::Optional rather than std::optional across the module boundary.
Streamed payload types: bool, the standard integer and floating types, char / unsigned char / wchar_t, const char*, const wchar_t*, std::string, std::string_view, std::wstring_view, std::span<const std::byte>, StormByte::Safe::Binary, StormByte::Safe::String, StormByte::Safe::WString, StormByte::Size, StormByte::ByteSize. The inline std::string overload passes a view during the call; Logger copies its bytes into the line buffer synchronously. std::wstring converts to the wide view. std::vector<std::byte> converts to the span. There is no std::format overload on the logger itself; format first, then stream the view or an owned Base text type.
A line is:
Do not start a line without a Level if you care about the filter. Do not omit the newline: ThreadedLog holds the line lock until one is seen.
Copy and copy-assignment of Log / ThreadedLog share the same Engine (Safe::Shared). That is the intended way to hand one logger to several objects on one thread.
Across threads, construct a ThreadedLog and pass a std::shared_ptr, std::unique_ptr, Safe::Shared or Safe::Unique. Log has no line lock; concurrent operator<< will interleave characters.
The objects store StormByte::Safe::Shared<Log> (or a std::shared_ptr<Log> converted from it). ThreadedLog is-a Log, so the same pointer type works. Scope facades also share that backend.
Text that is owned by another module, or that must remain valid after returning across a DLL / .so, is StormByte::Safe::String / WString. These length-aware types preserve embedded NUL code units; use a C-string constructor only when the source is intentionally NUL-terminated. Do not put std::string in objects that cross that boundary.
Safe::String has an implicit inline string_view in the caller. That view points at the other module's buffer. Logger provides an explicit operator<<(const Safe::String&) so the copy into the line happens on this side after WillWrite().
component("Media"), group("work") and push_format("[L]") are header factories. A literal binds to const char*, a std::string or std::string_view binds to the view, and a Safe::String binds by identity. The manipulator stores an owned String, built in the caller. They are not exported DLL overloads.
Ill-formed wide input is written as U+FFFD (EF BF BD). Logger does not throw UTF8Error on that path. A filtered wide write does not convert at all.
operator<< also accepts StormByte::Safe::Optional, StormByte::Safe::Vector and StormByte::Safe::Map, including nested combinations when their values have a Logger streaming overload. A present optional writes its value; an empty one writes (empty Safe::Optional). Vectors use [value1, value2]; maps use one tab-indented key: value entry per line, in the map's key order. Empty containers write [] and {}. StormByte::Safe::Binary has the same Base64 and hex output as an equivalent std::vector<std::byte>.
State stays until another of these manipulators is applied.
Applies to strings and numbers (numbers are converted first). Stays on until noredact.
| Manipulator | Effect |
|---|---|
| redact / redact(0) | Every character becomes * |
| redact(N) | Keep the last N characters |
| redact_first(N) | Keep the first N characters |
| noredact | Disable |
Same contract on ThreadedLog. Hex encoding runs before redaction.
hex dumps subsequent text payloads as space-separated 0xHH bytes. hex(N) wraps every N bytes with a raw newline (no new header, line stays open). Default N is 16. hex(0) is the same as nohex.
Numbers are converted to text first, then those text bytes are dumped. It is not a numeric hex printer.
std::span<const std::byte>, std::vector<std::byte> and StormByte::Safe::Binary are Base64 by default. With hex(N) they use Safe::Binary::HexDump(N) (offset, hex columns, ASCII), not the 0xHH text dump:
On ThreadedLog the Base64 / hex string is built before the line lock, then written as a prepared payload.
ANSI color output is disabled by default. Configure a general color per level with Color(level, color). A component-path rule has priority while that path (or a child of it) is active. Longest matching prefix wins; then the general level color.
color re-enables the configured color for the current level. color(Color::X) temporarily selects an explicit content color, and nocolor suppresses color for subsequent content. The header remains configured and every line ends with an ANSI reset when a color was active.
push_format saves the current format and activates a temporary one. Calls nest, and pop_format restores the most recent saved format. An empty pop is a no-op, and the stack persists across lines until explicitly popped.
Changing the format while a line is active closes that line before the new format is used.
Formats can also be configured persistently per component path:
Effective precedence: push_format first, then the longest matching component path, then the general format. Format("Path", "") removes that override.
On a Scope facade, Format("mask") with no path argument binds to the facade's sticky path. On the root logger it changes the global format.
group("name") labels one line and is rendered by g. A newline clears the group automatically; group("") also selects no group. Without g, the group is intentionally not added to the payload.
component("name") pushes a segment onto a thread-local stack. Nested pushes join with / for c and for config lookup:
component("") does not push. Use reset_component to return to root, or pop_component to drop one segment. The stack is not cleared by endl.
The stack is thread-local, not tied to a Log instance. Two Log objects used by the same thread share it. Start tests and job boundaries with reset_component if a previous caller may have left segments.
To switch to a sibling path, reset (or pop) first. Otherwise component("Media") then component("Other") becomes Media/Other.
Scope is the API intended for libraries that should not touch the TLS stack.
Rules:
Child rules win over parent rules. If the leaf has no format/color, the longest matching ancestor is used, then the general setting.
Throttle is disabled by default. It limits complete logical lines, not payload fragments.
Rules are selected by the most specific matching key. Component matching uses path prefixes (Multimedia matches Multimedia/Decoder). When two rules match, the longer component string wins.
Error and Fatal are never throttled. Warning can be throttled even though it is always visible with respect to the print floor.
ThrottleSpec::Component and ThrottleSpec::Group are StormByte::Safe::Optional<StormByte::Safe::String>, keeping optional owned text safe across the DLL boundary. Assigning a literal still works where Safe::String can be constructed from it.
Policies are Drop, Sample and Window. Sample(n) admits the first line and then one of every n attempts. Window(keep, period) admits the first keep lines of each count window. Rate/burst can additionally limit the admitted lines by time. rate == 0 && burst == 0 disables the time ceiling; rate > 0 requires burst >= 1, while rate == 0 && burst > 0 allows exactly that initial burst with no refill.
When lines are dropped, the next admitted line is preceded by dropped N messages using the same level, component, group, effective format and color. Call FlushThrottle() at a job boundary to emit pending summaries. FlushThrottle(spec) limits the flush to matching selectors.
Install rules before concurrent writers start.
Other suite modules log through this module. A useful convention is:
The application chooses the floor. A user who sets LowLevel is asking for noise and the cost that comes with it.
ThreadedLog serializes logical lines, not individual << tokens from one thread.
endl must drop the lock even if another thread just changed the current level. That is required so a filtered LowLevel line cannot leave the lock held and stall every other writer.
Engine current-level / enabled flags are still process-wide, not thread_local. Do not interleave two unfinished lines on the same logger from two threads without finishing each line with a newline. The supported pattern is: one thread writes a complete line (Level … endl) at a time; ThreadedLog only prevents those complete lines from mixing characters.
The component stack is thread-local. Scope paths are per-facade and do not use that stack. group remains line-scoped.
Issues only on this repository. Fork and open a pull request against master.
From 2.0.0, original StormByte-Logger source is dual-licensed:
Neither license covers other StormByte modules or third-party material shipped under thirdparty/ (including the bundled Base tree). Those keep their own licenses. Neither license grants patent rights.
Binary releases add THIRD-PARTY beside LICENSE. That file is a notice for what was compiled into the shared library, not another grant. The texts it names are the COPYING.* files in the same archive.
Static linking under the LGPL is described under Installation.
StormByte is developed in spare time. Sponsorship is optional and does not buy features, priority or support.