I am currently working on a program wherein, I must write all output to a log file.
I need to write a log method, that should give an output with a level, a message, an object value, another message, an integer value, another message and another integer value, in the same order as I have specified. I can't seem to find a log method that does this. I am using Java.util.logging
. Is this possible?
I assume you need the log format in the below format FINE,Message1,object.GetValue(),Message2,1,Message3,2
You need to create an output message format
Now you need to create a custom formatter which by extending Formatter class
Now set the newly created formatter
We used below code while using slf4j logger -
It's a quite old topic, anyhow, my two cents, because I also prefer to use java.util.logging.Logger` in my projects where sufficient.
Lambdas make this boilerplate Formatter extension for multiple custom parameters more or less obsolete, unless you benefit from its application-wide reuse. In (my) simple scenarios, log messages are tailored to the code part where it is inserted, so
String.format()
is usually much easier and more flexible.Before Java 8 and lambdas, the
Formatter
was the only possibility to postpone the message construction. The only alternative was, to construct the message to log in advance before theloggable
check based on the Level took place.With Java 8 lambdas, the String formatting can be postponed to after the
loggable
check, but still with access to the original method context. The only small downside is, that all accessed fields need to be final, due to the lambda restrictions.Here a fairly simple snippet:
Hope this helps some of you who also want to use the built-in logging :-)
Cheers Ben