How do I log a message in log4j2 independent of the set log level

457 Views Asked by At

I want to log a message regardless of which level my logger is set, except when the level is OFF. My understanding was that the following will do that.

logger.log(Level.ALL, <log message>);

However that doesn't work, unless I set my root logger level to all in the configuration file. I do not want to set logger configuration level to all, since I don't want debug, info messages in the log.

Other option is to write logger.trace() or logger.fatal(). However, semantically they are wrong since they will be marked as "TRACE" or "FATAL".

So, my question is (1) how to properly do it and (2) what are the right use cases of using Level.ALL in code?

1

There are 1 best solutions below

1
On

Level.ALL cannot be used as the level of an individual log event. It only can be used when filtering events. (Its actual value is Integer.MAX_VALUE which denotes a lower level than TRACE (600).)

Log4j2 allows you to define custom log levels; see https://logging.apache.org/log4j/2.x/manual/customloglevels.html.

So what you could do is to define a log level that is higher level than FATAL (100):

 final Level UNSUPPRESSABLE = Level.forName("UNSUPPRESSABLE", 1);

By default, the level name is what is output by the log formatters, but you can configure a Pattern to output something different. See the specification for the %level pattern.


However ... I think it is a bad idea to do this kind of thing in an application. It is unexpected. It is also taking away the customer's ability to control logging. Are these events really more important to the customer than FATAL? Is it up to you to make that call for the customer?

(In this case, the "customer" could be the people who manage your production servers. Or if you are currently responsible for that, they could be your successors: the people who take over when you are hit by the proverbial green bus on the way to work.)