Log4J: can I enable/disable logging from a class a

2019-07-24 23:35发布

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条回答
Juvenile、少年°
2楼-- · 2019-07-25 00:16

Try using something like :

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

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

查看更多
登录 后发表回答