Log through CoreLogger
Use CoreLogger to write fast, structured, and styled log messages. This guide demonstrates the default DeltaTimeLogger implementation and how to log using the styled Interpolated Expression Sequences (IES).
Using the DeltaTimeLogger
By default, calling initLogger installs DeltaTimeLogger as both the Phobos std.logger.sharedLog and sparkles.base.logger.sharedCoreLog. DeltaTimeLogger formats logs in the following layout:
[ Time | Δt (since start) | Δtᵢ (since last log) | Level | File:Line ]: Message
Here is an example showing how to initialize the logger and output logs of various levels, using both static styled messages and dynamic interpolated values.
#!/usr/bin/env dub
/+ dub.sdl:
name "base_core_logger"
dependency "sparkles:base" version="*"
+/
import sparkles.base.logger : initLogger, info, warning, error, critical, log, trace, LogLevel;
void main()
{
// Initialize the logger to output logs of TRACE level or higher
initLogger(LogLevel.trace);
// Standard log levels with static styled messages
trace(i"Application starting up");
info(i"Listening on port {green 8080}");
warning(i"Disk usage above {yellow 80%}");
error(i"Connection to {red database} lost");
critical(i"{bold.red Out of memory}");
// Styled IES with interpolated values
immutable host = "db-01.prod";
immutable port = 5432;
info(i"Reconnected to {green $(host)}:{cyan $(port)}");
// Explicit log level with styled IES
log(LogLevel.warning, i"Latency spike: {yellow.bold 230ms} on {dim $(host)}");
}[ 15:22:40 | Δt 46.7µs | Δtᵢ 46.7µs | TRC | base_core_logger.d:14 ]: Application starting up
[ 15:22:40 | Δt 119.7µs | Δtᵢ 72.9µs | INF | base_core_logger.d:15 ]: Listening on port 8080
[ 15:22:40 | Δt 167.3µs | Δtᵢ 47.5µs | WRN | base_core_logger.d:16 ]: Disk usage above 80%
[ 15:22:40 | Δt 212.2µs | Δtᵢ 44.9µs | ERR | base_core_logger.d:17 ]: Connection to database lost
[ 15:22:40 | Δt 257.9µs | Δtᵢ 45.7µs | CRT | base_core_logger.d:18 ]: Out of memory
[ 15:22:40 | Δt 315.2µs | Δtᵢ 57.2µs | INF | base_core_logger.d:23 ]: Reconnected to db-01.prod:5432
[ 15:22:40 | Δt 361.1µs | Δtᵢ 45.9µs | WRN | base_core_logger.d:26 ]: Latency spike: 230ms on db-01.prodAdvanced Customization: Fatal Handlers
fatal log calls are also @safe nothrow @nogc. By default, the fatal handler throws a thread-local, recycled FatalLogError to avoid GC allocation.
If you want the process to exit immediately or panic instead of throwing, you can customize the handler by setting coreFatalHandler to assertingFatalHandler or abortingFatalHandler:
import sparkles.base.logger : coreFatalHandler, assertingFatalHandler;
// Change the behavior of `fatal` logs to assert(0)
coreFatalHandler = &assertingFatalHandler;