经过一番战斗......(如果你不想要这个故事,只需复制下面的代码)
让我们首先说 GAC(全局汇编缓存)被发明的原因之一是在同一个地方使用多个版本的 dll。
所以..我有一个带有 NLog 2.0 的 Sharepoint 项目,我需要添加一个依赖于 NLog 3.2 的带有 dll 的第二个解决方案,问题是,在将所有内容推送到 GAC(对 SafeControls - 对于 sp 开发人员而言)之后,记录器只是从未登录过新的解决方案。
当我再次查看我的 web.config 时,铃声响起
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog, Version=2.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c" />
注意版本=2.0.0.0
所以后来我知道 NLog 只是加载旧项目的配置,并且在开始使用 3.2 dll 时以某种方式没有传递它。
我也尝试重新加载配置,做 DeepCopy,不明白为什么那不起作用。
然后我LoggingConfiguration
在代码中重新定义了 a 以在保存旧配置的同时重新初始化记录器,登录该类,然后在析构函数中再次使用旧配置重新初始化。
我猜结果是记录器现在在任何地方都使用 3.2 和 2.0 配置。
但后来我讨厌两件事:1 - 有一个析构函数,2 - 没有来自 web.config 的配置,并试图做所有的海峡没有工作,并观察到有时我认为有一些延迟的日志有可能是一些队列或者我最终找到了正确的方法来制作一个知道适当地重新启动 NLog 的 CTOR:
public EncryptEventReceiver()
{
oldConfig = LogManager.Configuration;
Task t = new Task(() =>
{
FileTarget target = new FileTarget();
target.FileName = "c:\\Data\\Logs\\MyProj\\EncryptEventReceiver.txt";
target.Layout = "${message}";
target.Encoding = Encoding.UTF8;
LoggingRule rule = new LoggingRule("*", LogLevel.Trace, target);
LoggingConfiguration config = new LoggingConfiguration();
config.AddTarget("FileLog", target);
config.LoggingRules.Add(rule);
LogManager.Configuration = config;
var _logger = LogManager.GetCurrentClassLogger();
_logger.Trace("EncryptEventReceiver CTOR initialized Logger");
});
t.Start();
t.Wait();
LogManager.GetCurrentClassLogger().Trace("EncryptEventReceiver MIDDLE");
LogManager.Configuration = oldConfig;
nlog3 = LogManager.GetCurrentClassLogger();
nlog3.Trace("EncryptEventReceiver CTOR done, nlog3 ready");
}
编辑:最后导致一些日志丢失,所以我回到了 CTOR-Destrucor,建议更频繁地使用 web-config
public static Logger nlog3;
private static LoggingConfiguration oldConfig;
public EncryptEventReceiver()
{
oldConfig = LogManager.Configuration;
FileTarget target = new FileTarget();
target.FileName = "c:\\Data\\Logs\\MyProj\\EncryptEventReceiver.txt";
target.Layout = "${date:format=yyyy-MM-dd HH\\:mm\\:ss} ${level} ${message} ${exception:format=tostring}";
target.ArchiveAboveSize = 5242880;
target.ArchiveFileName = "c:\\Data\\Logs\\MyProj\\Archive_EncryptEventReceiver\\EncryptEventReceiver_${shortdate}_{#}.txt";
target.Encoding = Encoding.UTF8;
LoggingRule rule = new LoggingRule("*", LogLevel.Trace, target);
LoggingConfiguration config = new LoggingConfiguration();
config.AddTarget("FileLog", target);
config.LoggingRules.Add(rule);
LogManager.Configuration = config;
nlog3 = LogManager.GetCurrentClassLogger();
nlog3.Trace("EncryptEventReceiver CTOR done, nlog3 ready");
}
~EncryptEventReceiver()
{
nlog3.Trace("EncryptEventReceiver Destructor");
LogManager.Configuration = oldConfig;
LogManager.GetCurrentClassLogger().Trace("EncryptEventReceiver Destructor done");
}