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.
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.
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.
Log4j Level Order/Priority Trace < Debug < Info < Warn < Error < Fatal.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With