开发者

log information into different log files

I have the following configurations in my web.config file, but how can I log the information into data.txt and general.txt separately in C#?

Could anyone provide some sample code for me?

<appender name="GeneralLog" type="log4net.Appender.RollingFileAppender">
  <file value="App_Data/Logs/general.txt" />
  <appendToFile value="true" />
  <maximumFileSize value="2MB" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="5" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n"  />
  </lay开发者_JS百科out>
</appender>
<appender name="DataLog" type="log4net.Appender.RollingFileAppender">
  <file value="App_Data/Logs/data.txt" />
  <appendToFile value="true" />
  <maximumFileSize value="2MB" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="5" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n"  />
  </layout>
</appender>


In your app, ideally, you should log the same way for both general and data, just using different loggers. In configuration you have a few options how to "route" the incoming log messages to different appenders.

The first is the loggers themselves. Depending on how your app is organized in terms of classes and namespaces, you organize your loggers in a hierarchical manner according to your namespace hierarchy. Then you can have different branches in the hierarchy going to different appenders. Read up on the Level Inheritance section here.

In addition to logger hierarchies, you can use any name as logger names. So for your general sections of your app, you could use a logger named "general".

Next thing you can use to control log message flow is using filters. You can filter messages on logger name, level, properties etc. or you can implement your own filters.

Here's a sample to show how you could route general and data to your appenders using the logger element and a filter. We route the root element (which receives all log messages) to the data appender. At the data appender we filter out all messages coming from the general logger.

Additionally, we route the general logger to the general appender.

<appender name="GeneralLog" type="log4net.Appender.RollingFileAppender">
    ...
</appender>

<appender name="DataLog" type="log4net.Appender.RollingFileAppender">
    <filter type="log4net.Filter.LoggerMatchFilter">
        <loggerToMatch value="general" />
        <acceptOnMatch value="false" />
    </filter>
    ...
</appender>

<root>
    <level value="DEBUG" />
    <appender-ref ref="DataLog" />
</root>

<logger name="general">
    <level value="WARN" />
    <appender-ref ref="GeneralLog" />
</logger>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜