log4j record-like log
I want log4j to produce record-like output.
What I DON'T want:
1 INFO ... - User login: Agostino
120 INFO ... - Start process: 0, elements to process 100
What I want:
1 INFO ... - User: Agostino, processid:null, elements: null, message: login
1 INFO ... - User: Agostino, processid:0, elements: 100, message: start process
I think I should use a ObjectRenderer, and since many data are contained in objects that I already have, so I think something like:
public class MyMessage {
Object myContextObject; //**this** contains user, processid, elements
String message;
}
What I am doing here is passing a "context object" that p开发者_如何学JAVArovides fields PLUS a message string. An ObjectRenderer then will do the formatting, based on myContextObject type.
Now i'm wondering if ObjectRenderer is designed with something like this in mind. If this was the normal use of ObjectRenderer, probably they'd provide a log(String message, Object myContextObject) that prevent the creation of the dummy wrapper MyMessage.
As an alternative to the ObjectRenderer
, You might want to look into log4j's PatternLayout
, which can be configured programmatically, or configuratively:
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html
for instance, you can do something like this (just an arbitrary example):
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p (%-35F:%-4L) - %m%n"/>
</layout>
</appender>
Once you've established that, you can use the %X{clientNumber}
pattern for retrieving data from your custom classes via MDC
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/MDC.html
精彩评论