Skip to content

Commit 471c934

Browse files
committed
Add logger
1 parent 7f914e2 commit 471c934

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

gulpfile.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ const base = [
1414
'../setimmediate/setImmediate.js',
1515
'../paho/src/mqttws31.js',
1616
'src/webduino.js',
17+
'src/core/Logger.js',
1718
'src/core/EventEmitter.js',
1819
'src/core/util.js',
1920
'src/util/promisify.js',

index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ var webduino = require('./src/webduino');
33
require('setimmediate');
44

55
require('./src/core/EventEmitter')(webduino);
6+
require('./src/core/Logger')(webduino);
67
require('./src/core/util')(webduino);
78
require('./src/util/promisify')(webduino);
89
require('./src/core/Transport')(webduino);

src/core/Logger.js

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
+(function (factory) {
2+
if (typeof exports === 'undefined') {
3+
factory(webduino || {});
4+
} else {
5+
module.exports = factory;
6+
}
7+
}(function (scope) {
8+
'use strict';
9+
10+
var DEBUG_STR = 'DEBUG_WEBDUINOJS';
11+
12+
function Logger(option) {
13+
if (!option) {
14+
option = '*';
15+
}
16+
if (typeof option === 'string') {
17+
option = { key: option };
18+
}
19+
this._option = option;
20+
this._key = option.key;
21+
this._isShow = isShow.bind(this);
22+
init.call(this);
23+
}
24+
25+
function hasLocalStorage() {
26+
try {
27+
return !!localStorage;
28+
} catch (err) {
29+
return false;
30+
}
31+
}
32+
33+
function hasProcess() {
34+
try {
35+
return !!process;
36+
} catch (err) {
37+
return false;
38+
}
39+
}
40+
41+
function isShow() {
42+
var reg = new RegExp();
43+
var debugKeys = [];
44+
var debugStr;
45+
46+
if (hasLocalStorage()) {
47+
debugStr = localStorage.getItem(DEBUG_STR);
48+
}
49+
50+
if (hasProcess()) {
51+
debugStr = process.env[DEBUG_STR];
52+
}
53+
54+
if (debugStr) {
55+
debugKeys = debugStr.split(',').map(function (val) {
56+
return val.trim();
57+
});
58+
}
59+
60+
if (debugKeys.indexOf('*') !== -1 || debugKeys.indexOf(this._key) !== -1) {
61+
return true;
62+
}
63+
64+
return false;
65+
}
66+
67+
function init() {
68+
var self = this;
69+
var methodNames = ['log', 'info', 'warn', 'error'];
70+
var noop = function () { };
71+
var isCopy = this._isShow();
72+
73+
methodNames.forEach(function (name) {
74+
if (isCopy) {
75+
self[name] = Function.prototype.bind.call(console[name], console);
76+
} else {
77+
self[name] = noop;
78+
}
79+
});
80+
}
81+
82+
scope.Logger = Logger;
83+
}));

0 commit comments

Comments
 (0)