annotate Implab/Diagnostics/TraceContext.cs @ 40:fe33f4e02ad5

improved tracing added text listeners (file,console)
author cin
date Tue, 15 Apr 2014 17:52:09 +0400
parents c2c043520724
children 2fc0fbe7d58b
Ignore whitespace changes - Everywhere: Within whitespace: At end of lines:
rev   line source
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
1 using System;
313f708a50e9 improved log concept
cin
parents:
diff changeset
2 using System.Collections.Generic;
313f708a50e9 improved log concept
cin
parents:
diff changeset
3 using System.Linq;
313f708a50e9 improved log concept
cin
parents:
diff changeset
4 using System.Text;
313f708a50e9 improved log concept
cin
parents:
diff changeset
5 using System.Threading;
313f708a50e9 improved log concept
cin
parents:
diff changeset
6 using System.Threading.Tasks;
313f708a50e9 improved log concept
cin
parents:
diff changeset
7
313f708a50e9 improved log concept
cin
parents:
diff changeset
8 namespace Implab.Diagnostics {
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
9 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
10 /// Контекст трассировки, привязывается к потоку и содержит в себе информацию о стеке логических операций.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
11 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
12 /// <remarks>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
13 /// Контекст трассировки передается слушателям событий для определения места, где возникло событие.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
14 /// </remarks>
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
15 public class TraceContext {
313f708a50e9 improved log concept
cin
parents:
diff changeset
16 LogicalOperation m_currentOperation;
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
17 readonly LogicalOperation m_bound;
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
18 readonly int m_threadId;
313f708a50e9 improved log concept
cin
parents:
diff changeset
19
313f708a50e9 improved log concept
cin
parents:
diff changeset
20 [ThreadStatic]
313f708a50e9 improved log concept
cin
parents:
diff changeset
21 static TraceContext _current;
313f708a50e9 improved log concept
cin
parents:
diff changeset
22
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
23 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
24 /// Текущий контекст трассировки для потока, создается астоматически при первом обращении.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
25 /// </summary>
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
26 public static TraceContext Current {
313f708a50e9 improved log concept
cin
parents:
diff changeset
27 get {
313f708a50e9 improved log concept
cin
parents:
diff changeset
28 if (_current == null)
313f708a50e9 improved log concept
cin
parents:
diff changeset
29 _current = new TraceContext();
313f708a50e9 improved log concept
cin
parents:
diff changeset
30 return _current;
313f708a50e9 improved log concept
cin
parents:
diff changeset
31 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
32 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
33
313f708a50e9 improved log concept
cin
parents:
diff changeset
34 TraceContext(TraceContext context) {
313f708a50e9 improved log concept
cin
parents:
diff changeset
35 if (context == null)
313f708a50e9 improved log concept
cin
parents:
diff changeset
36 throw new ArgumentNullException("context");
313f708a50e9 improved log concept
cin
parents:
diff changeset
37
313f708a50e9 improved log concept
cin
parents:
diff changeset
38 m_currentOperation = context.CurrentOperation;
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
39 m_bound = context.CurrentOperation;
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
40 m_threadId = Thread.CurrentThread.ManagedThreadId;
313f708a50e9 improved log concept
cin
parents:
diff changeset
41 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
42
313f708a50e9 improved log concept
cin
parents:
diff changeset
43 TraceContext() {
313f708a50e9 improved log concept
cin
parents:
diff changeset
44 m_currentOperation = new LogicalOperation();
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
45 m_bound = m_currentOperation;
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
46 m_threadId = Thread.CurrentThread.ManagedThreadId;
313f708a50e9 improved log concept
cin
parents:
diff changeset
47 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
48
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
49 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
50 /// При необходимости копирует состояние контекста трассивровки в текущий поток.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
51 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
52 /// <param name="from">Исходный контекст трассировки, который передается.</param>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
53 /// <remarks>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
54 /// <para>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
55 /// Копирование происходит за счет создания нового контекста трассировки и заполнением его
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
56 /// состояния из переданного контекста. При этом копируется стек операций, однако в новом
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
57 /// контексте ранее начатые логические операции не могут быть завершены.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
58 /// </para>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
59 /// <para>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
60 /// Если передача состояния состоялась, то вызывается событие трассировки <see cref="TraceEventType.Transfer"/>.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
61 /// </para>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
62 /// </remarks>
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
63 public static void Transfer(TraceContext from) {
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
64 if (_current == from)
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
65 return;
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
66 if (from != null) {
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
67 var context = new TraceContext(from);
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
68 context.LogEvent(TraceEventType.Transfer, "[{0}]-->[{1}]",from.ThreadId, context.ThreadId);
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
69 _current = context;
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
70 } else {
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
71 _current = new TraceContext();
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
72 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
73 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
74
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
75 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
76 /// Создает постоянную копию текущего контекста, данную копию можно хранить и использовать для передачи через <see cref="Transfer(TraceContext)"/>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
77 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
78 /// <returns>Копия текущего контекста трассировки или <c>null</c> если таковой не был создан.</returns>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
79 public static TraceContext Snapshot() {
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
80 return _current == null ? null : new TraceContext(_current);
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
81 }
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
82
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
83 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
84 /// Выполняет переданное действие в указанном контексте трассировки, по окончании восстанавливает предыдущий контекст трассировки потока.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
85 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
86 /// <param name="action"></param>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
87 public void Invoke(Action action) {
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
88 if (action == null)
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
89 throw new ArgumentNullException("action");
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
90 var old = _current;
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
91 Transfer(this);
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
92 try {
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
93 action();
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
94 } finally {
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
95 _current = old;
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
96 }
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
97 }
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
98
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
99 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
100 /// Текущая логическая операция.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
101 /// </summary>
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
102 public LogicalOperation CurrentOperation {
313f708a50e9 improved log concept
cin
parents:
diff changeset
103 get {
313f708a50e9 improved log concept
cin
parents:
diff changeset
104 return m_currentOperation;
313f708a50e9 improved log concept
cin
parents:
diff changeset
105 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
106 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
107
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
108 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
109 /// Операция ниже которой нельзя опускаться в стеке логических операций, т.е. она не может быть завершена в текущем контексте.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
110 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
111 public LogicalOperation BoundOperation {
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
112 get {
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
113 return m_bound;
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
114 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
115 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
116
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
117 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
118 /// Поток, в котором создан контекст трассировки.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
119 /// </summary>
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
120 public int ThreadId {
313f708a50e9 improved log concept
cin
parents:
diff changeset
121 get {
313f708a50e9 improved log concept
cin
parents:
diff changeset
122 return m_threadId;
313f708a50e9 improved log concept
cin
parents:
diff changeset
123 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
124 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
125
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
126 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
127 /// Начинает безымянную логическую операцию.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
128 /// </summary>
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
129 public void StartLogicalOperation() {
313f708a50e9 improved log concept
cin
parents:
diff changeset
130 StartLogicalOperation(null);
313f708a50e9 improved log concept
cin
parents:
diff changeset
131 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
132
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
133 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
134 /// Начинает логическую операцию с указанным именем. Созданная операция будет добвалена в стек логических операций контекста, затем будет создано соответсвующее событие.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
135 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
136 /// <param name="name">Имя начинаемой операции.</param>
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
137 public void StartLogicalOperation(string name) {
313f708a50e9 improved log concept
cin
parents:
diff changeset
138 m_currentOperation = new LogicalOperation(name, m_currentOperation);
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
139 LogEvent(TraceEventType.OperationStarted, name);
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
140 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
141
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
142 /// <summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
143 /// Заканчивает логическую операцию начатую в текущем контексте. Операции, начатые в других контекстах не могут быть закончены в текущем контексте.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
144 /// </summary>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
145 /// <remarks>
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
146 /// При вызове данного метода создается событие журнала трассировки, либо о завершении операции, либо об ошибки, поскольку данная операция
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
147 /// начата в другом контексте.
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
148 /// </remarks>
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
149 public void EndLogicalOperation() {
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
150 if (m_bound == m_currentOperation) {
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
151 LogEvent(TraceEventType.Error, "Trying to end the operation which isn't belongs to current trace");
313f708a50e9 improved log concept
cin
parents:
diff changeset
152 } else {
313f708a50e9 improved log concept
cin
parents:
diff changeset
153 var op = m_currentOperation;
40
fe33f4e02ad5 improved tracing
cin
parents: 37
diff changeset
154 LogEvent(TraceEventType.OperationCompleted, "{0} {1} ms", op.Name, op.Duration);
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
155 m_currentOperation = m_currentOperation.Parent;
313f708a50e9 improved log concept
cin
parents:
diff changeset
156 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
157 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
158
313f708a50e9 improved log concept
cin
parents:
diff changeset
159 void LogEvent(TraceEventType type, string format, params object[] args) {
37
c2c043520724 working version of diagnostics logging
cin
parents: 36
diff changeset
160 LogChannel<TraceEvent>.Default.LogEvent(this, TraceEvent.Create(type, format, args));
36
313f708a50e9 improved log concept
cin
parents:
diff changeset
161 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
162 }
313f708a50e9 improved log concept
cin
parents:
diff changeset
163 }