log4cxx: configuring appender with arguments

2019-07-15 05:44发布

log4cxx's config is read from follow-by xml via:

DOMConfigurator::configure("log4cxx.xml");

But, want to have filename set at runtime, and this creates a problem of either having multiple .xmls for reading, or creating one on the fly (in memory/at disk -- no matter where).

  <appender name="appxNormalAppender" class="org.apache.log4j.FileAppender">
    <param name="file" value="appxLogFile.log" />
    <param name="append" value="true" />
    <layout class="org.apache.log4j.PatternLayout">
      <param name="ConversionPattern" value="%d %-5p [%t:%x] %C{2} (%F:%L) - %m%n" />
    </layout>
  </appender>

Is there any way to pass configurator some values to substitute into <param file="file" value="%%value%%" /> or to access the property after configuring and change it?

P.S. The reason for doing this: multiple copies of the same program are writing to same log making it look ..strange. How to avoid this with log4j/log4cxx in traditional way without inventing too much bicycles?

标签: log4j log4cxx
1条回答
聊天终结者
2楼-- · 2019-07-15 06:40

This problem hit me about 2 years ago; I don't have access to source code anymore, but here's what I did, more or less:

  1. Extended the FileAppender and used it in the config file.
  2. Inside the setFile() method I appended process name and id to the file name (you can do it in the setOption() method, if you don't use a rolling file.

We already had a mechanism for uniquely identifying our processes and their instances by our internal id; you could use a PID, for example, or add a global variable and set it in every application using log4cxx to your unique value, then using it in the setOption method of your appender.

See also my answer: Using Log4j CompositeTriggeringPolicy feature with log4CXX

查看更多
登录 后发表回答