mur*_*nsk 10 c# windows-runtime winrt-xaml win-universal-app windows-10
我正在尝试为Windows Universal Application创建事件日志.早些时候我们不得不System.Diagnostics EventLog记录事件,但我在Windows 10 Universal Apps平台上找不到类似的东西.是否可以为Windows 10创建日志,是否可以将这些日志写入文件以便以后访问?
我搜索了很多,但找不到任何东西.
FileLoggingSession
由于命名空间中Windows 8.1有FileLoggingSession和LoggingChannel类Windows.Foundation.Diagnostics,因此在配置时可以执行对文件的记录.您可以在官方文档中阅读更多内容.
初始化,使用和检索日志文件可以像在下面的代码片段中那样完成,当然您需要创建接口,单例等以使其可用:
// 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
Run Code Online (Sandbox Code Playgroud)
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>();
}
Run Code Online (Sandbox Code Playgroud)
然后你可以在页面中使用它,如下所示:
// 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);
}
Run Code Online (Sandbox Code Playgroud)
MetroEventSource
第二个解决方案是Can Bilgin在MSDN示例库中的这个日志示例,您可以在这里获得MetroEventSource该类.您可以记录消息,例如这样的错误:
MetroEventSource.Log.Error("Here is the error message");
Run Code Online (Sandbox Code Playgroud)
如果使用此记录器,请不要忘记在应用程序运行时对其进行初始化,如示例项目中所述.
| 归档时间: |
|
| 查看次数: |
6410 次 |
| 最近记录: |