Reputation: 1392
I have two SharePoint timer jobs that exists in the same process at the same time. The jobs have nothing to do with each other and shoudln't share NLog configuration. However they tend to overlap each other configurations, logging in each others file.
All configuration is done by code. The targets are named and the logger is named. And i make sure to get a reference of the current LogManager.Configuration and reloading it.
Configuration in first timer job:
if (LogManager.Configuration == null)
{
LogManager.Configuration = new LoggingConfiguration();
}
var fileTarget = new FileTarget();
LogManager.Configuration.AddTarget("file", fileTarget);
fileTarget.Encoding = Encoding.UTF8;
fileTarget.FileName = "C:/OTDPLog/Log-{0}.txt"._Format(DateTime.Now.ToString("dd-MM-yyyy_hhmmss"));
fileTarget.Layout = "${date:format=HH\\:mm\\:ss} ${logger} ${event-context:item=Dev} [${level:uppercase=true}]\t${message}. ${exception:format=ToString,StackTrace}";
var async = new AsyncTargetWrapper(fileTarget, 5000, AsyncTargetWrapperOverflowAction.Block);
var rule = new LoggingRule("OTDP", LogLevel.Debug, async);
LogManager.Configuration.LoggingRules.Add(rule);
LogManager.Configuration.Reload();
Usage:
var logger = LogManager.GetLogger("OTDP");
logger.Info("bla bla bla");
Configuration for the other job:
if (LogManager.Configuration == null)
{
LogManager.Configuration = new LoggingConfiguration();
}
var fileTarget = new FileTarget();
LogManager.Configuration.AddTarget("file", fileTarget);
fileTarget.Encoding = Encoding.UTF8;
fileTarget.FileName = "C:/WikiLog/Log-{0}.txt"._Format(DateTime.Now.ToString("dd-MM-yyyy_hhmmss"));
fileTarget.Layout = "${date:format=HH\\:mm\\:ss} ${logger} ${event-context:item=Dev} [${level:uppercase=true}]\t${message}. ${exception:format=ToString,StackTrace}";
var async = new AsyncTargetWrapper(fileTarget, 5000, AsyncTargetWrapperOverflowAction.Block);
var rule = new LoggingRule("Wiki", LogLevel.Debug, async);
LogManager.Configuration.LoggingRules.Add(rule);
LogManager.Configuration.Reload();
Usage:
var logger = LogManager.GetLogger("Wiki");
logger.Info("bla bla bla");
How do i setup loggers for different applications in the same process?
Upvotes: 3
Views: 1958
Reputation: 1392
So i finally found the solution. First, it's not possible when configuring NLog to work directly on LogManager.Configuration, i had to obtain a reference, do my work on that reference and finally set the LogManager.Configuration. Second, i had to rename the targets they were both named "file" and they had to have different names.
if (LogManager.Configuration == null)
{
LogManager.Configuration = new LoggingConfiguration();
}
var config = LogManager.Configuration;
// Do my stuff, add targets and rules...
LogManager.Configuration = config;
Upvotes: 5