Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding date to logback.xml

Tags:

xml

slf4j

Have tried to search for it but I keep on getting ...IS_UNDEFINED as my file name. I simply want to append the current date to a log file. Any simple example for the logback.xml file?

This is my latest try:

<Properties>
  <property name="filePattern">log_${date:yyyy-MM-dd}.log</property>
</Properties>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
  <file>${application.home:-.}/logs/${filePattern}</file>
  <encoder>
    <pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern>
  </encoder>
</appender>
like image 857
Jesper Avatar asked Jul 11 '17 09:07

Jesper


2 Answers

Regular FileAppender does not support patterns in filenames, so you have to use RollingFileAppender + TimeBasedRollingPolicy instead.

RollingFileAppender extends FileAppender with the capability to rollover log files. For example, RollingFileAppender can log to a file named log.txt file and, once a certain condition is met, change its logging target to another file.

TimeBasedRollingPolicy is both easy to configure and quite powerful. It allows the roll over to be made based on time. It is possible to specify that the roll over occur once per day, per week or per month.

Like this:

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
      <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${application.home:-.}/logs/log_.%d{yyyy-MM-dd}.log</fileNamePattern>
      </rollingPolicy>
  <encoder>
    <pattern>%date [%level] from %logger in %thread - %message%n%xException</pattern>
  </encoder>
</appender>
like image 168
zeppelin Avatar answered Oct 25 '22 21:10

zeppelin


I figured it out like this:

  <timestamp key="timestamp" datePattern="yyyyMMdd"/>

  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>${application.home:-.}/logs/log_${timestamp}.log</file>
    <encoder>
      <pattern>%date [%level] - %message%n%xException</pattern>
    </encoder>
  </appender>
like image 35
Jesper Avatar answered Oct 25 '22 23:10

Jesper