Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change priority level in log4j per request

I am new with Logging and Log4j. What I want to do is change logger level per request. This means:

Normally, the priority level is set to ERROR, but a user can call the server with a special parameter to set the priority log level to DEBUG, but only for that user/request.

This means that if a user A sends a request http://myServer.com/test it logs only those message that have a priority of ERROR.

But if a user A sends a request http://myServer.com/test?debug=true, the logger logs all messages, however if user B simultaneously sends requests http://myServer.com/test only ERROR messages are logged.

It would be good if those logs can be saved in new appenders.

like image 779
Marko Zadravec Avatar asked Jun 11 '14 08:06

Marko Zadravec


People also ask

Can we change log level at runtime?

In terms of scaling, the challenge is to change log levels in each instance. So to avoid all pitfalls following is needed: Dynamically change the log level at runtime without application restart. Propagation of log level changes across the application instances.

How do I change the log4j properties at runtime?

Use LogManager. resetConfiguration(); to clear the current config and configure it again. Another approach is to build a new appender and replace the old one with it (most appenders don't support changing their config). This way, all the loggers (and their levels, etc) stay intact.

Which of the following is correct order for log4j levels?

Log4j Level Order/Priority Trace < Debug < Info < Warn < Error < Fatal.


1 Answers

I think you should use Log4j Filters.

Have this in your log4j2.xml configuration:

<DynamicThresholdFilter key="X-Log-Level" onMatch="ACCEPT" onMismatch="NEUTRAL" defaultThreshold="ERROR">
    <KeyValuePair key="TRACE" value="TRACE"/>
    <KeyValuePair key="DEBUG" value="DEBUG"/>
</DynamicThresholdFilter>

(...) And set up a filter in your request that will assign "X-Log-Level" to the Thread Context via, for example, MDC.

// Replace the hardcoded logLevel value with something dynamic,
// ideally from the http request header.
String logLevel = "DEBUG";
MDC.put("X-Log-Level", logLevel);
like image 94
juliaaano Avatar answered Oct 02 '22 07:10

juliaaano