Home > OS >  Define time limit using Log4j2 in configuration properties
Define time limit using Log4j2 in configuration properties

Time:11-27

This is parameters below,which are using the log4j2 library.

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

and the following code write logging messages up to 30 seconds. When it reaches 30 seconds, the process is terminated and created the new file in the logs folder. What I want to do here is first I want to set my time limit to 30 seconds in my Log4j2 configuration properties file and the reason I do this is because I want to create a new file after 30 seconds and check if it will write my logging messages there.

    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);
    }

In short, in my Log4j2 properties file, I first want my time limit to be 30 seconds and on the code side, I want the loop to loop 2 times. I want to check that when the first 30 seconds are over, it will create a new file and write a message to the new file in the next 30 seconds.

CodePudding user response:

The issue is with appender.rolling.filePattern=C:\\logs\\sms-%d{MM-dd-yy-HH-mm-ss}-%i.log .

The pattern you gave has HH-mm-sss in it . So when you restart the service/server again, a new file is created for that time frame.

If you want to write to one file per day, remove HH-mm-ss from filePattern and try.

Like this appender.rolling.filePattern=C:\\logs\\sms-%d{MM-dd-yy}-%i.log .

  • Related