Reputation: 425
I need to write event log for every instance of class to separate file. Historically project uses NLog for logging, so I want to try resolving this issue using NLog (I've found similar topic Unique log file for each instance of class , but it's suggests using log4net)
Currently I'm getting instance of logger like this:
public static Logger GetInstanceLogger(string name, bool init = false)
{
if (!LogManager.Configuration.AllTargets.Any(t => t.Name == name))
{
var target = new FileTarget();
target.Name = name;
target.FileName = string.Format("logs/{0}.${{shortdate}}.log", name);
target.Layout =
"${date:format=dd.MM.yyyy HH\\:mm\\:ss.fff} thread[${threadid}] ${logger} (${level:uppercase=true}): ${message}. ${exception:format=ToString}";
var config = init ? new LoggingConfiguration() : LogManager.Configuration;
config.AddTarget(name, target);
var ruleInfo = new LoggingRule("*", LogLevel.Trace, target);
config.LoggingRules.Add(ruleInfo);
LogManager.Configuration = config;
LogManager.ReconfigExistingLoggers();
}
var logger = LogManager.GetLogger(name);
return logger;
}
Right now it's writing same log into all files (I suppose it's caused by the log level). Is there a way to accomplish this task using NLog?
Thanks.
Upvotes: 1
Views: 3171
Reputation: 425
I came out with solution using event properties of layout renderer in the filename. When I'm writing new message to log, I'm adding filename as a property for LogEventInfo
protected virtual void SendEvent(LogLevel level, string message, Exception exception, string memberName = null)
{
var logEvent = new LogEventInfo(level, _name, message);
logEvent.Exception = exception;
foreach (String key in _properties.Keys)
{
logEvent.Properties[key] = _properties[key];
}
_logger.Log(logEvent);
}
And in configuration file in NLog targets section:
<targets async="true">
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}_${event-properties:item=Name}.log"
layout="${detailedLayout}" />
<target xsi:type="File" name="errorLogFile" fileName="${basedir}/logs/${shortdate}.ERROR_${event-properties:item=Name}.log"
layout="${detailedLayout}" />
</targets>
Upvotes: 3
Reputation: 1
try var ruleInfo = new LoggingRule(name, LogLevel.Trace, target);
Upvotes: -2