Accessing environment variable from log4j2.xml
Asked Answered
F

2

8

I am developing a Spring Boot web application. I am trying to access an environment variable from Websphere server in my log4j2.xml configuration. But somehow it's not working.

Environment variable is set in WAS under the below path -

Application servers > server001 > Process definition > Java Virtual Machine > Custom properties

environment variable image

My log4j2.xml configuration is as follows -

<Appenders>
 
        <RollingFile name="RollingFile"
            fileName="$${env:environment}/apps/was/logs/app-logs.log"
            filePattern="$${env:environment}/apps/was/logs/$${date:yyyy-MM}/app-logs-%d{-dd-MMMM-yyyy}-%i.log.gz">
            <PatternLayout>
                <pattern>%d %p %C{1.} [%t] %m%n</pattern>
            </PatternLayout>
            <Policies>
                <OnStartupTriggeringPolicy />
                <SizeBasedTriggeringPolicy
                    size="10 MB" />
                <TimeBasedTriggeringPolicy />
            </Policies>
        </RollingFile>
</Appenders>

I have tried to get the environment variable using $${env:environment} / ${env:environment}/ ${environment}. Nothing is working working. It's not able to fetch the environment variable. So it's crating a folder named "${env:environment}" / ${environment} instead of "DVL".

From java I can able to access my environment variable without any issue -

System.getProperty("environment") ==> DVL

Please Help.

Feme answered 6/2, 2020 at 8:45 Comment(0)
F
9

I have resolved this issue by using ${sys:environment} instead of ${env:environment}. For more details please go through the documentation logging.apache.org/log4j/2.x/manual/lookups.html

Feme answered 6/2, 2020 at 9:45 Comment(0)
Q
3

We had a same issue and we implemented a workaround.

We read the environment value using java and store into MDC (Using slf4j MDC)

And MDC key is accessible in log4j2.xml

Example:

MDC.put("environment", System.getProperty("environment"));

Now, you can access environemnt by simply writing {environment}

Hope this will help you.

Quasi answered 6/2, 2020 at 9:27 Comment(1)
Hello Yogesh, Thank you very much for your answer. I have not tried the solution, but I have resolved the issue. I am going through the documentation logging.apache.org/log4j/2.x/manual/lookups.html. I have used ${sys:environment} instead of ${env:environment}. And It's working. :) :)Feme

© 2022 - 2024 — McMap. All rights reserved.