TL;DR: Markers can be used to enrich logging events, and enable functionality without changing the SLF4J API. This post demonstrates enriched events by creating an
AudioMarker class, and using it to play sound using the
javax.sound API through Logback when the marker is attached.
This is part of the series of blog posts:
- Application Logging in Java: Creating a Logging Framework
- Application Logging in Java: Adding Configuration
- Application Logging in Java: Converters
- Application Logging in Java: Markers
- Application Logging in Java: Appenders
- Application Logging in Java: Logging Costs
- Application Logging in Java: Encoders
- Application Logging in Java: Tracing 3rd Party Code
- Application Logging in Java: Filters
- Application Logging in Java: Putting it all together
Markers are part of the SLF4J API, but they are not well documented. The most documentation you can find on Markers is on Stack Overflow, in Best practices for using Markers in SLF4J/Logback, where markers are listed as being for filtering, and triggering.
This is literally true, but severely understates the case for Markers: SLF4J markers enrich
ILoggingEvent. You cannot touch an
ILoggingEvent from the Logback API, but you can add and compose as many markers as you want, and those markers can contain both state and behavior. And once you have a marker on the event, you can pattern match on the marker using an appender, and execute on that behavior.
Making a Sound Player
Let's make a simple audio player with the
javax.sound API, using the playing trail as a guide:
And we'll add a
and a simple implementation:
Enriching Events with Markers
Now we've got a player up and running, we can hook it into Logback. Because Marker is an interface, we have to do some work to get a base class implementation up, but that's boring so it's in
TerseBasicMarker if you want to see it. The interesting bit is the
Note that the marker name is not significant, so we just use a constant. If we were using this marker with an evaluator, we'd have to do more custom work to disambiguate markers.
Playing AudioMarker with Appender
But this is only half the story. We also need a custom appender that will be aware of markers that it can play:
And then we can specify it:
This lets us indicate that a particular logging event will make your computer bark:
Using a PlayerConverter
You are not limited to an appender, of course. You can extract information from anything that takes an
ILoggingEvent, such as a converter:
The source code is available in the logback-audio module.
Needless to say, this can be extended in other directions. Markers are used extensively in
logstash-logback-encoder to write to a JSON generator, as described in event specific custom fields.
Next up: Appenders