Thursday, 10 September 2015

How to set log file with custom name in log4j2?

Sometimes having log4j2.xml file with default naming can be a problem if several projects share the same classpath. In order to change logger file at runtime the below method can be used:


public static void logAppInfo(String configFileName) {
    URL fileUrl = SLF4JHello.class.getClassLoader().getResource(configFileName);
    if (fileUrl == null) {
        throw new RuntimeException("File not found: " + configFileName);
    }
    try {
    LoggerContext loggerContext = (LoggerContext) LogManager.getContext(false);
    loggerContext.setConfigLocation(fileUrl.toURI());
    loggerContext.updateLoggers();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

No comments:

Post a Comment