Java 在Spring引导中向日志文件添加时间戳?
我目前正在我的应用程序中使用Java 在Spring引导中向日志文件添加时间戳?,java,spring,properties,timestamp,logback,Java,Spring,Properties,Timestamp,Logback,我目前正在我的应用程序中使用springboot,我知道它使用Logback作为默认的日志记录实现 当前在我的应用程序.properties文件中,我有以下内容: #some other properties #logging details logging.path= path/to/my/log/folder 这当前记录到我的输出文件夹中的文件:spring.log 如何更改此文件,使其包含时间戳和创建日期 例如,“我的应用程序日志日期时间.log”在附录中,尝试添加以下内容: <
springboot
,我知道它使用Logback
作为默认的日志记录实现
当前在我的应用程序.properties
文件中,我有以下内容:
#some other properties
#logging details
logging.path= path/to/my/log/folder
这当前记录到我的输出文件夹中的文件:spring.log
如何更改此文件,使其包含时间戳和创建日期
例如,“我的应用程序日志日期时间.log”在附录中,尝试添加以下内容:
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
</Pattern> </layout>
%d{yyyy-MM-dd HH:MM:ss}[%thread]-5级别%logger{36}-%msg%n
删除.properties文件样式配置,并使用logback的正确配置-logback.xml。弹簧靴已为此做好充分准备!下面是一个例子:
${logDirectory}/myapplication.log
${logDirectory}/myapplication\%d{yyyy-MM-dd}。%i.log
30MB
${logEncoding}
${logPattern}
这不仅会在日志文件中添加时间戳,还可以帮助您进行日志轮换(例如,它将保留旧日志,直到它们达到特定大小等)。您这样做是正确的。使用Spring Boot自定义application.properties文件
// application.properties file
app.name=appname
logging.path=logpath
logging.file=${appname}-{timestamp}.log
另一方面,在支持类中,可以创建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);
}
}
希望有帮助 我不知道你说的appender是什么意思?谢谢,我应该把它放在我的项目中的什么地方?假设您有一个基于maven的项目,只需创建一个名为logback.xml的文件并将其放在src/main/resources下,然后将内容复制到该文件中。另外,我犯了一个错误,没有在这里复制整个文件。。。以开始文件,以结束文件,使其成为一个正确的XML。检查此链接以获取两个完整的logback配置示例。我实现了相同的代码,但我无法获得定义的最大大小的文件,而且每个文件的滚动文件的大小随后会加倍,我是否遗漏了什么。结果是
没有为c.q.l.core.rolling.SizeAndTimeBasedRollingPolicy提供上下文
/**
* 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);
}
}