I'm trying to find a nice way to add a prefix to my logs without passing it on every calls, without instanciate Logger again.
The purpose is to trace Rest calls individually. (The prefix would be re-generated on each call using UUID)
This would be like
@RestController
class MyClass {
//Here the prefix is initialise once
//default value is X
Logger LOG = LoggerFactory.getLogger(MyClass.class);
@RequestMapping("/a")
void methodA() {
LOG.debug("foo");
}
@RequestMapping("/b")
void methodB() {
LOG.setPrefix("B");
LOG.debug("bar");
}
with this output
[...] [prefix X] foo
[...] [prefix B] bar
As you've said you're using Logback, here's a couple options to do the kind of thing you're trying to do:
Markers
Each log entry can have a "marker" established for it. (The best documentation I've seen for it is in the SLF4J FAQ.) Something like:
You would need to update all log entries in each method to use the appropriate marker. You can then put
%marker
in your layout to put the log entry's marker into the log.MDC
The other option is to use the "Mapped Diagnostic Context" functionality to specify the current "context" for each log entry.
You would then use
%mdc{method}
in your layout to output that particular MDC value. Note that MDC is really intended to be used for per-thread values like something web-connection-specific, so it's important to ensure that it's cleared out of what you don't want when you're leaving the context you want the value logged in.Here's my MDC implementation explained to share my experiments with MDC.
Calling RestControllerTest mapped /test/testA produces :
Calling /test/testC produces (id and name are kept even if initLogData is called in sub methods):
Please see http://www.slf4j.org/extensions.html#event_logger for an example of how to use the MDC. You do not have to use the EventLogger. Once you set things in the MDC they are present in every log record.
A Marker does not meet your criteria since it has to be specified on every call.