Win8 Store App的日志输出不像Desktop App 那么简单,见 这篇文档(http://www.cnblogs.com/xiaokang088/archive/2011/12/27/2303725.html)
经过同事指点加google,找到了办法。
1. 自定义EventSource,如下:
public class StoreEventSource : EventSource
{
public static StoreEventSource Instance = new StoreEventSource(); [Event(, Level = EventLevel.Verbose)]
public void Debug(string message)
{
this.WriteEvent(, message);
} [Event(, Level = EventLevel.Informational)]
public void Info(string message)
{
this.WriteEvent(, message);
} [Event(, Level = EventLevel.Warning)]
public void Warn(string message)
{
this.WriteEvent(, message);
} [Event(, Level = EventLevel.Error)]
public void Error(string message)
{
this.WriteEvent(, message);
} [Event(, Level = EventLevel.Critical)]
public void Critical(string message)
{
this.WriteEvent(, message);
}
}
关于这个EventSource,看似简单,说来话长,后面有篇文章,自行捉摸。
2. 自定义EventListenter
sealed class IsolatedStorageEventListener : EventListener
{
private StorageFile store; public IsolatedStorageEventListener(string location)
{
init(location);
} async void init(string location)
{
store = await ApplicationData.Current.LocalFolder.CreateFileAsync(location, CreationCollisionOption.ReplaceExisting);
} protected async override void OnEventWritten(EventWrittenEventArgs eventData)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine(eventData.EventId.ToString());
foreach (object o in eventData.Payload)
{
builder.AppendLine(o.ToString());
}
await FileIO.AppendTextAsync(store, builder.ToString());
} public override void Dispose()
{
base.Dispose();
}
}
带没看起来都不复杂,蛮简单的,急用的同学可以直接拷贝。
注意:这里有问题:初始化文件的时候,用的是 await , 也就是说,在写日志的时候,有可能这里还没初始化完成,这个问题还没妥善解决。
3.调用
IsolatedStorageEventListener listener; private void btnDebug_Click_1(object sender, RoutedEventArgs e)
{
if (listener == null)
{
listener = new IsolatedStorageEventListener("test.txt");
listener.EnableEvents(StoreEventSource.Instance, EventLevel.LogAlways);
} StoreEventSource.Instance.Debug("TestTest");
}
log会写在这里:C:\Users\[username]\AppData\Local\Packages\[package name]\LocalState
[package name] 在 Package.appxmanifest\Packaging\Package name
好了,火急火燎的同学,您可以直接粘贴过去用了,貌似还 有点问题,我也在捉摸。
相关资料如下:
1. 这个EventSource 其实是用来做性能分析的,具体见下文。
Tracing with EventSource in .NET 4.5(http://dev.goshoom.net/en/2013/04/tracing-with-eventsource/)
2.关于ETW和PerView的博客,非常详细
Vance Morrison's Weblog(http://blogs.msdn.com/b/vancem/)
3.specification for EventSource , 这个很重要。
The specification for the System.Diagnostics.Tracing.EventSource class.
http://blogs.msdn.com/b/vancem/archive/2012/07/09/more-details-on-eventsource-the-class-specification.aspx
就这些了,我也是刚开始学习,不对的地方请多多指教。