Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log non-string item in the slf4j

Tags:

java

slf4j

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

like image 611
user496949 Avatar asked Mar 28 '11 23:03

user496949


People also ask

How do you write log in SLF4J?

We create the Logger instance by using the LoggerFactory class and its getLogger method and providing the name of the class. That way we bind the logger to the class name which gives us the context of the log message. Once we have that, we can use the Logger methods to create LogRecord on a given level.

Does SLF4J call toString?

When you do something like LOG. debug("Exported {}.", product) in slf4j it will eventually call toString() on the arguments, e.g. product .

Does SLF4J use Commons logging?

The classes for commons-logging will be provided by jcl-over-slf4j.

Is SLF4J better than log4j?

Unlike log4j, SLF4J (Simple Logging Facade for Java) is not an implementation of logging framework, it is an abstraction for all those logging frameworks in Java similar to log4J. Therefore, you cannot compare both. However, it is always difficult to prefer one between the two.


2 Answers

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.

like image 75
Ceki Avatar answered Sep 28 '22 16:09

Ceki


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.)

like image 20
Stephen C Avatar answered Sep 28 '22 17:09

Stephen C