简体   繁体   中英

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.

in powershell i set

New-EventLog –LogName Application –Source "mySource"

I have this 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. but it is not working correctly when using the event viewer (VS is running in admin mode)

在此处输入图片说明

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:

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.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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