Is this the correct way to log to a specific target with NLog?
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
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