java123999 java123999 - 2 years ago 216
Java Question

Adding timestamp to a log file using Logback-test.xml

Currently my Spring-boot application logs to a file named:

, this is working as intended, however I would like the log file to have a
at the end of it and create a new file each time it is ran.

I have tried to implement this in my
file shown below, but it is just giving me the filename: myLog.log without a timestamp.

How can I fix this?


<?xml version="1.0" encoding="UTF-8"?>
<include resource="org/springframework/boot/logging/logback/base.xml"/>

<logger name="org.springframework.web" level="INFO"/>

<!-- Send debug messages to System.out -->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- By default, encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder -->
<pattern>%d{HH:mm:ss.SSS} - %msg%n</pattern>

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} - %msg%n</Pattern>

<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">

<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">

<logger name="" level="INFO" additivity="false">
<appender-ref ref="STDOUT" />
<appender-ref ref="FILE" />

<!-- By default, the level of the root level is set to DEBUG -->
<root level="INFO">
<appender-ref ref="STDOUT" />


Answer Source

You can define a variable like this:

<timestamp key="myTimestamp" datePattern="yyyy-MM-dd'_'HH-mm-ss.SSS"/>

(note: don't use colons in datePattern)

Then use it directly in your appender's file element:

 <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">

Or in a simple FileAppender:

<appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <Pattern>%d{yyyy-MM-dd_HH:mm:ss.SSS} - %msg%n</Pattern>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download