2015-09-30 47 views

回答

0

一种方法是使用IoC容器。只需定义一个接口,然后根据该接口定义记录器类。然后可以根据需要创建或注入他们的其他课程。

+0

这个答案在'NLog'上下文中吗? – Pablo

+0

我对NLog上下文一无所知。我通常使用温莎城堡,但你也可以使用任何这些:http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx – DrewB

+0

请检查标记,我的问题是关于'NLog' – Pablo

0

您的nlog配置定义彼此独立的规则和目标。您的要求是有2个目标,一个文件记录器和一些其他记录器,在文本框中显示您的日志条目。您只需在您的nlog配置中添加两条规则即可将您的日志条目定向到这两个目标。

这将是一个示例nlog.config,它将所有日志条目记录到两个不同的目标。您可以为各个日志规则设置不同的minLevel。第一个目标是一个简单的文件记录器,另一个目标是一个MethodCall目标,该目标使用日志参数调用静态方法。查看nlog documentation了解所有可用目标和更多文档。

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <configSections> 
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/> 
    </configSections> 
    <nlog> 
    <targets> 
     <target name="toFile" type="File" 
      layout="${longdate} ${level} [${threadid}] - ${callsite}: ${message} ${onexception:${newline}Ausnahme\:${exception:format=tostring}}" 
      fileName="${basedir}/log.txt" 
      archiveFileName="${basedir}/log.{#####}.txt" 
      archiveAboveSize="1024000" 
      archiveNumbering="Sequence" 
      concurrentWrites="true" 
      keepFileOpen="false" 
      maxArchiveFiles="3" 
      /> 

     <target xsi:type="MethodCall" 
     name="toRichTextBox" 
     methodName="String" 
     className="String"> 
     <parameter layout="Layout" name="String" type="System.Type"/><!-- repeated --> 
     </target> 

    </targets> 
    <rules> 
     <logger name="*" minlevel="Warn" writeTo="toFile" /> 
     <logger name="*" minlevel="Warn" writeTo="toRichTextBox" /> 
    </rules> 
    </nlog> 
</configuration> 
+0

如何在代码中使用单个'logger.Debug(...)'来让它登录到两个目标?假设我已经在代码中有很多正在写入文件目标的调试消息,并且我还想添加第二个目标,而不修改所有的'logger.Debug'行? – Pablo

+0

是的,这应该工作。您可以使用记录器规则将特定类或名称空间中的消息记录到不同的目标中(在“name”属性中为“*”完成),但只要您将日志条目转发给所有目标喜欢。 –

+0

您可以用示例更新您的示例配置吗? – Pablo