Structured logging is a concept that puts events over messages, events are logged with associated key-value data, not plain string messages. This helps in:
- processing log files for analytics
- searching and debugging (example: search log statements for particular user or request)
Basic Logging with
Lets create a simple logger:
- Drain is a trait which is responsible for deciding the output/destination of the logs. Any custom log handling logic should be implemented as a Drain.
- Context are key-value pairs that gets added into every log statement. Let’s say if you want to add the git commit version to each log statement you can add it here.
- Logger are objects used to execute logging statements.
For creating root logger, we need drain and context. Read complete documentation here.
In above example, a
root_logger object is created with drain Discard (which discards everything) and blank context (
Lets look at another example:
Since drain is a trait to customize logging to any output, it allows slog to become extensible, composable, and flexible. There are many feature libraries based on this trait:
You can always write your own implementation using this trait.
Drains can also be interlinked and extended according to our needs. Following is an example where there are two outputs:
- to stdout, where all log statements are sent
- to stderr, where log statements with log level greater than or equal to
Log Macros and Log Levels
To log a statement/record, we use log macros. In the above examples,
info! is used.
Log Levels are log categories based on urgency. For example, we have
error!, etc. for self-explaining urgencies.
We have different log macros for different log levels.
You can find many more examples here.