您可以使用LoggingChannel class。创建ETW 跟踪事件。
LoggingChannel 很酷的一点是您可以进行复杂的跟踪(并使用高级工具,如PerfView 等),但您也可以使用LoggingChannel.LogMessage Method 来简单地等效于Debug.WriteLine
public void LogMessage(String eventString)
或
public void LogMessage(String eventString, LoggingLevel level)
这比Debug.WriteLine 有很多优势:
- 速度要快得多,您可以轻松记录数百万条消息,而
Debug.WriteLine 速度很慢(基于古老的 Windows 的 OutputDebugString 函数)。
- 它不会阻止发送者或接收者。
- 每个频道都由自己的 guid 标识,而使用
Debug.WriteLine,您可以从任何地方获取所有跟踪,每个人,找到自己的跟踪有点麻烦。
- 您可以使用跟踪级别(Critical、Error、Information、Verbose、Warning)
- 您可以使用 PerfView(如果您真的需要)或 Device Portal 或任何其他 ETW tool。
所以,要发送一些跟踪,只需添加以下内容:
// somewhere in your initialization code, like in `App` constructor
private readonly static LoggingChannel _channel = new LoggingChannel("MyApp",
new LoggingChannelOptions(),
new Guid("01234567-01234-01234-01234-012345678901")); // change this guid, it's yours!
....
// everywhere in your code. add simple string traces like this
_channel.LogMessage("hello from UWP!");
....
现在,如果您想要一种简单的方法在本地计算机上显示这些跟踪,除了使用 PerfView 或其他 ETW 工具之外,您还可以使用我编写的免费开源 GUI 工具 WpfTraceSpy 可用:https://github.com/smourier/TraceSpy#wpftracespy 或这里一个示例 .NET Framework 控制台应用程序,它将所有跟踪及其级别输出到控制台:
using System;
using System.Runtime.InteropServices;
using Microsoft.Diagnostics.Tracing; // you need to add the Microsoft.Diagnostics.Tracing.TraceEvent nuget package
using Microsoft.Diagnostics.Tracing.Session;
namespace TraceTest
{
class Program
{
static void Main()
{
// create a real time user mode session
using (var session = new TraceEventSession("MySession"))
{
// use UWP logging channel provider
session.EnableProvider(new Guid("01234567-01234-01234-01234-012345678901")); // use the same guid as for your LoggingChannel
session.Source.AllEvents += Source_AllEvents;
// Set up Ctrl-C to stop the session
Console.CancelKeyPress += (object s, ConsoleCancelEventArgs a) => session.Stop();
session.Source.Process(); // Listen (forever) for events
}
}
private static void Source_AllEvents(TraceEvent obj)
{
// note: this is for the LoggingChannel.LogMessage Method only! you may crash with other providers or methods
var len = (int)(ushort)Marshal.ReadInt16(obj.DataStart);
var stringMessage = Marshal.PtrToStringUni(obj.DataStart + 2, len / 2);
// Output the event text message. You could filter using level.
// TraceEvent also contains a lot of useful informations (timing, process, etc.)
Console.WriteLine(obj.Level + ":" + stringMessage);
}
}
}