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.
NLog is a flexible and free logging platform for various . NET platforms, including . NET standard. NLog makes it easy to write to several targets. (database, file, console) and change the logging configuration on-the-fly.
NLog supports the following levels: Trace - Very detailed log messages, potentially of a high frequency and volume. Debug -Less detailed and/or less frequent debugging messages. Info - Informational messages.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With