Search code examples
log4j2tomcat8amazon-linux

Log4j2 environment lookup does not find variable in AWS Linux EC2 instance


I have a Tomcat WAR project running in AWS Elastic Beanstalk EC2 instances. I have configured the instances to ensure that they have an environment variable CLUSTER_NAME. I can verify that the variable is available in the EC2 instance.

[ec2-user@ip-10* ~]$ cat /etc/environment
export CLUSTER_NAME=sandbox
ec2-user@ip-10* ~]$ echo $CLUSTER_NAME
sandbox

This variable is looked up in a Log4j2 XML file like this:

<properties>
    <property name="env-name">${env:CLUSTER_NAME}</property>
</properties>

The env-name property is used in a Coralogix appender like this:

<Coralogix name="Coralogix" companyId="--" privateKey="--"
                   applicationName="--" subSystemName="${env-name}">
     <PatternLayout>
          <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS}{GMT+0}\t%p\t%c\t%m%n</pattern>
     </PatternLayout>
 </Coralogix>

I see that this lookup is not working, as the env-name is just shown as ${env:CLUSTER_NAME} in Coralogix dashboard. The value works if I hardcode it.

What can be done to fix this lookup? There are several related questions for this, but they seem to refer to log4j1.x. https://stackoverflow.com/a/22296362. I have ensured that this project uses log4j2.


Solution

  • The solution was to add the CLUSTER_NAME variable in the /etc/profile.d/env.sh. This variable is available in the log4j2.xml with the following lookup.

    <property name="env-name">
       ${env:CORALOGIX_CLUSTER_NAME}
    </property>
    

    I am still not clear of the difference between adding a variable to /etc/environment vs /etc/profile.d/env.sh.