public void addFileAppender ( final String fileName , final String deviceName ) throws DevFailed { if ( rootLoggerBack != null ) { logger . debug ( "add file appender of {} in {}" , deviceName , fileName ) ; final String deviceNameLower = deviceName . toLowerCase ( Locale . ENGLISH ) ; final File f = new File ( fileName ) ; if ( ! f . exists ( ) ) { try { f . createNewFile ( ) ; } catch ( final IOException e ) { throw DevFailedUtils . newDevFailed ( ExceptionMessages . CANNOT_OPEN_FILE , "impossible to open file " + fileName ) ; } } if ( ! f . canWrite ( ) ) { throw DevFailedUtils . newDevFailed ( ExceptionMessages . CANNOT_OPEN_FILE , "impossible to open file " + fileName ) ; } // debug level by default // setLoggingLevel(deviceName, LoggingLevel.DEBUG.toInt()); System . out . println ( "create file " + f ) ; final LoggerContext loggerContext = ( LoggerContext ) LoggerFactory . getILoggerFactory ( ) ; final FileAppender rfAppender = new FileAppender ( deviceNameLower ) ; fileAppenders . put ( deviceNameLower , rfAppender ) ; rfAppender . setName ( "FILE-" + deviceNameLower ) ; rfAppender . setLevel ( rootLoggingLevel ) ; // rfAppender.setContext(appender.getContext()); rfAppender . setFile ( fileName ) ; rfAppender . setAppend ( true ) ; rfAppender . setContext ( loggerContext ) ; final FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy ( ) ; // rolling policies need to know their parent // it's one of the rare cases, where a sub-component knows about its parent rollingPolicy . setParent ( rfAppender ) ; rollingPolicy . setContext ( loggerContext ) ; rollingPolicy . setFileNamePattern ( fileName + "%i" ) ; rollingPolicy . setMaxIndex ( 1 ) ; rollingPolicy . setMaxIndex ( 3 ) ; rollingPolicy . start ( ) ; final SizeBasedTriggeringPolicy < ILoggingEvent > triggeringPolicy = new SizeBasedTriggeringPolicy < ILoggingEvent > ( ) ; triggeringPolicy . setMaxFileSize ( FileSize . valueOf ( "5 mb" ) ) ; triggeringPolicy . setContext ( loggerContext ) ; triggeringPolicy . start ( ) ; final PatternLayoutEncoder encoder = new PatternLayoutEncoder ( ) ; encoder . setContext ( loggerContext ) ; encoder . setPattern ( "%-5level %d %X{deviceName} - %thread | %logger{25}.%M:%L - %msg%n" ) ; encoder . start ( ) ; rfAppender . setEncoder ( encoder ) ; rfAppender . setRollingPolicy ( rollingPolicy ) ; rfAppender . setTriggeringPolicy ( triggeringPolicy ) ; rfAppender . start ( ) ; rootLoggerBack . addAppender ( rfAppender ) ; rfAppender . start ( ) ; // OPTIONAL: print logback internal status messages // StatusPrinter.print(loggerContext); } }
Add an file appender for a device