在RollingFileAppender上调用rollover()时出现空指针异常

时间:2019-01-21 13:52:07

标签: logging log4j

我在应用程序中使用的是log4j Logger,它具有基于时间和文件大小的过渡策略(因此文件大小不会超过10MB,而且每天还会获取新文件)。我想添加手动转换到新文件的功能(我们有时会发送日志,并希望新日志文件在发送后开始运行)

private static void configureLogbackDirectly(Activity activity, String macAddress) {
    if(!logDir.exists()){
        if(!logDir.mkdir()){
            Log.e("Logger","unable to create logs folder");
        }
    }

    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.reset();
    PatternLayoutEncoder logcatEncoder = new PatternLayoutEncoder();
    logcatEncoder.setPattern("[%thread] %-5level %marker: %msg%n");
    logcatEncoder.setContext(context);
    logcatEncoder.start();

    LogcatAppender logcatAppender= new LogcatAppender();
    logcatAppender.setCheckLoggable(true);
    logcatAppender.setEncoder(logcatEncoder);
    logcatAppender.setName(logcatAppenderName);
    logcatAppender.start();

    RollingFileAppender<ILoggingEvent> rollingFileAppender = new ExtraRollingFileAppender();
    rollingFileAppender.setAppend(true);
    rollingFileAppender.setContext(context);
    rollingFileAppender.setName(rolloverAppenderName);

    TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<>();
    SharedPreferences sp = activity.getApplicationContext().getSharedPreferences(activity.getPackageName(), 0);
    String deviceId = myApp.GetDeviceID();
    rollingPolicy.setFileNamePattern(logDir.getAbsolutePath() +"/" + deviceId + "_" + filePrefix + "_%d{yyyyMMdd}.%i.log");
    rollingPolicy.setMaxHistory(21);
    rollingPolicy.setParent(rollingFileAppender);
    rollingPolicy.setContext(context);


    SizeAndTimeBasedFNATP<ILoggingEvent> sizeAndTimeBasedFNATP = new SizeAndTimeBasedFNATP<>();
    sizeAndTimeBasedFNATP.setMaxFileSize(FileSize.valueOf("10MB"));
    sizeAndTimeBasedFNATP.setContext(context);
    sizeAndTimeBasedFNATP.setTimeBasedRollingPolicy(rollingPolicy);

    rollingPolicy.setTimeBasedFileNamingAndTriggeringPolicy(sizeAndTimeBasedFNATP);
    rollingPolicy.start();
    sizeAndTimeBasedFNATP.start();
    rollingFileAppender.setRollingPolicy(rollingPolicy);

    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %marker: %msg%n");
    encoder.setContext(context);
    encoder.start();

    rollingFileAppender.setEncoder(encoder);
    rollingFileAppender.start();

    ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(LOGGER_NAME);
    root.setLevel(Level.INFO);
    root.addAppender(logcatAppender);
    root.addAppender(rollingFileAppender);


    Logger.logger=root;
}

所以我有了这个新功能

public static void startNewLogFile() {
    ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger)Logger.logger;
    RollingFileAppender appender = (RollingFileAppender) root.getAppender(rolloverAppenderName);
    if (appender == null) {
        return;
    }
    appender.rollover();
}

但是当我调用新函数时,会出现如下错误:

01-21 07:56:52.824 17816-17816/com.company.Application E/com.Company.APP: [main] ERROR general_logs: uncaughtException: 
    java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.lastIndexOf(int)' on a null object reference
        at ch.qos.logback.core.rolling.helper.FileFilterUtil.afterLastSlash(Unknown Source)
        at ch.qos.logback.core.rolling.TimeBasedRollingPolicy.rollover(Unknown Source)
        at ch.qos.logback.core.rolling.RollingFileAppender.attemptRollover(Unknown Source)
        at ch.qos.logback.core.rolling.RollingFileAppender.rollover(Unknown Source)
        at com.company.Application.logging.Logger.startNewLogFile(Logger.java:125)

我可以看到有关此Here的问题,但我想知道是否有人对我有解决方法

1 个答案:

答案 0 :(得分:0)

即使使用logback v1.2.3,我也遇到相同的问题,但是胜过了:

// logback.groovy (part):

file = 'foo.log'

rollingPolicy(SizeAndTimeBasedRollingPolicy) {
  maxFileSize = '1MB'
  fileNamePattern = "foo.%d{yyyy-MM-dd}.%i.log"
  maxHistory = 3
  totalSizeCap = '1GB'
}

//component.rollover()  // leads to NPE: https://stackoverflow.com/q/54291436/1915920

因此在开始时进行过渡的解决方法可以是使用应用程序启动时间戳,如下所示:

// logback.groovy (part):

def ts = new Date().format('yyyy-MM-dd.HH-mm-ss')  // workaround to rollover at start: https://stackoverflow.com/q/54291436/1915920
file = "foo.${ts}.log"

rollingPolicy(SizeAndTimeBasedRollingPolicy) {
  maxFileSize = '1MB'
  fileNamePattern = "foo.${ts}.%d{yyyy-MM-dd}.%i.log"
  maxHistory = 3
  totalSizeCap = '1GB'
}