Search code examples
javajunitlog4jlog4j2

Get Log4j2 log file location to write to directory containing a date


How can I get the location of a log4j log file? I tried this: Where can i programatically find where the log4j log files are stored?

But it doesn't work for newer versions of log4j.

I am creating the file with the system date inside it, but when I retrieve the path, the time stamp would have changed.


Solution

  • If you have configured an appender as follows:

    <File name="Technical" 
          fileName="app/${date:yyyy-MM-dd HHmmss}/logTechnical.log">
      <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
    </File>
    

    You can get the directory as follows:

    import java.io.File;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import org.apache.logging.log4j.core.LoggerContext;
    import org.apache.logging.log4j.core.appender.FileAppender;
    import org.apache.logging.log4j.core.config.Configuration;
    
    ...
    
    LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    Configuration config = ctx.getConfiguration();
    FileAppender techical = (FileAppender) config.getAppender("Technical");
    File dir = new File(techical.getFileName().replaceFirst("[^\\/]+$", ""));