【问题标题】:Define time limit using Log4j2 in configuration properties在配置属性中使用 Log4j2 定义时间限制
【发布时间】:2022-01-04 12:32:47
【问题描述】:

这是下面的配置参数,属于log4j2库。

status=all
name=PropertiesConfig
#Make sure to change log file path as per your need
property.filename=C:\\logs\\sms.log
filters=threshold
filter.threshold.type=ThresholdFilter
filter.threshold.level=all
appenders=rolling
appender.rolling.type=RollingFile
appender.rolling.name=RollingFile
appender.rolling.fileName=${filename}
appender.rolling.filePattern=C:\\logs\\sms-%d{MM-dd-yyyy}-%i.log
appender.rolling.layout.type=PatternLayout
appender.rolling.layout.pattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.rolling.policies.type=Policies
appender.rolling.policies.time.type=TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval=1
appender.rolling.policies.time.modulate=true
appender.rolling.policies.size.type=SizeBasedTriggeringPolicy
#appender.rolling.policies.size.size=10MB
appender.rolling.strategy.type=DefaultRolloverStrategy
appender.rolling.strategy.max=20
loggers=rolling
logger.rolling.name=com.company.Main
logger.rolling.level=all
logger.rolling.additivity=true
logger.rolling.appenderRef.rolling.ref=RollingFile

以下代码最多可写入 30 秒的日志消息。当它达到 30 秒时,进程终止并在日志文件夹中创建新文件。我在这里要做的是首先我想在我的 Log4j2 配置属性文件中将我的时间限制设置为 30 秒,我这样做的原因是因为我想在 30 秒后创建一个新文件并检查它是否会写入我的日志记录那里的消息。

    String s1 = "test";
    String s2 = "test";


    long start = System.currentTimeMillis();
    long end = start + 30 * 1000;
    while (System.currentTimeMillis() < end) {
        LOG.info(s1);
        LOG.info(s2);
    }

简而言之,在我的 Log4j2 属性文件中,我首先希望我的时间限制为 30 秒,在代码方面,我希望循环循环 2 次。我想检查当前 30 秒结束时,它会创建一个新文件并在接下来的 30 秒内向新文件写入一条消息。

如何在配置文件中将时间限制设置为 1 天?我这样做的原因是我想检查当 1 天结束时,当它切换到第二天时,它会创建一个新文件并在那里写入日志消息。

【问题讨论】:

    标签: java logging time configuration log4j2


    【解决方案1】:

    问题在于appender.rolling.filePattern=C:\\logs\\sms-%d{MM-dd-yy-HH-mm-ss}-%i.log

    你给的模式里面有HH-mm-sss。因此,当您再次重新启动服务/服务器时,会为该时间范围创建一个新文件。

    如果您想每天写入一个文件,请从 filePattern 中删除 HH-mm-ss 并尝试。

    喜欢这个appender.rolling.filePattern=C:\\logs\\sms-%d{MM-dd-yy}-%i.log

    【讨论】:

    • 是的,它奏效了。当我终止项目并再次运行它时,它会将消息写入同一个文件而不创建新文件。但是,我怎么知道当我切换到新的一天时,它会创建一个新文件并在那里写入消息?
    • 很高兴它有帮助。如果对你有帮助,请点赞我的回答
    • 我正在考虑使用线程做这样的事情。我想在我的配置文件中将时间限制设置为 5 分钟,然后每 5 分钟打印一次日志消息。如果需要超过 5 分钟,我希望它创建一个新文件并在那里写入,我该怎么做?
    • 以及如何在配置文件中设置5分钟进程?
    • 我不确定如何实现它。请点击此链接。它可能会有所帮助。 stackoverflow.com/questions/4858022/…
    猜你喜欢
    • 2021-05-09
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 2016-07-04
    • 2023-02-07
    • 2020-09-16
    • 2021-08-02
    相关资源
    最近更新 更多