Reputation: 1920
I have class library (that I would be distributing) which has a log appender that writes some metrics to a specific location. I have the appenders configured in a csharp file
var config = new LoggingConfiguration();
const string layout = @"${longdate}|${level:uppercase=true}(${threadid})|${logger}|${message}";
//File appender
var fileTarget = new FileTarget
{
Layout = layout,
FileName = "${basedir}/logs/Desktop.Log",
MaxArchiveFiles = 5,
ArchiveAboveSize = 5000000
};
config.AddTarget("file", fileTarget);
var fileRule = new LoggingRule("*", LogLevel.Debug, fileTarget);
config.LoggingRules.Add(fileRule);
//Activate
LogManager.Configuration = config;
Firstly, is it a good idea to activate log manager in a library project that I am planning to distribute? I am doing it this way as my library needs to log data to a file and it should not be turned off by the consuming App
If the consuming app uses the same logging library and if it replaces my config with their implementation, would it not overwrite the rules that I had defined in my library? I want to make sure that the library continues to log data to a file.
Upvotes: 0
Views: 101
Reputation: 1920
I ended up using a LogFactory which would protect my library's logging config from being overwritten by a consuming Application
Here is how I create an instance of LogFactory
class NLogManager
{
public static readonly LogFactory Instance = new LogFactory(GetConfig());
private static LoggingConfiguration GetConfig()
{
var config = new LoggingConfiguration();
const string layout = @"${longdate}|${level:uppercase=true}(${threadid})|${logger}|${message}";
//Console appender
var consoleTarget = new ColoredConsoleTarget
{
Layout = layout,
UseDefaultRowHighlightingRules = true
};
config.AddTarget("PPH.ConsoleTarget", consoleTarget);
var consoleRule = new LoggingRule("*", LogLevel.Debug, consoleTarget);
config.LoggingRules.Add(consoleRule);
return config;
}
And I invoke the logger by calling the Instance method on the log manager
var logger = Instance.GetLogger(component);
logger.debug("hello world!");
Upvotes: 1