Working Experience - NLog 多实例时配置文件冲突
正文
问题: 当前项目已使用 NLog 的情况下再引用使用 NLog 的项目, 出现配置文件冲突, 有一个配置文件不工作
方法: 使用 LogFactory 代替 LogManager 来获取 Logger 实例
internal class MyLogManager
{
// A Logger dispenser for the current assembly (Remember to call Flush on application exit)
public static LogFactory Instance { get { return _instance.Value; } }
private static Lazy<LogFactory> _instance = new Lazy<LogFactory>(BuildLogFactory);
//
// Use a config file located next to our current assembly dll
// eg, if the running assembly is c:\path\to\MyComponent.dll
// the config filepath will be c:\path\to\MyComponent.nlog
//
// WARNING: This will not be appropriate for assemblies in the GAC
//
private static LogFactory BuildLogFactory()
{
// Use name of current assembly to construct NLog config filename
Assembly thisAssembly = Assembly.GetExecutingAssembly();
string configFilePath = Path.ChangeExtension(thisAssembly.Location, ".nlog");
LogFactory logFactory = new LogFactory();
logFactory.Configuration = new XmlLoggingConfiguration(configFilePath, true, logFactory);
return logFactory;
}
}
// 使用下面两个方法中的一个获取 Logger 实例
Logger logger = MyLogManager.Instance.GetCurrentClassLogger();
Logger logger = MyLogManager.Instance.GetLogger("name");