Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4j2 how to read property variable from file into log4j2

Background: As usual we have various life cycles like dev. stage, lt, prod all these are picked at deploy time from environment variable ${lifecycle}. So JNDI setting we stores in ${lifecycle}.properties as variable datasource.jndi.name=jdbc/xxx. As other beans are also using this properties file, it is verified that such variable is loaded & file is in classpath, but somehow I am not able to consume this variable in log4j2.xml in below JDBC Appender.

<JDBC name="DBAppender" tableName="V1_QUERY_LOG" bufferSize="4" ignoreExceptions="false">
    <DataSource jndiName="${sys:datasource.jndi.name}" />
    <Column name="event_date" isUnicode="false" isEventTimestamp="true" />
    <Column name="log_level" isUnicode="false" pattern="%level" />
    <Column name="logger" isUnicode="false" pattern="%logger" />
    <Column name="message" isUnicode="false" pattern="%message" />
    <Column name="exception_msg" isUnicode="false" pattern="%ex{full}" />
</JDBC>

I have tried some option like "${datasource.jndi.name}" too, or is there any way I can fit the solution in

<Properties>
 <Property name="datasource.jndi.name">get datasource.jndi.name from {lifecycle}.properties</property>
</Properties>
like image 211
CodeLab Avatar asked Dec 19 '22 17:12

CodeLab


2 Answers

If you are not using java system properties, but environment variables, you should not use the ${sys:variable} prefix, but the ${env:variable} prefix instead. See also http://logging.apache.org/log4j/2.x/manual/lookups.html#EnvironmentLookup

like image 188
Remko Popma Avatar answered Dec 28 '22 07:12

Remko Popma


In general the placeholders that work in Spring bean configuration files do not work in Log4j configuration. They look the same, but the syntax and underlying discovery mechanism are completely different.

For instance ${sys:something} attempts to resolve a Java system property. System properties are usually passed to JVM as command line arguments in format -Dkey=value and not stored in property files.

You can try to use Resource bundle syntax ${bundle:MyProperties:MyKey} however this will load from that specific file and will not perform any additional Spring substitutions.

See also:

  • http://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitution
like image 21
anttix Avatar answered Dec 28 '22 08:12

anttix