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(1, Level = EventLevel.Verbose)] public void Debug(string message) { this.WriteEvent(1, message); } [Event(2, Level = EventLevel.Informational)] public void Info(string message) { this.WriteEvent(2, message); } [Event(3, Level = EventLevel.Warning)] public void Warn(string message) { this.WriteEvent(3, message); } [Event(4, Level = EventLevel.Error)] public void Error(string message) { this.WriteEvent(4, message); } [Event(5, Level = EventLevel.Critical)] public void Critical(string message) { this.WriteEvent(5, 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
就這些了,我也是剛開始學習,不對的地方請多多指教。