UNPKG

2.2 kBJavaScriptView Raw
1/*
2 * Copyright 2012 Amadeus s.a.s.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16require('colors'); // this modifies String.prototype
17
18var LEVEL_COLORS = [
19 ['red', 'bold'], 'yellow', 'green', null
20];
21//var LEVEL_NAMES = ['error', 'warn', 'info', 'debug'];
22
23var ConsoleLogger = function (output) {
24 this.output = output || process.stdout;
25};
26
27var buildId = function (loggersChain) {
28 var somethingBefore = false;
29 var leftParen = '['; // https://github.com/jshint/jshint/issues/1485
30 var res = [leftParen];
31 for (var i = 0, l = loggersChain.length; i < l; i++) {
32 var curLogger = loggersChain[i];
33 if (somethingBefore && (curLogger.name || curLogger.instanceId)) {
34 res.push('.');
35 }
36 if (curLogger.name) {
37 res.push(curLogger.name);
38 somethingBefore = true;
39 }
40 if (curLogger.instanceId) {
41 res.push('(');
42 res.push(curLogger.instanceId);
43 res.push(')');
44 somethingBefore = true;
45 }
46 }
47 res.push('] ');
48 return res.join('');
49};
50
51ConsoleLogger.prototype.onLog = function (evt) {
52 var color = LEVEL_COLORS[evt.level - 1];
53 var message = evt.message;
54 if (color) {
55 if (Array.isArray(color)) {
56 for (var i = 0, len = color.length; i < len; i++) {
57 message = message[color[i]];
58 }
59 } else {
60 message = message[color];
61 }
62 }
63 var id = buildId(evt.loggersChain).grey;
64 this.output.write(id + message + '\n');
65};
66
67ConsoleLogger.prototype.attach = function (logger) {
68 logger.on('log', this.onLog.bind(this));
69};
70
71module.exports = ConsoleLogger;