13
votes

I'd like to log some special events into a different table that will contain more data then the general application log.

If I add a second database target to the NLog.config how can I use it in my code?

Would this be the right thing to do:

NLog
    .LogManager
    .Configuration
    .AllTargets
    .Single(x => x.Name == "mySecondLogTable")
    .WriteAsyncLogEvent(...);

Then in the NLog.config I would just skip this target in the rules element, right?


Summary: I'd like to define multiple database targets like a general log and specialized log for cases where I need to log more details into a different table. I'd like to use the general log by default and the special log only in functions that need this special kind of logging because of their business logic.

2
I'd use only config settings and no source code. The config file is a mix of Targets & Rules. You can use it to control where the entries are written. - Fabrizio Accatino
Agreeing with @FabrizioAccatino. XML configurations may seem daunting at first, but I highly recommend it for NLog. It makes the process much more understandable, and you can easily make highly configurable targets/rules. - Flater
Yes, I also prefer XML configurations but I found only this so I thought I'd better ask if this is ok because I had the feeling I'm doing something terribly wrong. - t3chb0t

2 Answers

24
votes

You can always create another logger instance and use the NLog LoggingRules for redirection to the wanted target.

For example I want to make an extended logging into a separate file. Then I go and create:

<nlog>
  <rules>
    <!--- Notice that final=true stops the logevents from also reaching defaultTarget -->
    <logger name="ExtendedLogging" minlevel="Trace" writeTo="extendedTarget" final="true" />
    <!--- Wildcard rule will capture all logevents not matching the "final" rule above -->
    <logger name="*" minlevel="Trace" writeTo="defaultTarget" />
  </rules>
    
  <targets>
    <target name="extendedTarget" xsi:type="File" fileName="ExtendedLog_${shortdate}.log" />
    <target name="defaultTarget" xsi:type="File" fileName="AppLog_${shortdate}.log" />
  </targets>
</nlog>

And then I go to the code and create

private readonly Logger logger = LogManager.GetLogger("ExtendedLogging");

I don't think it's a good idea to search for something inside the config-file and perform logging through something like a backdoor. It's better to make all this things explicitly.

See also: https://github.com/nlog/nlog/wiki/Configuration-file#rules

1
votes
    var fileLogger = LogManager.Configuration.AllTargets.Single(x => x.Name == "file");
    fileLogger.WriteAsyncLogEvents(
                            new LogEventInfo(LogLevel.Info, null, error.ToString())
                            .WithContinuation(new NLog.Common.AsyncContinuation(_ => { })));

I am not sure what did I do but it works. Because the accepted solution didn't