How to modify a message in Log4J 2? - java

I'm trying to MODIFY, not DENY, certain messages before being logged using Log4J 2. I'm currently trying to use a Filter, but I can't seem to be able to modify a message from any of it's methods.
Please be patient with me as I'm totally new to Log4j.

Log4j purposely does not let you modify the LogEvent as it might get passed on to other Filters and Appenders that expected the original event. However, the RewriteAppender will let you create a copy of the LogEvent that is modified and then pass that to a subordinate Appender. The RoutingAppender also supports a RewritePolicy that does the same thing.

Related

Differentiate logging informations of multiple instances of the same class

I'm trying to log the methods call chain of some classes instances of a Java program using Log4j2. Each instance will behave differently based on the inputs they will recive (obviously).
The problem I'm facing is differentiating the logging messages of each instances for easly reconstructing the methods call chains I was talking about.
In addition to logging the entering and the leaving of each method, which is the default logging schema I'm using, I've tried to:
add method call parameters to the log: too few informations and not very readable;
add more informations about the method behaviour: too verbose and not very readable;
adding instance hash code to all the logging messages, which will become something like LOG.trace("{} - Leaving constructor(index:{})", System.identityHashCode(this), index);: good solution, but I've to add some boilerplate code to all the logging methods, which makes the code a little less readable;
using per-instance loggers (so not the per-class/static one) and adding the instance hash code in the logger name (so the logger name will be Classname#hashcode): seems the best solution in clean code terms, but I didn't found any way for declaring logger settings (like logging threshold) for multiple loggere, i.e. for all the loggers which name starts with Classname.
Which one do you think will be the best solution, or do you have any other way to suggest?
For this requirement, you can easily use an nested thread context: Look at "Fish Tagging" in https://logging.apache.org/log4j/2.x/manual/thread-context.html .
Excerpt:
ThreadContext.push(UUID.randomUUID().toString()); // Add the fishtag;
logger.debug("Message 1");
.
.
.
logger.debug("Message 2");
.
.
ThreadContext.pop();

Pass log event specific data with slf4j (and log4j)

Is there a way to pass further information which just applies to the current log event with slf4j? Request based information like user, ip address or application name can be stored and accessed via the MDC. Later I can access that information in a layout or a converter and dont have to parse the log message. If I use a JSON based format I have another field with "appName":myApp and if I log with log4j in plaint text I can access it via the %{appName} notation.
Is there a way to achieve this with information which just applies to one log event? For example I want to pass an exception id(even for exceptions I do not own). The best but still ugly solution is to pass the id to the MDC, log the exception and delete it afterwards. Does anyone know a better solution?
If you don't need to use slf4j and log4j is good enough - you can use custom messages with log4j: https://logging.apache.org/log4j/2.x/manual/messages.html
If you want slf4j - you could implement your own Logger adapter which would treat any extra parameters appropriately (just like http://www.slf4j.org/xref/org/slf4j/impl/JDK14LoggerAdapter.html)

Filtering a subclass in log4j

I have a message driven system with, say, com.example.BaseMessagingAgent class, which is a basic class for many message agents. This base class logs message events. There are many subclasses of this base class, implementing different specific agents of system. Let us com.example.MyAgent which extends com.example.BaseMessagingAgent is one of them.
I want to log messages only related to class MyAgent. But I cannot define logging as:
log4j.logger.com.example.MyAgent=DEBUG, APPENDER
because logging occurs in parent class com.example.BasicMessagingAgent - I will record nothing.
And I also do not want to set logging in base class:
log4j.logger.com.example.BaseMessagingAgent=DEBUG, APPENDER
because it will log events for all agents, and I will have a lot of unnecessary logging.
Does enyone know how to limit logging to only one subclass?
You should write a filter for Log4j since AFAIK there is no way to put such information on log4j.properties file. More details at http://books.google.it/books?id=vHvY008Zq-YC&lpg=PA95&ots=yi335bZU7z&dq=&pg=PA95#v=onepage&q&f=false
It's pretty simple, actually.
First, add the appender to the root logger. Really. It will make your life much more simple.
Now configure the whole thing:
log4j.rootLogger=DEBUG, APPENDER
log4j.logger.com=ERROR
log4j.logger.com.example.MyAgent=DEBUG
The default for all classes below "com.*" will be to log only errors. The sole exception is com.example.MyAgent which will log at debug level.
You need to set the root logger to DEBUG as well or it will throw away all the DEBUG log messages.
The next step is to use one logger per instance. To get that, simply remove the static in the line which you create your logger and replace BaseMessagingAgent with getClass()
I know, it looks like overkill but that's how log4j works. Also creating a logger per instance isn't very expensive (unless you create millions of MyAgent per second).
If you really want to add an appender to a single class, then don't forget to turn off additivity (...Class.additivity=false) or you will get all log messages twice.

Log to a different file according to thread

I have an application with multiple "controllers", and I'd like to have each log to their own file. This is easy enough for their own code, but I'm also using some library code which uses commons logging. Could I somehow get that code to log to the controller-specific file as well?
I was thinking I could somehow do it by thread:
class Controller {
public void action() {
setCurrentThreadLogFile(myLogFile);
try {
Library.stuff();
} finally {
restoreCurrentThreadLogFile();
}
}
}
Currently I'm using commons-logging for my own logging as well, with log4j as backend. But I could change that, if needed, or use a mix (is that's possible within the commons logging framework).
One way I could do this would be to write my own commons logging implementation (possibly a wrapper around log4j), but is there an existing solution?
You probably want to be looking at mapped diagnostic contexts (MDCs). Commons logging does not support these but Log4J does, so you would have to go directly to Log4J to set this up. You will probably have to roll your own filter to filter using the MDC and apply to the appenders.
If you willing to change logging implementations then you could use SL4J as the logging facade and Logback as the logging implementation. Have the controller or some sort of filter/interceptor add a discriminator value for a key you are going to use to discriminate the controllers with to the MDC. Use a SiftingAppender to separate the log event into separate files.
A logger per thread? Put the logger in a ThreadLocal. If you are using java.util.logging, a Handler could make this transparent to the caller.

log4j property configuration question

I have to stop showing logging messages of some methods within the system without changing a Java code (loggers)...
I was thinking, is it possible to configure log4j.properties, where I could skip the logging for certain method? and is it possible to do log on method level at all with log4j?
Thanks,
K.
log4j does not support this level of configuration. But you can implement an appender that will extends your current appender (for example, create a MyConsoleAppender that extends ConsoleAppender). Then, add a check for the method that you which to skip in the checkEntryConditions() method.

Categories