0
votes

I'm building an application that tails log files. To do this, I read the logback.xml file configuration, choose an appender by name, and extract the necessary information of the file to tail, and format of the messages in it.

Right now I can only tail log files that have a set file name, and I'm trying to tail files that have a patterned file name. But to avoid doing this complex check of every possible pattern, I was thinking about extracting the value of the file from the logger class itself. After investigating, I found that the RollingPolicyBase class has a method called getActiveFileName() that I suspect that has what I need (the file name of the log file at the moment the method is invoked), but for some reason I can't even find the logger for its name. Anyone tried something like this before, or knows if it's even possible to do?

My current logback (the important bits):

<appender name="DateRollingFileAppender"     class="ch.qos.logback.core.rolling.RollingFileAppender">    
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
  <fileNamePattern>logs/jwsgateway.%d{yyyyMMddHH}.log.zip</fileNamePattern>
  <maxHistory>1500</maxHistory>
</rollingPolicy>
<encoder>
    <pattern>%d{dd/MM/yy HH:mm:ss.SSS} [%thread] %-5level %logger{0} - %m%n     </pattern>
</encoder>      

My current code:

private static ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(MyClass.class);
RollingFileAppender appender=(RollingFileAppender)logger.getAppender("DateRollingFileAppender");
filePath=appender.getRollingPolicy().getActiveFileName();

The variable "appender" ends up null. Any suggestions?

1

1 Answers

1
votes

Logger#getAppender(String) gets an appender that is currently attached to the logger. Since "DataRollingFileAppender" is attached to the root logger, you would need to call LoggerFactory#getLogger(String) on Logger.ROOT_LOGGER_NAME to get the logger that would contain your appender:

import ch.qos.logback.classic.Logger;
import ch.qos.logback.core.rolling.RollingFileAppender;
import org.slf4j.LoggerFactory;

public class Main {
  public static void main(String[] args) {
    Logger logger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    RollingFileAppender appender=(RollingFileAppender)logger.getAppender("DateRollingFileAppender");
    System.out.println(appender.getRollingPolicy().getActiveFileName());
  }
}