Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to print the Object parameter in log4j2

Tags:

java

log4j2

I am new to log4j2. Here is the Scenario I am tracing it as follows

log.trace("some message",object);

Now i would like to print the Object using the Console appender. My appender looks like this.

<Console name="Console">
  <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>

but right now it prints only.

"16:40:30.300 [main] TRACE com.xxx.skip.webservice.RunService - test"

But if "Object" is of instance Throwable it works fine but not for any other object. Please point me right direction.

Update

Seems like it is not possible to custom log the object to a different field from the answers below.

like image 457
Sabareesh Kkanan Avatar asked Oct 25 '25 03:10

Sabareesh Kkanan


2 Answers

You want to print your object as part of your log message? Then just do this:

log.trace("some message {}", object);

This is actually the same as:

log.trace("some message " + object);

But it's better because the String concatenation only happens if the level used (trace in this case) is enabled (lazy evaluation).

like image 194
Fred Porciúncula Avatar answered Oct 27 '25 17:10

Fred Porciúncula


Log4j2 is a logging solution. Logging solutions write text messages to appenders -- file, standard out, a network location etc. It doesn't make sense to log an object. If you you really are sure that this is what you want to do, then add a meaningful toString to your object and log that.

log.trace("some message", object.toString());

If you are trying to serialize your object, you should take a different approach, as Log4j2 is not the right tool for this.

like image 35
mvd Avatar answered Oct 27 '25 19:10

mvd