We’ve made it through the overview of the slog documentation. Now it’s time to get down and dirty!
First up, constants! There are four, and they all define built-in attribute keys:
Constants
const ( // TimeKey is the key used by the built-in handlers for the time // when the log method is called. The associated Value is a [time.Time]. TimeKey = "time" // LevelKey is the key used by the built-in handlers for the level // of the log call. The associated value is a [Level]. LevelKey = "level" // MessageKey is the key used by the built-in handlers for the // message of the log call. The associated value is a string. MessageKey = "msg" // SourceKey is the key used by the built-in handlers for the source file // and line of the log call. The associated value is a *[Source]. SourceKey = "source" )Keys for “built-in” attributes.
The important thing to understand about these, is that they all relate to attribute keys that are automatically added to logs for you—and that you can interact with them.
By default, this code:
slog.Info("something happened!")
will produce a log with three attribute keys:
time: The current timelevel: Infomsg: `“something happened!”
And if you’ve enabled AddSource: true in your handler options, source will be set, too.
So how do you interact with them? Well, if you’re writing a log handler, you get to interact with them as you do any other attribute key. As a “mere” consumer, you can also interact with them using the ReplaceAttr function on the HandlerOptions config struct—we’ll talk more about that in time.