Log4j config: Use Tomcat context params

I wanted to use parameters defined in context.xml on Tomcat 8 in configuration of Log4j2. My context was defined like:

<?xml version="1.0" encoding="UTF-8"?>

<Context>
    <Parameter name="instanceName" value="testInstance" override="false"/>

    <Resource .../>
</Context>

Now I would like to use parameter instanceName in log filename. I spent many hours trying various approaches and googling. I wonder why is this not better documented – Using Log4j 2 in Web Applications does not really help. In the end it is easy – just use web: prefix like this:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
    <Properties>
        <Property name="log-path">${sys:catalina.base}/logs/${web:instanceName}</Property>
    </Properties>

    <Appenders>
        <RollingFile name="file" fileName="${log-path}/test.log" filePattern="${log-path}/test-%d{yyyy-MM-dd}.log">
            ...
            ...
        </RollingFile>

    ...
    ...
</Configuration>

That’s it folks!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s