OLD | NEW |
| (Empty) |
1 // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 library tracer; | |
6 | |
7 import 'dart:async'; | |
8 | |
9 import 'package:logging/logging.dart'; | |
10 import 'package:observe/observe.dart'; | |
11 | |
12 _deepCopy(src) { | |
13 if (src is Map) { | |
14 var dest = {}; | |
15 src.forEach((key, val) { | |
16 dest[key] = _deepCopy(val); | |
17 }); | |
18 return dest; | |
19 } else if (src is List) { | |
20 var dest = []; | |
21 src.forEach((val) { | |
22 dest.add(_deepCopy(val)); | |
23 }); | |
24 return dest; | |
25 } else { | |
26 return src; | |
27 } | |
28 } | |
29 | |
30 class TraceEvent { | |
31 TraceEvent.msg(this._time, this.message, Map originalMap) { | |
32 map = _deepCopy(originalMap); | |
33 } | |
34 | |
35 String get timeStamp => "T+${_time}us"; | |
36 | |
37 String toString() { | |
38 return "[${timeStamp}] ${message}"; | |
39 } | |
40 | |
41 int _time; | |
42 String message; | |
43 Map map; | |
44 } | |
45 | |
46 class Tracer extends Observable { | |
47 // The current global tracer. | |
48 static Tracer get current => _current; | |
49 | |
50 static Tracer _current; | |
51 | |
52 static void start() { | |
53 if (_current == null) { | |
54 _current = new Tracer(); | |
55 } | |
56 } | |
57 static void stop() { | |
58 if (_current != null) { | |
59 _current.cancel(); | |
60 _current = null; | |
61 } | |
62 } | |
63 | |
64 // The tracer subscribes to all logging events. | |
65 StreamSubscription loggerSub = null; | |
66 | |
67 // The start time for the current request. | |
68 Stopwatch _time; | |
69 | |
70 // A list of all tracing events for thre current request. | |
71 ObservableList<TraceEvent> events = new ObservableList<TraceEvent>(); | |
72 | |
73 Tracer() { | |
74 _time = new Stopwatch(); | |
75 _time.start(); | |
76 loggerSub = Logger.root.onRecord.listen((LogRecord rec) { | |
77 // Echo all log messages to the trace. | |
78 trace('${rec.level.name}: ${rec.message}'); | |
79 }); | |
80 reset(); | |
81 } | |
82 | |
83 void cancel() { | |
84 loggerSub.cancel(); | |
85 } | |
86 | |
87 void reset() { | |
88 _time.reset(); | |
89 events.clear(); | |
90 } | |
91 | |
92 TraceEvent trace(String message, {Map map: null}) { | |
93 var event = new TraceEvent.msg(_time.elapsedMicroseconds, message, map); | |
94 events.add(event); | |
95 return event; | |
96 } | |
97 } | |
OLD | NEW |