c#,Nlog和更改目标

问题描述 投票:0回答:1

我正在运行Windows服务,我希望当我在debugto中运行时写入控制台以及何时作为事件查看器的服务。

在powershell我设置

New-EventLog –LogName Application –Source "mySource"

我有这个nlog.config

<nlog>
<targets>
<target name="debugger" type="Debugger" layout="${logger}::${message}"/>
<target name="console" type="Console" layout="${logger}::${message}"/>
<target name="file" type="File" layout="${longdate} ${logger}::${message}" fileName="${basedir}/Logs/${shortdate}.log"/>
<target name="eventLog" type="eventlog" layout="${logger}::${message}" source="mySource"/>
</targets>
<rules>
<logger name="" minlevel="Trace" writeTo="debugger"/>
<logger name="" minlevel="Trace" writeTo="console"/>
<logger name="*" minlevel="Trace" writeTo="file"/>
<logger name="*" minlevel="Debug" writeTo="eventLog" />
</rules>
</nlog> 

我在服务开始时做init:

    public static void InitLogger()
    {
        NLog.Targets.Target target = null;

        target = LogManager.Configuration.FindTargetByName("eventlog");

        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Info);
        LogManager.Configuration.Reload();

    }

测试这个我在两种情况下都改变它,甚至在调试模式下写入“eventlog”。但是在使用事件查看器时它无法正常工作(VS在管理模式下运行)

enter image description here

我在每个班级都设置了

private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

缺什么?

c# logging nlog event-viewer
1个回答
1
投票

这一行将加载NLog.config并查找命名目标:

target = LogManager.Configuration.FindTargetByName("eventlog");

此行将丢弃原始NLog配置(包含所有规则和目标)并使用单个目标创建新的配置:

NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Info);

这一行不会做任何事情:

LogManager.Configuration.Reload();

我想你正在尝试为现有配置添加额外的目标。这可以这样做(替换所有上面的代码):

LogManager.Configuration.AddRule("*", LogLevel.Info, target):
LogManager.ReconfigExistingLoggers();

顺便说一句。如果你没有为EventLog-target配置Source-property,那么它将使用AppDomain.FriendlyName

© www.soinside.com 2019 - 2024. All rights reserved.