[logback-user] FileAppender : change log filename at runtime with a datePattern

Alessio Pollero alessio.pollero at gmail.com
Sun Dec 4 21:10:44 CET 2011


Hi to all, 
i just switched to logback from log4j now and i want to change at runtime some settings contained in the logback.xml configuration file.
I have a logback.xml configuration file that looks like the following : 

<configuration>

 <property name="defaultPattern"
        value="%d{dd/MM/yyyy HH:mm:ss.SSS} [%thread] %-5level - %msg%n" />

 <!-- Appenders Configuration -->
  <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <target>System.err</target>
    <filter class="com.aleroot.ErrOutFilter" />
    <encoder>
      <pattern>${defaultPattern}</pattern>
    </encoder>
  </appender>
 
  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>aleroot.log</file>
    <append>true</append>
    <encoder>
      <pattern>${defaultPattern}</pattern>
    </encoder>
  </appender>
  
  
  <!-- Output Configuration -->
  <root level="debug">
    <appender-ref ref="FILE" />
    <appender-ref ref="CONSOLE"/>
  </root>
  
  <logger name="mainLogger" level="debug">
    <appender-ref ref="FILE" />
    <appender-ref ref="CONSOLE"/>
</logger>
  
</configuration>


i want to change the file property of the FILE appender at runtime and add a DatePattern to the filename, i've tried with this code : 

LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
	      ch.qos.logback.classic.Logger logbackLogger = lc.getLogger("mainLogger");
	      FileAppender<ILoggingEvent> fileAppender =
                  (FileAppender<ILoggingEvent>) logbackLogger.getAppender("FILE");
		      if(fileAppender != null) {
		        fileAppender.stop();
		        fileAppender.setFile("aleroot-ddMMyyyy.log");
		        fileAppender.setContext(lc);
		        fileAppender.start();
		      }

The problem is that the file aleroot.log is created anyway also if i have changed the filename, furthermore i get another file that is named exactly : aleroot-ddMMyyyy.log while i want to have a filename like aleroot-04122011.log . How can i achieve that ? 

Is there a settings to avoid that the log file will be created at the LoggerFactory.getLogger("mainLogger")  call ? I want that the log file will be created only the first time that i write into the log files, there is no need to create an empty log file .
The log file should be created the first time that i log something to the log, for example at the first logger.debug("Something.log") , Is there a settings to achieve that ? 

Thanks.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.qos.ch/pipermail/logback-user/attachments/20111204/80204173/attachment.html>


More information about the Logback-user mailing list