简体   繁体   中英

How to set log4j2 folder in tomcat?

I'm running a spring-boot war application in tomcat8 and use log4j2 for logging. Problem:

  • the logs are found in the wrong directory
  • the logs don't rotate properly

log4j2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
       <Appenders>
        <RollingRandomAccessFile name="APP" fileName="logs/my-application.log"
                                 filePattern="logs/archive/my-application-%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="%d %p %c{1.}: %m%n" charset="UTF-8" />
            <Policies>
                <TimeBasedTriggeringPolicy modulate="true"/>
            </Policies>
        </RollingRandomAccessFile>
    </Appenders>

    <Loggers>
       <Root level="DEBUG">
            <AppenderRef ref="APP" />
        </Root>
    </Loggers>
</Configuration>

pom.xml:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-log4j2</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-web</artifactId>
    </dependency>

Result: the logs are found in /var/log/tomcat8/my-application.log . The archives in /var/log/tomcat8/my-application.log.gz

This is really strange. The correct logger filenames are picked up. But now the folders.

Question: why is my /logs folder not taken into account? And why does the zipped archive name not contain the timestamp?

Sidenote: running the app as a jar in my idea works perfectly. It automatically creates a /logs folder under the classpath root. And all files are properly moved to /archive at midnight, with timestamp!

But why is this not working as is in tomcat?

Found the cause:

If the fileName starts without a / , it is taken relative to catalina.base=/var/lib/tomcat8 Inside that folder is a symlink /logs . thus a fileName="logs/myapp" will follow that symlink. Which points to /var/log/tomcat8 .

As a result all files are written into that folder. Further, some tomcat default logrotate seems to take all files inside that folder and automatically compress it. So log4j has no chance to apply the logrotate.

Solution: just set and additional subpath for the filename. I used:

fileName="logs/logs/my-application.log"
filePattern="logs/logs/my-app..."

This will move the logfiles to:

/var/log/tomcat8/logs
/var/log/tomcat8/logs/archive

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM