1

I have a log4j.xml config file. I want to change log level if environmental variables changes. I have multiple environmental which are DEVELOP, TEST, PREPROD etc. How can I do this?

DEVELOP:

 <Loggers>
    <Root level="debug">
        <AppenderRef ref="Console"/>
    </Root>
 </Loggers>

TEST:

 <Loggers>
    <Root level="error">
        <AppenderRef ref="Console"/>
    </Root>
 </Loggers>
Arif Acar
  • 1,461
  • 2
  • 19
  • 33

2 Answers2

0

I would say create several appenders, one for each setting and with its own log level. Then decide at runtime which one to get, and fetch the logger accordingly.

For example:

log4j.rootLogger=WARN
log4j.com.yourcompany.package1= DEBUG, appender1, stdout
log4j.com.yourcompany.package2= INFO, appender2, stdout

Then define appender1 and 2 in the file. You can enter the same output file to the two appenders. When creating the logger in Java, you can choose between the two:

final Logger log = Logger.getLogger(package1.Class1.class);
// final Logger log = Logger.getLogger(package2.Class2.class);

I didn't test it, but I think it works. I believe you can also use class names instead of package names in log4j.xml definitions.

GregT
  • 1,039
  • 4
  • 14
  • 34
0

I came into the same situation and I did below,

Have separate log4j configurations with the suffix as the environment.

log4j-<ENVIRONMENT>.xml

In your logger factory class or in the minus d options pass the environment and pick the correct file,

String log4jFile = "/log4j-" + System.getProperty("ENVIRONMENT") + ".xml";
String url = LoggerFactory.class.getResource(log4jFile); 
org.apache.log4j.xml.DOMConfigurator.configure(url);
Praveen
  • 1,791
  • 3
  • 20
  • 33