Reputation: 6289
Right now I am rotating logs using log4j2 if it reaches 2000MB and time based i.e. every hour with following logic:-
<RollingRandomAccessFile name="test"
fileName="${sys:log4j.logPath}/testlog" filePattern="${sys:log4j.logPath}/test-%d{yyyy-MM-dd-HH}-%i.log.gz">
<PatternLayout>
<Pattern>%d{ISO8601} %m%n</Pattern>
</PatternLayout>
<Policies>
<SizeBasedTriggeringPolicy size="1990 MB" />
<TimeBasedTriggeringPolicy />
</Policies>
</RollingRandomAccessFile>
I also want to rotate logs when server shutdown. what configuration I have to add to the following ?
I have used OnStartupTriggeringPolicy to rotate logs on shutdown. But logs gets rotated after made a single request with server restart.
But I want my logs rotated when server shutdown. Is there a way to do it ?
Upvotes: 1
Views: 2308
Reputation: 6289
I have found the solution for above issue. Following code works for me.
Add 'shutdownHook="disable"' in log4j.xml
<Configuration status="WARN" shutdownHook="disable">
Method for rollover():-
public class RollOverLog4j {
public static void rollover() {
public final Logger logger = LogManager.getLogger("test");
Map<String, Appender> appenders = ((org.apache.logging.log4j.core.Logger) logger).getAppenders();
Iterator<Entry<String, Appender>> appenderIterator = appenders.entrySet().iterator();
while (appenderIterator.hasNext()) {
Appender appender = appenderIterator.next().getValue();
if (appender instanceof RollingRandomAccessFileAppender) {
((RollingRandomAccessFileAppender) appender).getManager().rollover();
}
}
}
}
Call rollover() on server stop:-
RollOverLog4j.rollover()
// shutting down log4j manually
Configurator.shutdown((LoggerContext) LogManager.getContext());
Note:- rollover() is not public method in log4 2.3 version. So use latest version 2.6 to make it work.
Upvotes: 1
Reputation: 9141
The title of your question is to rotate the logs on server restart but your question is to rotate the logs on shutdown. Rotating the log on shutdown is unreliable because the file won't rotate if the server or system crashes. A feature could be implemented to roll on normal shutdown but you would need to create a Jira issue for Log4j for that.
Log4j 2 supports an OnStartupTriggeringPolicy. It will cause the file to rollover when the server starts, unless the file is empty.
Upvotes: 1