我需要将应用中的某些事件记录到某个文件中。我有一个正在运行的主日志文件,但如何将特定事件定向到某个文件。
在下面的示例中,如何将count属性记录到某个文件?
ILogger mainApplog = container.Resolve<ILogger>(); // this is working just fine to c:\log.txt
ILogger valuesLog = container.Resolve<ILogger>(); // what should I resolve to log to c:\values.txt?
mainApplog.DebugFormat("Calculating values");
var count = 0;
while (true)
{
count++;
valuesLog.InfoFormat(count.ToString());
if (count > 100)
break;
}
mainApplog.DebugFormat("Calculations completed");
答案 0 :(得分:0)
如果只是关于Log4Net,请尝试以下方法:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<log4net>
<appender name="MainAppender" type="log4net.Appender.ColoredConsoleAppender" >
<mapping>
<level value="ALL" />
<foreColor value="White" />
<backColor value="Red, HighIntensity" />
</mapping>
<filter type="log4net.Filter.LoggerMatchFilter">
<LoggerToMatch value="MainApplicationLog" />
</filter>
<filter type="log4net.Filter.DenyAllFilter">
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
</layout>
</appender>
<appender name="ValueAppender" type="log4net.Appender.ColoredConsoleAppender" >
<mapping>
<level value="ALL" />
<foreColor value="White" />
<backColor value="Green, HighIntensity" />
</mapping>
<filter type="log4net.Filter.LoggerMatchFilter">
<LoggerToMatch value="ValuesLog" />
</filter>
<filter type="log4net.Filter.DenyAllFilter">
</filter>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%ndc] - %message%newline" />
</layout>
</appender>
<root>
<level value="ALL" />
<appender-ref ref="MainAppender" />
<appender-ref ref="ValueAppender" />
</root>
</log4net>
</configuration>
您可以选择自己的appender替换appender。为了完整起见,这是将进行日志记录的代码。
log4net.Config.XmlConfigurator.Configure();
ILog mainAppLog = LogManager.GetLogger("MainApplicationLog");
ILog valuesLog = LogManager.GetLogger("ValuesLog");
mainAppLog.Debug("Calculating values");
valuesLog.InfoFormat("{0}", 0); // do not use ToString, you will use processor time even when not logging