log4j2 how to read property variable from file int

2019-04-10 02:26发布

问题:

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>

回答1:

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



回答2:

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