【发布时间】:2013-04-02 08:46:14
【问题描述】:
所有 ViewModel 类都继承自一个基类:
public abstract class ScreenBase : ViewModelBase, IScreen, IDisposable
{
protected readonly NLog.Logger _logger;
protected ScreenBase()
: this(Messenger.Default) { }
protected ScreenBase(IMessenger messenger)
: base(messenger)
{
_logger = NLog.LogManager.GetLogger(this.GetType().Name);
_logger.Debug("{0} ({1}) constructed. ", this.GetType().Name, this.GetHashCode());
}
~ScreenBase()
{
FinalizeProc();
}
[Conditional("DEBUG")]
private void FinalizeProc()
{
_logger.Debug("{0} ({1}) Finalized. ", this.GetType().Name, this.GetHashCode());
}
}
如您所见,任何时候 ViewModel 实例被创建/销毁,它都应该记录它。我将其登录到控制台窗口和文件:
<targets>
<!-- add your targets here -->
<target name="logDebugInfo" xsi:type="File" deleteOldFileOnStartup="true" fileName="${specialfolder:folder=CommonApplicationData}/MyApp/debug.txt" layout="${longdate} | ${uppercase:${level}} | ${stacktrace} | ${message}${onexception:EXCEPTION OCCURRED\:${exception:format=tostring}}" />
<target name="console" xsi:type="Console" />
</targets>
<rules>
<!-- add your logging rules here -->
<logger name="*" minlevel="Trace" maxlevel="Info" writeTo="logDebugInfo" />
<logger name="*" minlevel="Trace" writeTo="console" />
</rules>
在应用程序关闭之前,每条消息都会被正确记录。当在主视图上按下“X”关闭按钮时,我没有在代码中做任何特定的事情,我让应用程序自行关闭。但是,此时不会显示“已完成”消息。
有人知道为什么吗?
【问题讨论】:
-
Finalizer not called的可能重复
-
不重复,调用了finalizer,执行了_logger.Debug(...),但是file/console中的输出没有注册。
-
问题类似,但您对该主题的评论使我得出结论,为什么会发生这种情况。启用 InternalLogger 后,我注意到 Logger 在应用程序关闭时被破坏,所以它没有记录的原因。如果您想发布您的答案,只需提及启用内部记录器或其他内容,我会接受。