How to add/subtract date in log4j 2? - java

i have following configuration file in log4j 2
<RollingFile name="RollingFile" fileName="logs/test.log"
filePattern="logs$${date:yyyyMM}/app-%d{MM-dd-yyyy}.log">
<PatternLayout pattern="%d %-5p [%t] %C{4} (%F:%L) - %m%n"/>
<Policies>
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy size="20 MB"/>
</Policies>
<DefaultRolloverStrategy fileIndex="max" max="100"/>
</RollingFile>
can I perform date addition and/or subtraction in the filePattern. ? as of now the files generated upon rollover has current date. I would like to subtract single day from it . how can it be done ?

This is currently not possible, but I believe someone requested something similar earlier. I believe filing your request on the Log4j-2.0 issue tracker ( https://issues.apache.org/jira/browse/LOG4J2 ) may be the best way to proceed.

Related

log4j2 RollingFile only keeping 4 days

I tried setting up log4j to compress my log files and send them to a mount. I added a day/month/year to it in an attempt to get it in directories like that.
At first this appeared to be working.
Coming back a while later, it turns out only the most recent 4 days are present.
This is my config:
<Configuration>
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout>
<Pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p (%t) %c{1.} %m%n
</Pattern>
</PatternLayout>
</Console>
<RollingFile
name="RollingFile"
fileName="$/home/myservice/myservice.log"
filePattern="/mnt/logbackups/$${date:dd-MM-yyyy}/myservice-%d{dd-MM-yyyy}-%i.log.gz" >
<PatternLayout>
<Pattern>
%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p (%t) %c{1.} %m%n
</Pattern>
</PatternLayout>
<Policies>
<OnStartupTriggeringPolicy />
<SizeBasedTriggeringPolicy size="32 MB"/>
</Policies>
</RollingFile>
</Configuration>
I tried looking for a cause in the documentation: https://logging.apache.org/log4j/2.x/manual/appenders.html
But I can't find anything. Then again it's a gigantic page, maybe I'm missing something.
Does anybody know why this is happening?
You defined the RollingFileAppender which will regularly write to a new logfile. You also defined the triggers when to write to a new file, but you did not set the Rollover Strategies.
You could use the DirectWrite Rollover Strategy with maxFiles not set (to a value greater than zero).
You could also try to configure the Log Archive Retention Policy/Delete on Rollover action. Set testMode=true to prevent any file from being deleted.
Examples are available on the huge page you mentioned.
What you looking for is the "Default Rollover Strategy" specified under Rollover Policies. You can add one explicitly to adjust the default parameters.
Specify it like this inside the RollingFile:
<DefaultRolloverStrategy max="20"/>
Although I am confused because according to their documentation the default is 7:
max | integer | The maximum value of the counter. Once this values is reached older archives will be deleted on subsequent rollovers. The default value is 7

Log4j2 Rollover based on date but override based on size limit

I'm trying to configure a RollingFile appender which performs a rollover after every month (for 18 months). However in addition, I want log4j2 to override my current log if it reaches 25 MB. For example, if we are currently in February, then I would have a previous log for January. However, if my current February log will reach 25 MB then my February log would be overwritten with a new log for February. This is my current appender configuration:
<RollingFile name="audit-log" fileName="${sys:user.dir}/${baseDir}/${projectName}-Audit.log" immediateFlush="true" filePattern="${sys:user.dir}/${baseDir}/${projectName}-Audit.%d{yyyy-MM}.log">
<PatternLayout pattern="%d %-5level: %msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="25 MB"/>
</Policies>
<DefaultRolloverStrategy max="18"/>
</RollingFile>
However this rolls over whether I have switched months or reached the 25 MB size limit. How can I make logs roll over only after switching months, but have my current log be overwritten after the size limit has been reached?
Thanks!
I was able to solve this using the following configuration:
<RollingFile name="audit-log" fileName="${sys:user.dir}/${baseDir}/${projectName}-Audit.log" immediateFlush="true" filePattern="${sys:user.dir}/${baseDir}/${projectName}-Audit.%d{yyyy-MM}.log">
<PatternLayout pattern="%d %-5level: %msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="25 MB"/>
</Policies>
<DefaultRolloverStrategy max="1">
<Delete basePath="${baseDir}">
<IfAccumulatedFileCount exceeds="18" />
</Delete>
</DefaultRolloverStrategy>
</RollingFile>

How to use current date pattern in log4j2 fileName?

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Properties>
<property name="filePattern">%d{yyyy-MM-dd}</property>
</Properties>
<Appenders>
<RollingFile name="TEST"
fileName="application-${filePattern}.log"
filePattern="application-${filePattern}-rolled.log">
<Policies>
<TimeBasedTriggeringPolicy modulate="true"/>
</Policies>
</RollingFile>
</Appenders>
...
</Configuration>
I'd like to use the current date directly in the written logfile. But the result of the configuration above is application-%{yyyy-MM-dd} as filename.
Why is the date placeholder not resolved?
By the way: the renamed file on midnight is properly renamed like application-2016-03-13-rolled.log. Why does it work there, but not in the current logfile?
I'm running tomcat 8 and java 8, if that matters.
Remove the filename attribute. It worked for me. (got the solution from: https://issues.apache.org/jira/browse/LOG4J2-1859) Here is my working configuration
<RollingFile name="File" filePattern="${basePath}/api_test_execution_log_%d{yyyy-MM-dd}_%d{HH-mm-ss}_%i.log" immediateFlush="true">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<SizeBasedTriggeringPolicy size="32 MB" />
<OnStartupTriggeringPolicy/>
</Policies>
</RollingFile>
This one worked (whyever):
<property name="filePattern">${date:yyyy-MM-dd}</property>
I don't know why the placeholder isn't resolved but here is my working configuration:
<Appenders>
<RollingFile name="Permament"
fileName="E:/workspace/myproject/logs/ergo.log"
filePattern="E:/workspace/myproject/logs/ergo.%d{yyyy-MM-dd.HH:mm}.log"
immediateFlush="true">
<PatternLayout pattern="%d{HH:mm:ss.SSS} %5p{length=5} - %c{1} %m %ex%n"/>
<Policies>
<TimeBasedTriggeringPolicy/>
</Policies>
</RollingFile>
...
For those are using Log4j2 version 2.6.2 and below:
The fileName is indeed a file name that never changes while the
application is running. If you do not want this behavior upgrade to
the latest version of Log4j 2 and do not specify the fileName
attribute.
From https://issues.apache.org/jira/browse/LOG4J2-1859

DailyRollingFileAppender alternative in Log4j 2x

DailyRollingFileAppender was removed in Log4j 2x. What should be used instead?
Use a RollingFile 1 with TimeBasedTriggeringPolicy 2. e.g.:
<RollingFile name="RollingFile"
fileName="/tmp/app.log"
filePattern="/tmp/app%d{yyyy-MM-dd}.log">
<PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
<TimeBasedTriggeringPolicy />
</RollingFile>
See more in Apache Log4j 2 User's Guide [PDF].
Notes
org.apache.logging.log4j.core.appender.RollingFileAppender
org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy
If, like me, you're finally getting around to upgrading to log4j2 – because of the log4shell vulnerability – and you are accustomed to DailyRollingFileAppender rolling over at midnight, you should make that:
<TimeBasedTriggeringPolicy modulate="true" />

Time based triggering policy in log4j2

I am trying to create new log files on an hourly basis. I am using TimeBasedTriggerringPolicy of lo4j2 in RollingFileAppender. Below is the sample xml configuration code i have taken from log4j2 official site.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
<Appenders>
<RollingFile name="RollingFile" fileName="logs/app.log" filePattern="logs/$${date:yyyy-MM}/app-%d{yyyy-MM-dd-HH}-%i.log.gz">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
<Policies>
**
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
**
<SizeBasedTriggeringPolicy size="250 MB" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="RollingFile" />
</Root>
</Loggers>
</Configuration>
In the interval attribute I have set 1 which signifies 1 hour.
But still my file does not roll every 1 hour.
Please help me find any mistake.
Note : I have included beta9 of log4j2 (which is the latest)
1 here indicates 1 day and not 1 hour. I have manually tested with below configuration.
<RollingFile name="T" fileName="/data_test/log/abc.log"
filePattern="/data_test/log/abc-%d{MM-dd-yyyy}-%i.log">
<PatternLayout>
<Pattern>%d{ISO8601} %-5p [%t] (%F:%L) - %m%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
<SizeBasedTriggeringPolicy size="100 KB" />
</Policies>
</RollingFile>
For manual testing, I change the system date and time.
First, try with increasing 1 hour. The log files will be generated but not as per the expectation.
Then change the system date, increase by 1 day and then see the results.
Suppose the last log file (abc.log) on day 29-Oct is of 50 KB. Configuration size is 100 KB. If we change the day (increase by 1 day) and then run.
Then, last file will be renamed 29-Oct-(some sequence number).log (50 KB file as it is copied) and new file will be created with abc.log
I have tried this with simple servlet with below configuration in web.xml
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>log4j2.xml</param-value>
</context-param>
keep log4j2.xml in src folder. log4j2.xml is not loaded if we keep it in classpath.
Log4j documentations:
interval -> (integer) How often a rollover should occur based on the most
specific time unit in the date pattern. For example, with a date
pattern with hours as the most specific item and and increment of 4
rollovers would occur every 4 hours. The default value is 1.
You should change the filename pattern if you would like to create it every hour.
As Abid mentioned, interval value is interpreted in context of pattern that is specified as part of filePattern. It starts with lowest denomination. For example,if pattern contains S, frequency will be in millisecond. It supports the date pattern as described in detail as part of SimpleDateFormat java doc http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
You do have a non-empty log file (otherwise there is nothing to roll over)?
Note that even though the name is "TimeBased..." It will not actually roll over at the specified time, but at the first log event that arrives after the time threshold has been exceeded. Can you try with a small test program that logs something after 61 minutes or so and see if the problem still occurs?
If it doesn't roll over with the above test program, you may have found a bug. In that case please raise it on the log4j issue tracker. (Be sure to attach the test program the team can use to reproduce the issue).
Everyday day Rolling
<RollingFile name="RollingFile" fileName="logs/app.log"
filePattern="logs/app.%d{yyyy-MM-dd}.log" ...>
...
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
Everyday Hour Rolling
<RollingFile name="RollingFile" fileName="logs/app.log"
filePattern="logs/app.%d{yyyy-MM-dd-HH}.log" ...>
...
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
Everyday 5 day Rolling
<RollingFile name="RollingFile" fileName="logs/app.log"
filePattern="logs/app.%d{yyyy-MM-dd}.log" ...>
...
<TimeBasedTriggeringPolicy interval="5" modulate="true" />
Everyday 5 hours Rolling
<RollingFile name="RollingFile" fileName="logs/app.log"
filePattern="logs/app.%d{yyyy-MM-dd-HH}.log" ...>
...
<TimeBasedTriggeringPolicy interval="5" modulate="true" />
Every Month Rolling
<RollingFile name="RollingFile" fileName="logs/app.log"
filePattern="logs/app.%d{yyyy-MM}.log" ...>
...
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
Hope these cases will helps very well in understanding how filePattern and interval are related.
The time interval interpretation depends on file pattern you are using. The following configuration rolls file every second for me.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="A" target="SYSTEM_OUT">
<PatternLayout pattern="%d [%t] %-5p {%F:%L} %x - %m%n" />
<ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
</Console>
<RollingFile name="R"
fileName="/home/xxx/yyy/myapp.log" filePattern="/home/xxx/yyy/myapp-%d{yyyy-MM-dd-HH-mm-ss}-%i.log">
<PatternLayout pattern="%d [%t] %-5p {%F:%L} %x - %m%n" />
<Policies>
<TimeBasedTriggeringPolicy interval="1" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="A" />
<AppenderRef ref="R" />
</Root>
</Loggers>
</Configuration>
According to your TimeBasedTriggeringPolicy configuration, logger will only populate the logs every day not every hour.
AFAIK,You can achieve the functionality by changing the filePattern from HH(Hours) to dd(Days).
I have modified your config.xml. Try This
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
<Appenders>
<RollingFile name="RollingFile" fileName="logs/app.log" filePattern="logs/$${date:yyyy-MM}/app-%d{yyyy-MM-dd}-%i.log.gz">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
<Policies>
**
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
**
<SizeBasedTriggeringPolicy size="250 MB" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="RollingFile" />
</Root>
</Loggers>
</Configuration>
For more details check this
Hope this will workout for you too.

Categories