在 Spring 引导中向日志文件添加时间戳?

Adding timestamp to log file in Spring Boot?

我目前在我的应用程序中使用 Spring Boot,我知道它使用 Logback 作为其默认日志记录实现。

目前在我的 applications.properties 文件中有以下内容:

#some other properties

#logging details
logging.path= path/to/my/log/folder

这当前记录到一个文件:spring.log 在我的输出文件夹中。

如何更改此文件,使其包含创建时间的时间戳和日期

例如 - "my-application-log-DATE-TIME.log"

在 appender 中,尝试添加:

<layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>
                %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
            </Pattern>      </layout>

删除 .properties 文件样式配置并使用 logback 的正确配置 - logback.xml。 Spring Boot为此做好了充分的准备!这是一个例子:

<property name="logPattern" value="%d %-5level %logger{35} - %msg%n"/>
<property name="logEncoding" value="UTF-8"/>
<property name="logDirectory" value="logs"/>

<appender name="fileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>${logDirectory}/myapplication.log</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
        <fileNamePattern>${logDirectory}/myapplication_%d{yyyy-MM-dd}.%i.log</fileNamePattern>
        <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
            <maxFileSize>30MB</maxFileSize>
        </timeBasedFileNamingAndTriggeringPolicy>
    </rollingPolicy>
    <encoder>
        <charset>${logEncoding}</charset>
        <pattern>${logPattern}</pattern>
    </encoder>
</appender>

<logger name="org.springframework" level="warn"/>

<root level="INFO">
    <appender-ref ref="fileAppender"/>
</root>

这不仅会向日志文件添加时间戳,还会帮助您进行日志轮换(例如,它会保留旧日志,直到它们达到一定大小,等等)。

你的做法是对的。使用Spring Boot 的property support 自定义您的application.properties 文件。

    // application.properties file
app.name=appname
logging.path=logpath
logging.file=${appname}-{timestamp}.log

另一方面,在您的支持下 class,您可以创建一个 url 助手来获取 属性 值:

    /**
 * Helper class to get configured urls.
 */
@Component
public class UrlHelper {

    @Inject
    private Environment env;

    private static final String LOGGING_TIMESTAMP = "{timestamp}";

private static String loggingFileUrlPattern;

/**
     * Initializes properties.
     */
    @PostConstruct
    public void initProperties() {

        loggingFileUrlPattern = env.getRequiredProperty("logging.file");
    }

/**
     * Formats the loggin Url pattern application property with the current
     * timestamp
     * 
     * @param timestamp
     *            current timestamp.
     * @return The complete logging file url.
     */

    public static String buildLoggingFileUrl(String timestamp) {
        return loggingFileUrlPattern.replace(LOGGING_FILE_URL, timestamp);
    }
}

希望对您有所帮助!