javaslf4j

How to log non-string item in the slf4j


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


Solution

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

    Update 2024: the fluent API introduced in SLF4J 2.0 allows passing Object data via addArgument(Object) and addKeyValue(String, Object) methods .