Files: d2b5693b01842e3376dae3c3cf5c579e03e490c4 / plugins / logging.js
2175 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 | if (conf.logging && conf.logging.level) { |
56 | level = LOG_LEVELS.indexOf(conf.logging.level) |
57 | } else { |
58 | level = DEFAULT_LEVEL |
59 | } |
60 | |
61 | if (level === -1) { |
62 | console.log('Warning, logging.level configured to an invalid value:', conf.logging.level) |
63 | console.log('Should be one of:', LOG_LEVELS.join(', ')) |
64 | level = DEFAULT_LEVEL |
65 | } |
66 | |
67 | var id = server.id |
68 | if (level >= LOG_LEVELS.indexOf('info')) |
69 | server.on('log:info', formatter(id, color.green('info'))) |
70 | if (level >= LOG_LEVELS.indexOf('notice')) |
71 | server.on('log:notice', formatter(id, color.blue('note'))) |
72 | if (level >= LOG_LEVELS.indexOf('warning')) |
73 | server.on('log:warning', formatter(id, color.yellow('warn'))) |
74 | if (level >= LOG_LEVELS.indexOf('error')) |
75 | server.on('log:error', formatter(id, color.red('err!'))) |
76 | } |
77 | |
78 | module.exports.init = module.exports |
79 |
Built with git-ssb-web