开发者

How to log non-string item in the slf4j

开发者 https://www.devze.com 2023-02-20 04:43 出处:网络
It seems that slf4j\'s method only accepts string argument, do I have to convert everything to strin开发者_如何学Gog when using its method?The main reason for requiring String instead of Object for th

It seems that slf4j's method only accepts string argument, do I have to convert everything to strin开发者_如何学Gog when using its method?


The main reason for requiring String instead of Object for the message type was to avoid ambiguity in the method signatures.

Takes the following signatures:

1) debug(Object) // a message
2) debug(Object, Object) // message followed by a parameter
3) debug(Object, Exception)  // message followed by an exception

then, when you write

debug("hello", new Exception("world"));

it is not clear if variant 2 or variant 3 should be used.

In any case, with the existing SLF4J API you can always write:

  logger.debug("{}", yourObject);

If the underlying logging framework is logback, then yourObject will be available to all appenders unchanged. Other logging frameworks do not support message parameters so SLF4J has to format the message before calling the underlying framework.


It seems that slf4j's method only accepts string argument, do I have to convert everything to string when using its method?

If you are talking about the 1 argument methods like Logger.debug(String message) , then yes you do. But there are other methods such as Logger.debug(String format, Object[] args) that don't require this.

I'm not sure why sl4fj's APIs are like this (and for example log4j's APIs are not), but it is probably some combination of:

  • trying to cater for underlying logging framework behaviour,
  • trying to minimize the performance impact, and
  • "implementor's prerogative".

(The last is the principle that if something is being designed / implemented by one person who doesn't answer to some design committee, his opinions on style, etc hold greater weight than anyone else's.)


try

String.valueOf(yourObject)

and then make sure your toString() methods are actually meaningful

0

精彩评论

暂无评论...
验证码 换一张
取 消