java logger dynamically change a field
I need to change our log format.
Now the log looks like:
[Thread ID] TIME ClassName
Content
I need to add a field in the header, and this field can only be determined at logging time:
[Thread ID] TIME ClassName NewField
Content
Here when we need to log something, we want to add a dynamically changing field, which is a system related information.
I cannot easily move it to the beginning of the Content, because in this way, I need to change all the places where call the logger开发者_StackOverflow中文版.warning or logger.info and so on.
There is a common place (entry point) for subsequent code, I can set the value of this new field here. Later on, when logger.warning("XXX") get called, it could recognize the value.
Can I achieve this?
Maybe you can do it by subclassing/creating your own implementation of the Logger, LogRecord and Formatter. The Logger would get an extra field which you set, and is also added to the LogRecord at the moment of logging. The Formatter should take care of including that value in the header.
If NewField is something coming out of the environment, you could see if there is a way to do it with log4j.
In any case, you will be refactoring. It might very well be the case that it is easier to just find all the info()
, warn()
etc methods and prepend the information here.
精彩评论