Log4J: can I enable/disable logging from a class at runtime?

安稳与你 提交于 2019-12-11 05:29:56

问题


Sometimes logging needs to be enabled/disabled at runtime only during a specific phase of the execution of a code (e.g. for debugging purposes). Now, I use Java and Log4J to debug. This is my log4j.properties file:

# Define the root logger with appender file
log = /Users/Admin/Documents/log4j
log4j.rootLogger = DEBUG, stdout, file

#Logging for class Solution in package org.solver will be disabled
log4j.category.org.solver.Solution = OFF, stdout, file

# Define the file Console appender
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# Define the file file appender
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=${log}/log.out

# Define the layout for file appender
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.conversionPattern=%m%n

As you may see, I log both on a file and on the console output.

Now, suppose that I have a class X from package foo. How can I enable and disable the logging at runtime? Here I found a possible answer, but an example would be really appreciated.


回答1:


Try using something like :

LogManager.getRootLogger().setLevel(Level.DEBUG);

You can also get the exact logger passing class into the get.



来源:https://stackoverflow.com/questions/24322573/log4j-can-i-enable-disable-logging-from-a-class-at-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!