How-To: Configure Tomcat 9 to log via Log4j2
Asked Answered
M

2

6

How can you redirect Tomcat 9's internal logging (catalina and localhost) to Log4j2?

While there are many guides available for older versions of Tomcat and Log4j, I couldn't find anything "complete" regarding Tomcat 9 and Log4j2; the Apache Tomcat 9 documentation points to "the instructions provided by the alternative logging framework", and the Apache Log4j documentation states (jar names in 2. corrected):

Log4j may be used as the logging framework for Apache Tomcat. This support is implemented automatically by including the log4j-api, log4j-core, and log4j-appserver jars in the boot classpath. A file named log4j2-tomcat.xml, log4j2-tomcat.json, log4j2-tomcat.yaml, log4j2-tomcat.yml, or log4j2-tomcat.properties must also be placed in the boot classpath. This is most easily done by:

  1. Creating a set of directories in catalina home named log4j2/lib and log4j2/conf.
  2. Placing log4j-api-2.12.0.jar, log4j-core-2.12.0.jar, and log4j-appserver-2.12.0.jar in the log4j2/lib directory.
  3. Creating a file named log4j2-tomcat.xml, log4j2-tomcat.json, log4j2-tomcat.yaml, log4j2-tomcat.yml, or log4j2-tomcat.properties in the log4j2/conf directory.
  4. Create or modify setenv.sh in the tomcat bin directory to include CLASSPATH=$CATALINA_HOME/log4j2/lib/*:$CATALINA_HOME/log4j2/conf

But what to put in that log4j2-tomcat.* config file?

May answered 5/7, 2019 at 12:33 Comment(0)
M
5

I found a sample properties file in the Apache Tomcat 7 documentation, but since this is meant for use with Log4j 1.x, I had to adapt it to the Log4j2 properties file syntax. This is the result:

# 'status' refers to log messages from Log4j2 itself
monitorInterval = 30
status = warn

property.loglevel.catalina = info
property.loglevel.localhost = info

property.layoutPattern.catalina = %d %-5p [%t] %-22.22c{1} %m%n
property.layoutPattern.localhost = %d %-5p [%t] %-30.30c{1} %m%n

# Roll-over the logs once per month using CronTriggerPolicy.

property.fileDatePattern.catalina = %d{yyyy-MM}
property.fileDatePattern.localhost = %d{yyyy-MM}

property.cronTriggerSchedule.catalina = 0 0 0 1 * ?
property.cronTriggerSchedule.localhost = 0 0 0 1 * ?

## Appenders

# N.B.: - No need to specify 'appenders = CATALINA, LOCALHOST, CONSOLE'
#         since these identifiers do not contain '.' characters.
#       - The sub-component identifiers 'policies' and 'cron' are arbitrarily
#         chosen; the actual type is specified via the 'type' attribute.
#       - 'DirectWriteRolloverStrategy' is used automatically since no 'fileName' specified.

appender.CATALINA.type = RollingFile
appender.CATALINA.name = RollingFile-CATALINA
appender.CATALINA.filePattern = ${sys:catalina.base}/logs/catalina.${fileDatePattern.catalina}.log
appender.CATALINA.layout.type = PatternLayout
appender.CATALINA.layout.pattern = ${layoutPattern.catalina}
appender.CATALINA.policies.type = Policies
appender.CATALINA.policies.cron.type = CronTriggeringPolicy
appender.CATALINA.policies.cron.schedule = ${cronTriggerSchedule.catalina}
appender.CATALINA.policies.cron.evaluateOnStartup = true
appender.CATALINA.filePermissions = rw-r-----
appender.CATALINA.fileOwner = tomcat
appender.CATALINA.fileGroup = adm

appender.LOCALHOST.type = RollingFile
appender.LOCALHOST.name = RollingFile-LOCALHOST
appender.LOCALHOST.filePattern = ${sys:catalina.base}/logs/localhost.${fileDatePattern.localhost}.log
appender.LOCALHOST.layout.type = PatternLayout
appender.LOCALHOST.layout.pattern = ${layoutPattern.localhost}
appender.LOCALHOST.policies.type = Policies
appender.LOCALHOST.policies.cron.type = CronTriggeringPolicy
appender.LOCALHOST.policies.cron.schedule = ${cronTriggerSchedule.localhost}
appender.LOCALHOST.policies.cron.evaluateOnStartup = true
appender.LOCALHOST.filePermissions = rw-r-----
appender.LOCALHOST.fileOwner = tomcat
appender.LOCALHOST.fileGroup = adm

# Uncomment if you want to keep logging to catalina.out after Log4j2 takes over.

#appender.CONSOLE.type = Console
#appender.CONSOLE.name = STDOUT
#appender.CONSOLE.layout.type = PatternLayout

## Configure which loggers log to which appenders

rootLogger.level = ${loglevel.catalina}
rootLogger.appenderRef.CATALINA.ref = RollingFile-CATALINA
#rootLogger.appenderRef.stdout.ref = STDOUT

# Here, the identifier does contain '.' characters, so we must specify the list.
loggers = org.apache.catalina.core.ContainerBase.[Catalina].[localhost]

logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost].name = LOCALHOST
logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = ${loglevel.localhost}
logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost].appenderRef.LOCALHOST.ref = RollingFile-LOCALHOST

The main reason for me to use Log4j2 was to be able get monthly log rotation, but you can easily adjust everything how you like, even without restarting Tomcat.

May answered 5/7, 2019 at 12:33 Comment(23)
is there a way to get it to use our existing xml config?Kurt
xml config for what? Log4j?May
@May can you help me with this ? i need that precise config file in log4j1 translated to log4j2. Seems in documentation that standard format of properties is xml file instead of file.properites ... is this correct ? My first option was to use log4j with tomcat9 but i didnt get with it.....: askubuntu.com/questions/1324010/tomcat-9-logging-with-log4jBeak
log4j2 supports xml, yaml, json and .properties, it's up to you what you want to use. Take a look at the log4j1 .properties file (it's linked in the first sentence of my answer) and compare it with my log4j2 version. You will notice e. g. these transformations: log4j.appender -> appender, .layout = org.apache.log4j.PatternLayout -> .layout.type = PatternLayout, .layout.ConversionPattern -> .layout.pattern, .File = ${catalina.base}/logs/catalina -> .filePattern = ${sys:catalina.base}/logs/catalina.%d{yyyy-MM-dd}.log, .DatePattern = '.'yyyy-MM-dd'.log' -> delete.May
@Eduardo Gutierrez let me know if you need further assistance, then I will edit my answer and explain the translation steps in detail.May
@Christoph, id definitely need a more detailed explanation. My first question was if you know if is someway of use log4j1 in Tomcat 9. If so the steps in my question are the same or i have to do other things. Second i know about properties file could be xml or properties, but log4j most documentation or tutorials use the .properties styles, but log4j2 seem that most people use xml. And the third question your "translated" file is bigger than the one i need to transale. Hopefully with more detailed explanation i could understand it better. Thanks for your help.Beak
Perhaps you can answer my question and dont mix things, its up to you.... Thanks againBeak
@Eduardo Gutierrez I don't tend to mix things up. Your first statement was you need to translate a log4j1 config to log4j2, and I gave you the most crucial transformation steps to achieve that. Now you say your first question was if I know if log4j1 can be used together with tomcat9, but that's not true. However, I don't know if this is possible because I've never used log4j1. Anyway, since the last release of log4j1 is from 2012, I don't recommend to use it anymore. What is the file format of your log4j1 config?May
the log4j.properties...codejava.net/coding/… most of tutorials appear without xml, but really xml is a valid format for setup log4j. Can you please explain how to "translate" the properties to log4j2 ? Thanks By the way sorry for my bad english, about mixing things was to myself, because perhaps we have to follow the discussion in other place like this question, nothing with you. Sorry if I bother you.Beak
So my first bet was to use log4j in tomcat9, but if you recommend to pass to log4j2, then a step by step tutorial would be nice, how to use log4j2 in tomcat9 and how did you translate the properties file ( the one in the link of askubuntu, i.sstatic.net/eoYUw.png this file whic i suppose is a part of the one in this thread). Thanks again for your effortBeak
@Eduardo Gutierrez You don't bother me, it was just a misunderstanding. I'm very busy ATM, but I will come back to you soon.May
@Christoph, im waiting to your explanation. Thanks for your help and im happy we have no misunderstandings... ;)Beak
@May just a remember.....when you have some time can you explain using log4j2 with tomcat 9 ?? ThanksBeak
@May id appreciated you could share the tutorial about using log4j2 and Tomcat9 Thanks in advanceBeak
If I had written a tutorial, I would share it immediately ;) I haven't asked you an important question yet: Do you want to use log4j2 for Tomcat's own logging or for your servlets' logging?May
Thanks for your help...as far as i know, are independent things... inmy servlets i began with log4j and then used common-loggings, so the library should not be a problem.... I suppose that to make things easier to my students id use the same log4j2... so i can explain configuration samples.... Perhaps later i could try commons logging or another library in servlets....Beak
In my opinion, log4j2 is the best. I use it for both Tomcat's and my servlets' logs. You can configure it to meet your exact requirements and it's very efficient. My servlets handle requests from my Alexa Skills. I use Apache2 as reverse proxy to forward requests to Tomcat. Although everything is running on my NAS (1 GHz Dual-Core ARMv7l, 1 GB RAM), the response time is fantastic. That's the reason why I got in touch with Tomcat9 and log4j2; I've never used log4j1. But now BTT: Could you create a new question and post the log4j1 config for one of your servlets, then I can help you in no time.May
@Cristoph...i have used mkyong.com/logging/log4j-hello-world-example this example to configure log4j in servlets. Its flexible, two outputs, one for console and one for log file with rolling... (in point 3 you can read de log4j properties, which it would be nice if you could "translate" to log4j2). Thanks for your helpBeak
@Cristoph..by the way i m not able to ask new questions, as my bad english is giving me bad reputation ;)Beak
Are you sure? As far as I know, you lose reputation when someone votes down your question or answer. Regarding comments, I don't see a control to vote down, but I don't know if comments just can't be voted down, or if the reason why I don't see a control to vote down is that my reputation is too low. However, your Englisch isn't as bad as you think, by far ;) Mine isn't perfect too, I'm German ;) And last not least, I think the criterion for voting up/down is the contents, not the language. But BTT: I'll write the translation guide right now.May
@May just a remember about tutorial.....thanksBeak
@EduardoGutierrez I didn't forget you, I just had a lot of work to do. I'll notify you as soon as the guide is online.May
@Cristoph dont worry, i just wanted to remind in case you forgot....As you didnt answer the other comments... Thanks in advance and sorry for the inconvenience ofr if i bother you...Beak
M
0

In order to work Tomcat 9.0.54+ setup with log4j2 please complete following:

  1. Activate JDK JUL bridge - https://logging.apache.org/log4j/2.x/log4j-jul/

To use the JDK Logging Adapter, you must set the system property java.util.logging.manager to org.apache.logging.log4j.jul.LogManager This must be done either through the command line (i.e., using the -Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager argument) or by using System.setProperty() before any calls are made to LogManager or Logger.

  1. Copy all necessary log4j2 jars into classpath or /lib
  2. Configure -Dlog4j.configurationFile=/your/path/logger.xml like below example
<?xml version="1.0" encoding="utf-8"?>
<!-- ================================================ -->
<!--               Tomcat log4j2 logger               -->
<!-- ================================================ -->
<Configuration status="INFO" monitorInterval="60">
    <Properties>
        <Property name="logsdir">${sys:catalina.base}/logs</Property>
        <Property name="layout">[%d][%p][%c:%L:%M] - %m%n</Property>
    </Properties>
    <Appenders>
        <Console name="DEFAULT" target="SYSTEM_OUT">
            <PatternLayout pattern="${layout}"/>
        </Console>
        <Async name="ASYNC-DEFAULT" includeLocation="true">
            <AppenderRef ref="DEFAULT"/>
            <AppenderRef ref="INTOFILE"/>
        </Async>
        <RollingFile name="INTOFILE"
                     fileName="${logsdir}/worker.log"
                     filePattern="${logsdir}/catalina.%d{yyyy-MM-dd}-%i.log">
            <PatternLayout pattern="${layout}"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="100"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <!-- OFF -->

        <!-- ERROR -->

        <!-- WARN -->

        <!-- INFO -->
        <logger name="org.apache.catalina" level="INFO"/>
        <logger name="org.apache.catalina.core" level="INFO"/>
        <logger name="org.apache.tomcat" level="INFO"/>
        <logger name="org.apache.coyote" level="INFO"/>
        <logger name="org.apache.jasper" level="INFO"/>

        <!-- DEBUG -->
        <logger name="org.apache.catalina.startup" level="DEBUG"/>
        <logger name="org.apache.tomcat1" level="DEBUG"/>


        <Root level="TRACE">
            <AppenderRef ref="ASYNC-DEFAULT"/>
        </Root>
    </Loggers>
</Configuration>

Munger answered 1/2, 2022 at 22:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.