【问题标题】:c#, Nlog and change targetc#, Nlog 和更改目标
【发布时间】:2019-03-14 11:16:57
【问题描述】:

我正在运行 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> 

我在服务启动时进行初始化:

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

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

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

    }

为了测试这一点,我在两种情况下都将其更改为写入“事件日志” 即使在调试模式下。但使用事件查看器时无法正常工作(VS 以管理员模式运行)

我在每个班级都设置了

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

缺少什么?

【问题讨论】:

  • 更新:我发现偶数观众在这里写字(见图)pasteboard.co/I5ngzT8.png
  • 很高兴也能看到你的nlog.config
  • 看不到任何名为eventlog的目标
  • @RolfKristensen 我更新了之前的答案
  • 你应该只有一个 NLog 配置。不在 app.config 和 nlog.config 中。

标签: c# logging nlog event-viewer


【解决方案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

【讨论】:

  • 问题是事件没有写到正确的地方,而是写到了这个(图中红圈)pasteboard.co/I5ngzT8.png
  • 您是否阅读了我关于为 EventLog-target 配置 Source-property 的评论?另见github.com/nlog/NLog/wiki/EventLog-target
  • 您是否记得删除所有错误代码,并使用我推荐的AddRule-call?
  • 如果 Source-property 为 eventlog-target 正确配置,可能检查 github.com/NLog/NLog/wiki/Internal-Logging
  • 现在它可以正确写入事件日志,我的目标是在调试中仅写入控制台并作为服务仅写入事件查看器。目前它在我添加 AddRule 后写入这两个地方
猜你喜欢
  • 2021-09-27
  • 2012-07-09
  • 1970-01-01
  • 1970-01-01
  • 2015-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多