简体   繁体   English

C#,Nlog和更改目标

[英]c#, Nlog and change target

i am running windows service, and i want when i run in debugto to write to console and when as service to event viewer. 我正在运行Windows服务,并且我想在debugto中运行时将其写入控制台,并将其作为事件查看器的服务。

in powershell i set 在PowerShell中我设置

New-EventLog –LogName Application –Source "mySource"

I have this nlog.config : 我有这个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> 

i do init when service start : 服务启动时我会进行初始化:

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

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

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

    }

to test this i change it in both cases to write to "eventlog" even in debug mode. 为了测试这一点,即使在调试模式下,我在两种情况下都将其更改为写入“ eventlog”。 but it is not working correctly when using the event viewer (VS is running in admin mode) 但是使用事件查看器时,它无法正常运行(VS在管理员模式下运行)

在此处输入图片说明

i set in each class 我在每堂课上

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

what is missing? 什么东西少了?

This line will load the NLog.config and lookup a named target: 此行将加载NLog.config并查找命名目标:

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

This line will discard the original NLog config (with all rules and targets) and create new one with a single target: 这行代码将丢弃原始的NLog配置(包含所有规则和目标),并使用单个目标创建新的NLog配置:

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

This line will not do anything: 该行将不执行任何操作:

LogManager.Configuration.Reload();

I guess you are trying to add an extra target to the existing configuration. 我猜您正在尝试向现有配置添加额外的目标。 This can be done like this (Replacing all the above code): 可以这样完成(替换上面的所有代码):

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

Btw. 顺便说一句。 if you don't configure the Source -property for the EventLog-target, then it will use AppDomain.FriendlyName 如果您没有为EventLog-target配置Source -property,则它将使用AppDomain.FriendlyName

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM