comparison Implab/Diagnostics/TextListenerBase.cs @ 43:7c2369f580b8

improved tracing, TextListenerBase can be bound to logical operation scope.
author cin
date Wed, 16 Apr 2014 10:12:56 +0400
parents fe33f4e02ad5
children b181f7bcb259
comparison
equal deleted inserted replaced
42:3ba6778ed336 43:7c2369f580b8
5 5
6 namespace Implab.Diagnostics { 6 namespace Implab.Diagnostics {
7 public abstract class TextListenerBase : ServiceLocator, IEventTextFormatter<object>, IEventTextFormatter<TraceEvent> { 7 public abstract class TextListenerBase : ServiceLocator, IEventTextFormatter<object>, IEventTextFormatter<TraceEvent> {
8 8
9 readonly Dictionary<object, Action> m_subscriptions = new Dictionary<object, Action>(); 9 readonly Dictionary<object, Action> m_subscriptions = new Dictionary<object, Action>();
10 readonly LogicalOperation m_boundOperation;
11 readonly int m_baseIndent;
10 12
11 protected TextListenerBase() { 13 protected TextListenerBase(bool local) {
12 Register(this); 14 Register(this);
15 if (local) {
16 m_boundOperation = TraceContext.Current.CurrentOperation;
17 m_baseIndent = Math.Max(0, m_boundOperation.Level - 1);
18 }
13 } 19 }
14 20
15 public void Subscribe(Type eventType) { 21 public void Subscribe(Type eventType) {
16 if (eventType == null) 22 if (eventType == null)
17 throw new ArgumentNullException("eventType"); 23 throw new ArgumentNullException("eventType");
30 AssertNotDisposed(); 36 AssertNotDisposed();
31 37
32 var formatter = GetService<IEventTextFormatter<TEvent>>(); 38 var formatter = GetService<IEventTextFormatter<TEvent>>();
33 39
34 EventHandler<ValueEventArgs<TEvent>> handler = (sender, args) => { 40 EventHandler<ValueEventArgs<TEvent>> handler = (sender, args) => {
35 WriteEntry((TraceContext)sender, formatter.Format((TraceContext)sender, args.Value)); 41 TraceContext context = (TraceContext)sender;
42 var text = formatter.Format(context, args.Value);
43 text.indent -= m_baseIndent;
44
45 if (IsRelated(context.CurrentOperation))
46 WriteEntry(context, text);
36 }; 47 };
37 48
38 if (m_subscriptions.ContainsKey(channel)) 49 if (m_subscriptions.ContainsKey(channel))
39 return; 50 return;
40 51
44 channel.Events -= handler; 55 channel.Events -= handler;
45 }; 56 };
46 57
47 m_subscriptions.Add(channel, unsubscribe); 58 m_subscriptions.Add(channel, unsubscribe);
48 } 59 }
60 }
61
62 public bool IsRelated(LogicalOperation op) {
63 if (m_boundOperation == null)
64 return true;
65
66 while (op != m_boundOperation && op.Level > m_boundOperation.Level)
67 op = op.Parent;
68 return op == m_boundOperation;
49 } 69 }
50 70
51 public void Unsubscribe<TEvent>(LogChannel<TEvent> channel) { 71 public void Unsubscribe<TEvent>(LogChannel<TEvent> channel) {
52 if (channel == null) 72 if (channel == null)
53 throw new ArgumentNullException("channel"); 73 throw new ArgumentNullException("channel");