Log4Net Writing to different files

ぐ巨炮叔叔 提交于 2019-12-23 01:16:18

问题


I'm making a vehicle tracking application(ASP.NET MVC C#). I have windows service that takes data sent by GPS device. In the service I have written the code to Log the data.

Now consider a normal logging scenario in which i have only one GPS device.

08:00:24 Inside OnDataAvailable Method

08:00:25 Data Received - Device Id: 2 Data: abcdefghijkl

08:00:25 Leaving OnDataAvailable

and few more statements. and then it repeats


Now when I have more than one GPS device sending data, the log gets mixed. That is I have following kind of log:

08:00:23 Inside OnDataAvailable Method 08:00:24 Inside OnDataAvailable Method

08:00:25 Data Received - Device Id: 2 Data: abcdefghijkl

08:00:25 Leaving OnDataAvailable

08:00:26 Data Received - Device Id: 1 Data: abcdefghijkl

08:00:26 Leaving OnDataAvailable

Now what I want to achieve is that, I should have different log files for different devices. So for device with Id 1 I have Log_D1.txt, For Device Id 2, Log_D2.txt.

Would appreciate if someone can point me in the right direction.


回答1:


You should be able to use one of the context objects (like ThreadContext.Properties) to build the filename. You can configure the log file name to use properties to build up the name. So, in your case, you might store the device id in the context (are your requests being handled in separate threads?).

This article has a good explanation of how this works:

http://geekswithblogs.net/rgupta/archive/2009/03/03/dynamic-log-filenames-with-log4net.aspx

To summarize, you can configure your appender something like this:

<appender name="RollingFileAppenderV1" type="log4net.Appender.RollingFileAppender">
     <file type="log4net.Util.PatternString" value="F:\HornetFeed\Log_%property{DeviceID}" />
     <appendToFile value="true" />
     <rollingStyle value="Size" />
     <maxSizeRollBackups value="-1" />
     <maximumFileSize value="5000KB" />
     <staticLogFileName value="true" />
     <countDirection value="1"/>
     <layout type="log4net.Layout.PatternLayout">
         <conversionPattern value="%m%n" />
     </layout>
     <filter type="log4net.Filter.PropertyFilter">
         <Key value="Version" />
         <StringToMatch value="1" />
     </filter>
     <filter type="log4net.Filter.DenyAllFilter" />
</appender>

Note the use of %property in the filename specification.

Then, in your code, you might do something like this:

private void OnDataAvailable(string id, int data)
{
  ThreadContext.Properties["DeviceID"] = id;

  logger.Info("Inside OnDataAvailable");

  logger.Info("Leaving OnDataAvailable");
}

All log messages, at least in cases where the DeviceID property has been set, should be segregated into separated files, named, in part, by the DeviceID.



来源:https://stackoverflow.com/questions/24886364/log4net-writing-to-different-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!