Introduction
First and foremost, this has been tested with Tomcat 9.0.54 and log4j2 – 2.1.2. This will not require modifying any of the Tomcat directories but the web application’s directory inside the webapps directory, which you would if you really need to use log4j2.
Why is this a big deal? because Tomcat 9 has moved on to use JUL – Java util logging. So, if you take your f’ing webapp which uses log4j2 and shove it up Tomcat 9’s ass, it is not going to work, as it turns out!
NOTE: You will find articles or comments online asking you to remove Java Util logging.properties sitting in Tomcat/Conf directory or adding log4j2 jars in a new log4j directory, all of those instructions appear to be to make the Tomcat itself use log4j and I have not had to do any of that to just get my app work with the log4j2.
The steps
- Make sure your web app has at least the two log4j2 jars – log4j-core-2.11.2.jar and log4j-api-2.11.2.jar in your WEB-INF/lib. If you used maven, you probably had something similar to:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.2</version>
</dependency>
2. Make sure you have a log4j2.xml (or properties) that follows the new v2 standard. Here is an example for you copy paste, you can simply replace the com.xyz.abc with your own root project class name and I am sure you know how to further enhance it as you see fit.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Properties>
<Property name="logPath">C:/src/main/apache-tomcat-9.0.54</Property>
</Properties>
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d [%t] %-5p [%C.%M()] %m%n" />
</Console>
<RollingFile name="rollingFile" fileName="${logPath}/logs/myapp.log"
filePattern="${logPath}/myapp_%d{yyyy-MM-dd}.log">
<PatternLayout
pattern="%d [%t] %-5p [%C.%M()] %m%n" />
<Policies>
<OnStartupTriggeringPolicy />
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="org.springframework" level="warn" additivity="false">
<AppenderRef ref="console" level="warn"/>
<AppenderRef ref="rollingFile" level="warn"/>
</Logger>
<Logger name="org.hibernate" level="debug" additivity="false">
<AppenderRef ref="console" level="debug"/>
<AppenderRef ref="rollingFile" level="debug"/>
</Logger>
<Logger name="com.xyz.abc" level="trace" additivity="false">
<AppenderRef ref="console" level="trace"/>
<AppenderRef ref="rollingFile" level="trace"/>
</Logger>
<Root level="TRACE" additivity="false">
<AppenderRef ref="console" />
<AppenderRef ref="RollingFile" />
</Root>
</Loggers>
</Configuration>