comparison src/implab/log/trace.js @ 24:f750c89976d3

Added trace tools, implab/log/trace!<channel-name>, <channel-name> is optional
author cin
date Thu, 07 Dec 2017 19:19:29 +0300
parents
children
comparison
equal deleted inserted replaced
23:1d72fddc319a 24:f750c89976d3
1 define(["../text/format"], function (format) {
2 'use strict';
3
4 var listeners = [];
5 var channels = {};
6
7 var Trace = function (name) {
8 this.name = name;
9 this._subscribers = [];
10 };
11
12 Trace.prototype.debug = function () {
13 if (Trace.level >= 4)
14 this.notify("debug", format.apply(null, arguments));
15 };
16
17 Trace.prototype.log = function () {
18 if (Trace.level >= 3)
19 this.notify("log", format.apply(null, arguments));
20 };
21
22 Trace.prototype.warn = function () {
23 if (Trace.level >= 2)
24 this.notify("warn", format.apply(null, arguments));
25
26 };
27
28 Trace.prototype.error = function () {
29 if (Trace.level >= 1)
30 this.notify("error", format.apply(null, arguments));
31 };
32
33 Trace.prototype.notify = function (name, msg) {
34 var me = this;
35 me._subscribers.forEach(function (cb) {
36 cb(me, name, msg);
37 });
38 };
39
40 Trace.prototype.subscribe = function (cb) {
41 this._subscribers.push(cb);
42 };
43
44 Trace.prototype.toString = function () {
45 return this.name;
46 };
47
48 Trace.createChannel = function (type, name, cb) {
49 var chId = name;
50 if (channels[chId])
51 return channels[chId];
52
53 var channel = new type(chId);
54 channels[chId] = channel;
55
56 Trace._onNewChannel(chId, channel);
57 cb(channel);
58 };
59
60 Trace._onNewChannel = function (chId, ch) {
61 listeners.forEach(function (listener) {
62 listener(chId, ch);
63 });
64 };
65
66 Trace.on = function (filter, cb) {
67 if (arguments.length == 1) {
68 cb = filter;
69 filter = undefined;
70 }
71 var d, test;
72 if (filter instanceof RegExp) {
73 test = function (chId) {
74 return filter.test(chId);
75 };
76 } else if (filter instanceof Function) {
77 test = filter;
78 } else if (filter) {
79 test = function (chId) {
80 return chId == filter;
81 };
82 }
83
84 if (test) {
85 d = function(chId, ch) {
86 if(test(chId))
87 ch.subscribe(cb);
88 };
89 } else {
90 d = function(chId, ch) {
91 ch.subscribe(cb);
92 };
93 }
94 listeners.push(d);
95
96 for(var chId in channels)
97 d(chId,channels[chId]);
98 };
99
100 Trace.load = function (id, require, cb) {
101 if (id)
102 Trace.createChannel(Trace, id, cb);
103 else if (require.module && require.module.mid)
104 Trace.createChannel(Trace, require.module.mid, cb);
105 else
106 require(['module'], function (module) {
107 Trace.createChannel(Trace, module && module.id, cb);
108 });
109 };
110
111 Trace.dynamic = true;
112
113 Trace.level = 4;
114
115 return Trace;
116 });