Mr. Brickowski
Mr. Brickowski

Reputation: 1181

Referencing java class variable from log4j2.xml configuration

I am using log4j2 and using log4j2.xml for its configuration. I am configuring the PatternLayout and its pattern currently is %d [%t] %p %c - %m%n. It is the same value as PatternLayout.SIMPLE_CONVERSION_PATTERN defined in log4j2 core Javadoc. So is it possible to reference this variable instead of copy the value into the xml?

My full log4j2.xml is attached for your reference.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="consoleAppender" target="SYSTEM_OUT">
            <PatternLayout pattern="%d [%t] %p %c - %m%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Root level="ALL">
            <AppenderRef ref="consoleAppender" />
        </Root>
    </Loggers>
</Configuration>

Upvotes: 3

Views: 1790

Answers (1)

dan
dan

Reputation: 13272

You have at least the following choices:

  1. Use an environment variable, like: <PatternLayout pattern="${env:MY_PATTERN}" />. And define the variable before the logger is initialized, with: System.setProperty("MY_PATTERN",PatternLayout.SIMPLE_CONVERSION_PATTERN).
  2. Or, if you need the pattern to be defined at runtime based on some conditions, you can define your own Logger class with a custom appender, something like (this is using the file appender, but you will get the idea):

    public class MyLogClass {
    
     private static Logger log =  Logger.getLogger(MyLogClass.class);
     private static boolean initFlag = false;
    
     private static void initLogger(){
       log.setLevel(Level.DEBUG);
    
       DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
       Date date = new Date();
    
       RollingFileAppender appender = new RollingFileAppender();
       appender.setAppend(true);
       appender.setMaxFileSize("1MB");
       appender.setMaxBackupIndex(1);
       appender.setFile("my_log_file-" + dateFormat.format(date) + ".log");
    
       PatternLayout layOut = new PatternLayout();
       layOut.setConversionPattern(PatternLayout.SIMPLE_CONVERSION_PATTERN);
       appender.setLayout(layOut);
    
      log.addAppender(appender);
     }
    
     public static Logger getLogger(){
       if(initFlag == false){
          initLogger();
          initFlag = true;
          return MyLogClass.log;
       } else {
          return MyLogClass.log;
       }
     }
    }
    

Then use it like:

LogClass.getLogger().debug("test");

Upvotes: 2

Related Questions