Mercurial > pub > ImplabNet
comparison Implab/Diagnostics/ListenerBase.cs @ 134:04d4c92d0f28 v2
Improved logging
author | cin |
---|---|
date | Wed, 11 Feb 2015 02:12:15 +0300 |
parents | |
children | 240aa6994018 |
comparison
equal
deleted
inserted
replaced
133:6c49d02a9a05 | 134:04d4c92d0f28 |
---|---|
1 using System; | |
2 using System.Collections.Generic; | |
3 using System.Linq; | |
4 using System.Text; | |
5 | |
6 namespace Implab.Diagnostics { | |
7 public abstract class ListenerBase : ServiceLocator, ILogWriter<object>, ILogWriter<TraceEvent> { | |
8 | |
9 readonly Dictionary<object, Action> m_subscriptions = new Dictionary<object, Action>(); | |
10 | |
11 protected ListenerBase() { | |
12 Register(this); | |
13 } | |
14 | |
15 public void Subscribe(Type eventType) { | |
16 if (eventType == null) | |
17 throw new ArgumentNullException("eventType"); | |
18 GetType().GetMethod("Subscribe", new Type[0]).MakeGenericMethod(eventType).Invoke(this, null); | |
19 } | |
20 | |
21 public void Subscribe<TEvent>() { | |
22 Subscribe<TEvent>(LogChannel<TEvent>.Default); | |
23 } | |
24 | |
25 public void Subscribe<TEvent>(LogChannel<TEvent> channel) { | |
26 if (channel == null) | |
27 throw new ArgumentNullException("channel"); | |
28 | |
29 lock (m_subscriptions) { | |
30 AssertNotDisposed(); | |
31 if (m_subscriptions.ContainsKey(channel)) | |
32 return; | |
33 | |
34 var writer = GetService<ILogWriter<TEvent>>(); | |
35 | |
36 EventHandler<LogEventArgs<TEvent>> handler = (sender, args) => writer.Write(args,args.Value); | |
37 | |
38 channel.Events += handler; | |
39 | |
40 Action unsubscribe = () => { | |
41 channel.Events -= handler; | |
42 }; | |
43 | |
44 m_subscriptions.Add(channel, unsubscribe); | |
45 } | |
46 } | |
47 | |
48 public void Unsubscribe<TEvent>(LogChannel<TEvent> channel) { | |
49 if (channel == null) | |
50 throw new ArgumentNullException("channel"); | |
51 | |
52 lock (m_subscriptions) { | |
53 Action subscription; | |
54 if (m_subscriptions.TryGetValue(channel, out subscription)) { | |
55 subscription(); | |
56 m_subscriptions.Remove(channel); | |
57 } | |
58 } | |
59 } | |
60 | |
61 public void UnsubscribeAll() { | |
62 lock (m_subscriptions) { | |
63 foreach (var subscription in m_subscriptions.Values) | |
64 subscription(); | |
65 m_subscriptions.Clear(); | |
66 } | |
67 } | |
68 | |
69 #region ILogWriter implementation | |
70 public abstract void Write(LogEventArgs args, object entry); | |
71 #endregion | |
72 | |
73 #region ILogWriter implementation | |
74 public virtual void Write(LogEventArgs args, TraceEvent entry) { | |
75 Write(args, (object)entry); | |
76 } | |
77 #endregion | |
78 | |
79 | |
80 protected override void Dispose(bool disposing) { | |
81 base.Dispose(disposing); | |
82 if (disposing) { | |
83 UnsubscribeAll(); | |
84 } | |
85 } | |
86 } | |
87 } |