开发者

How to have different instances of the same application log to different files with log4net?

My question is similar to this one, but with a somewhat simpler context. In my case I have a single application which may be run twice (at most) simultaneously with different command line parameters, so each instance knows its context.

The app.config file defines a log4net section to configure logging. Here it is:

<log4net xsi:noNamespaceSchemaLocation="http://csharptest.net/downloads/schema/log4net.xsd"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <appender name="MainAppender" type="log4net.Appender.FileAppender">
    <file value="${TMP}\NCAgent.log" />
    <appendToFile value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <appender name="DebugAppender" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="ERROR" />
    <appender-ref ref="MainAppender" />
    <level value="INFO"/>
    <appender-ref ref="DebugAppender"/>
  </root>
</log4net>

And, of course, we have a problem that two application instances may log to the same log file, so at runtime one of the instances (the choice is well defined and unambiguous) loads the log4net XmlElement, changes there the name of the log file and configures log4net using the XmlConfigurator.Configure(XmlElement) overload.

I do not like our approach and feel that there开发者_如何转开发 should be a better solution. Any ideas?

Thanks.


You could try either configuring the FileAppender filename programmatically and appending the process ID, or subclass the FileAppender to make said behavior automatic with the config-based approach.


See this answer to a similar question..

You can define a pattern for the filename including something unique such as a timestamp or a process id.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜