我正在尝试为Windows通用应用程序创建事件日志。
之前我们使用过 System.Diagnostics EventLog
来记录事件,但我在Windows 10通用应用平台上找不到类似的东西。
是否可以为Windows 10创建日志,并且这些日志可以写入文件以供以后访问?
我搜索了很多,但没有找到任何信息。
我正在尝试为Windows通用应用程序创建事件日志。
之前我们使用过 System.Diagnostics EventLog
来记录事件,但我在Windows 10通用应用平台上找不到类似的东西。
是否可以为Windows 10创建日志,并且这些日志可以写入文件以供以后访问?
我搜索了很多,但没有找到任何信息。
FileLoggingSession
自从Windows 8.1
以来,在Windows.Foundation.Diagnostics
命名空间中,有FileLoggingSession
和LoggingChannel
类,当配置完成后可以执行文件日志记录。您可以在官方文档中了解更多。
初始化、使用和检索日志文件可以像以下片段一样实现,当然您需要创建接口、单例等使其可用:
// Initialization
FileLoggingSession fileLoggingSession = new FileLoggingSession("session");
var loggingChannel = new LoggingChannel("channel");
fileLoggingSession.AddLoggingChannel(loggingChannel);
// Log messages
loggingChannel.LogMessage("error message", LoggingLevel.Error);
// When file is needed
var file = await fileLoggingSession.CloseAndSaveToFileAsync();
// Do anything with file
LoggingSession
LoggingSession
和FileLoggingSession
都是用于写入日志文件的类,但它们之间的主要区别在于FileLoggingSession
会立即将日志写入文件,而LoggingSession
不会,你需要手动使用SaveToFileAsync
方法请求将日志写入文件。根据文档:
FileLoggingSession类会在记录消息时将其发送到磁盘文件中。FileLoggingSession类使用顺序记录,这意味着所有消息都被发送到一个磁盘文件中,并保留了一个顺序消息历史记录。这与LoggingSession类不同,LoggingSession类会按需将记录的消息发送到磁盘上,当出现问题并需要分析内存中的最近历史消息时,才会发生这种情况。
MetroLog
如果您不想使用FileLoggingSession
或LoggingSession
类,还有其他选择。其中一个好的解决方案是MetroLog,它具有FileStreamingTarget
目标,非常适合在Windows/Phone应用程序中记录日志。
您可以在需要时创建记录器,例如在页面中:
public sealed partial class LogSamplePage : Win8Sample.Common.LayoutAwarePage
{
private ILogger Log = LogManagerFactory.DefaultLogManager.GetLogger<LogSamplePage>();
}
// flat strings...
if (this.Log.IsInfoEnabled)
this.Log.Info("I've been navigated to.");
// formatting...
if (this.Log.IsDebugEnabled)
this.Log.Debug("I can also format {0}.", "strings");
// errors...
try
{
this.DoMagic();
}
catch(Exception ex)
{
if (this.Log.IsWarnEnabled)
this.Log.Warn("You can also pass in exceptions.", ex);
}
MetroEventSource
第二种解决方案是在MSDN样例库中的此处,由Can Bilgin编写的日志记录示例,其中包含MetroEventSource
类。您可以像这样记录消息,例如错误:
MetroEventSource.Log.Error("Here is the error message");