[slf4j-user] logger.info("It took {%h hours %m minutes %s seconds}.", timeTakenInMilliseconds)

Thorbjoern Ravn Andersen ravn at runjva.com
Fri Jun 5 15:05:53 CEST 2009


Geoffrey De Smet skrev:
> Hi,
>
> Is it possible to do something like this?
>
> int timeTakenInMilliseconds) = 3662000;
> logger.info("It took {hh:mm:ss} seconds", timeTakenInMilliseconds);
>
> which prints this to the log:
>
> "It took 1 hours 1 minutes 2 seconds."
>
> The idea is that the timeTakeInMilliseconds is only parsed if info 
> logging is on.
I solved this problem yesteday as part of another problem.

Basically you need to delay the String rendering of the integer argument 
until AFTER the decision to log the object has been made.   The simplest 
way to do so is to create a wrapper class doing what you need to do in 
its toString() method, and then wrap your object in an instance in your 
log statement.  The wrappers toString method is then invoked by the 
logger framework, and there you can put your string rendering.

E.g.

  log.debug("big={}", new ToString(bigObject));

where ToString looks like:


public class ToString {

    Object o;

    public ToString(Object o) {
        this.o = o;
    }
   
    public String toString() {
        return o.toString();
    }
   
}

Let me know how it works for you :)

-- 
  Thorbjørn Ravn Andersen  "...plus... Tubular Bells!"




More information about the slf4j-user mailing list