I am using Java 1.7 and Log4j2 (beta9) and I have the following log4j2.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="info">
  <Appenders>
    <Console name="CONSOLE" target="SYSTEM_OUT">
      <PatternLayout pattern="[%d{dd/MMM/yyyy HH:mm:ss.SSS}]> %-5p - %m%n"/>
    </Console>

    <RollingFile name="RollingFile" fileName="logs/foo.log" filePattern="logs/foo-%d{dd-MMM-yyyy}-%i.log">
        <Policies>
            <OnStartupTriggeringPolicy/>
        </Policies>
        <DefaultRolloverStrategy fileIndex="max" max="10"/>
        <PatternLayout pattern="[%d{dd/MMM/yyyy HH:mm:ss.SSS}]> %-5p - %m%n"/>
    </RollingFile>

    <Async name="ASYNC">
      <AppenderRef ref="RollingFile"/>
      <AppenderRef ref="CONSOLE"/>
    </Async>
  </Appenders>

  <Loggers>
    <Root level="debug">
      <AppenderRef ref="ASYNC"/>
    </Root>
  </Loggers>
</Configuration>

And as far as the logging itself goes, it does what I need.

As part of the error/exception sequence, I need to send an email with the log file as an attachment.

How do I programmatically get the 'fileName="logs/foo.log"' bit? I would really hate to have to hard code this.

有帮助吗?

解决方案

From the Logger, iterate through all getAllAppenders looking for the one that implements RollingFileAppender, and call getFile on it. Or you could use getAppender("RollingFile") instead, if you don't mind hard-coding the appender's name.

For Log4j 1:

public static final Logger LOG = Logger.getLogger(YourClass.class);

public File getLoggerFile() {
  Appender appender = LOG.getAppender("RollingFile");
  return appender.getFile();
}

For Log4j 2: (note that this requires the non-interface logger)

public static final Logger LOG = LogManager.getLogger(YourClass.class);

public String getLoggerFileName() {
  org.apache.logging.log4j.core.Logger loggerImpl = (org.apache.logging.log4j.core.Logger) LOG;
  Appender appender = loggerImpl.getAppenders().get("RollingFile");
  // Unfortunately, File is no longer an option to return, here.
  return ((RollingFileAppender) appender).getFileName();
}

其他提示

Paul's answer was correct with a minor modification:

public static String getLoggerFile( Logger log ) {
    org.apache.logging.log4j.core.Logger loggerImpl = (org.apache.logging.log4j.core.Logger) log;
    Appender appender = loggerImpl.getAppenders().get("RollingFile");
    return ((RollingFileAppender) appender).getFileName();
}

All credit for the answer goes to Paul!

Alternative method with less class casting:

        RollingFileAppender appender = (RollingFileAppender) LoggerContext.getContext().getConfiguration()
        .getAppenders().get("myRfAppenderName");
    String logFile = appender.getFileName();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top