Windows 10通用应用程序中的事件记录器

10

我正在尝试为Windows通用应用程序创建事件日志。 之前我们使用过 System.Diagnostics EventLog 来记录事件,但我在Windows 10通用应用平台上找不到类似的东西。 是否可以为Windows 10创建日志,并且这些日志可以写入文件以供以后访问?

我搜索了很多,但没有找到任何信息。

1个回答

9

FileLoggingSession

自从Windows 8.1以来,在Windows.Foundation.Diagnostics命名空间中,有FileLoggingSessionLoggingChannel类,当配置完成后可以执行文件日志记录。您可以在官方文档中了解更多。

初始化、使用和检索日志文件可以像以下片段一样实现,当然您需要创建接口、单例等使其可用:

// 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

LoggingSessionFileLoggingSession都是用于写入日志文件的类,但它们之间的主要区别在于FileLoggingSession会立即将日志写入文件,而LoggingSession不会,你需要手动使用SaveToFileAsync方法请求将日志写入文件。根据文档:

FileLoggingSession类会在记录消息时将其发送到磁盘文件中。FileLoggingSession类使用顺序记录,这意味着所有消息都被发送到一个磁盘文件中,并保留了一个顺序消息历史记录。这与LoggingSession类不同,LoggingSession类会按需将记录的消息发送到磁盘上,当出现问题并需要分析内存中的最近历史消息时,才会发生这种情况。

MetroLog

如果您不想使用FileLoggingSessionLoggingSession类,还有其他选择。其中一个好的解决方案是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");

如果您使用此记录器,请不要忘记在应用程序运行时进行初始化,如示例项目中所述。

1
我已经阅读了FileLoggingSession的文档,它说FileLoggingSession会立即记录到硬盘中。然而,我没有看到任何相关示例。似乎我们需要创建一个日志通道,将其添加到FileLoggingSession中,并使用此日志通道进行记录。最后,当我们调用fileLoggingSession.closeAndSavetoFileAsync()时,它会将日志写入文件。问题是如何使用FileLoggingSession立即将日志写入硬盘?因为如果我的应用程序在此之前崩溃,我可能无法调用closeAndSaveToFileAsync()。请帮忙解决。谢谢! - Saurabh Rai
@Kristian:我们可以使用您提到的任何一种解决方案来登录Windows事件查看器吗,就像使用System.Diagnostics EventLog一样? - Pap

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接