Files: b3923852a5471785a61c33094414b62fa845b7b5 / plugins / logging.js
2193 bytesRaw
1 | var color = require('bash-color') |
2 | |
3 | // logging plugin |
4 | // subscribes to 'log:*' events |
5 | // and emits using lovely colors |
6 | |
7 | var LOG_LEVELS = [ |
8 | 'error', |
9 | 'warning', |
10 | 'notice', |
11 | 'info' |
12 | ] |
13 | var DEFAULT_LEVEL = LOG_LEVELS.indexOf('notice') |
14 | |
15 | function indent (o) { |
16 | return o.split('\n').map(function (e) { |
17 | return ' ' + e |
18 | }).join('\n') |
19 | } |
20 | |
21 | function isString(s) { |
22 | return 'string' === s |
23 | } |
24 | |
25 | function formatter(id, level) { |
26 | var b = id.substring(0, 4) |
27 | return function (ary) { |
28 | var plug = ary[0].substring(0, 4).toUpperCase() |
29 | var id = ary[1] |
30 | var verb = ary[2] |
31 | var data = ary.length > 4 ? ary.slice(3) : ary[3] |
32 | var _data = (isString(data) ? data : JSON.stringify(data)) || '' |
33 | |
34 | var pre = [plug, id, color.cyan(verb)].join(' ') |
35 | var length = (5 + pre.length + 1 + _data.length) |
36 | var lines = isString(data) && data.split('\n').length > 1 |
37 | |
38 | var c = process.stdout.columns |
39 | if((process.stdout.columns > length) && !lines) |
40 | console.log([level, b, pre, _data].join(' ')) |
41 | else { |
42 | console.log([level, b, pre].join(' ')) |
43 | if(lines) |
44 | console.log(indent(data)) |
45 | else if(data && data.stack) |
46 | console.log(indent(data.stack)) |
47 | else if(data) { |
48 | console.log(indent(JSON.stringify(data, null, 2))) |
49 | } |
50 | } |
51 | } |
52 | } |
53 | |
54 | module.exports = function logging (server, conf) { |
55 | var level = conf.logging && conf.logging.level && LOG_LEVELS.indexOf(conf.logging.level) || DEFAULT_LEVEL |
56 | if (level === -1) { |
57 | console.log('Warning, logging.level configured to an invalid value:', conf.logging.level) |
58 | console.log('Should be one of:', LOG_LEVELS.join(', ')) |
59 | level = DEFAULT_LEVEL |
60 | } |
61 | console.log('Log level:', LOG_LEVELS[level]) |
62 | |
63 | var id = server.id |
64 | if (level >= LOG_LEVELS.indexOf('info')) |
65 | server.on('log:info', formatter(id, color.green('info'))) |
66 | if (level >= LOG_LEVELS.indexOf('notice')) |
67 | server.on('log:notice', formatter(id, color.blue('note'))) |
68 | if (level >= LOG_LEVELS.indexOf('warning')) |
69 | server.on('log:warning', formatter(id, color.yellow('warn'))) |
70 | if (level >= LOG_LEVELS.indexOf('error')) |
71 | server.on('log:error', formatter(id, color.red('err!'))) |
72 | } |
73 | |
74 | module.exports.init = module.exports |
75 |
Built with git-ssb-web