[slf4j-user] How to prefix log messages for individual Loggers?

Toolforger toolforger at durchholz.org
Sat May 25 11:25:14 CEST 2013


Am 24.05.2013 11:53, schrieb niels:
> If your nodes run in different threads you can use MDC. It is a
> ThreadLocal.

That would work.

This is a bit of a judgement call, but in my book, I wouldn't consider 
restricting my design space in that way just to get id values shoved 
into log messages.
In particular since I tend to add lots of other values to log messages, 
like this:
   logger.info ("{}: file {} not found", id, fileName);
Adding an id is tedious but not a big deal.

Alternatively, one could write
   protected void logInfo(String message) {
     logger.info("{}: {}", id, message);
   }
You can't (efficiently) use {} parameters with that, because you'd have 
to write something like
   protected void logInfo(String message, Object... params) {
     logger.info(id + ": " + message, params);
   }
which means a string concatenation before the logger decided that it's 
even needed. (String concatenation is expensive, particularly if you're 
doing lots and lots of trace-level logging calls which are usually 
filtered anyway - one of the points of using SLF4J in the first place.)

 > Otherwise you need an own logger.

Does this even buy anything?
A separate per-id logger would just shove the problem from "I don't want 
to add the id to each logging call" to "I don't want to select the 
proper logger on each logging call".


More information about the slf4j-user mailing list