forked from quirkey/node-logger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.js
219 lines (196 loc) · 6.94 KB
/
logger.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// name: simple-logger
// version: 0.0.1
// http://github.com/quirkey/node-logger
// forked by Garrett Morris
/*
Copyright (c) 2010 Aaron Quint, 2019 Garrett Morris
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
var isDebug = false;
const debug = m => isDebug && process.stdout.write(m+"\n")
const colors = require('colors/safe');
const util = require('util');
function isFormattableString( args ) {
debug(args);
if(!args.length) return false;
if(typeof args[0] !== 'string') return false;
if( args[0].includes('%s') || args[0].includes('%d') || args[0].includes('%i') || args[0].includes('%f') || args[0].includes('%j') || args[0].includes('%o') || args[0].includes('%O') ) {
return true;
}
return false;
}
//pad string to specified length. used to keep messages aligned nicely
const pad = (str,len) => str + new Array(len - str.length).fill(' ').join('');
const dateFormatter = d=> d.toLocaleString('en-US');
const defaults = {
log_level:'debug',
transports:['console'],
formatDate:dateFormatter,
debug:false
};
class Logger {
constructor(_options={}) {
if(typeof _options !== 'object'){
throw new Error('configuration error: options must be an object');
}
const options = {...defaults,..._options};
isDebug = options.debug;
this.setLevel(options.log_level);
this.setTransports(options.transports);
this.setDateFormat(options.formatDate||dateFormatter);
}
getIndex(k){
if(!this.hasOwnProperty('_keys')) {
this._keys = Object.keys(this.levels).reverse();
}
return this._keys.indexOf(k)
}
setLevel(new_level) {
if(!this.levels.hasOwnProperty(new_level)){
throw new Error('invalid log_level ('+new_level+') supplied.');
}
this.log_level = new_level;
this.log_level_index = this.getIndex(this.log_level);
debug(this.log_level);
debug(this.log_level_index);
}
setTransports(transports) {
if(!Array.isArray(transports)){
throw new Error('transports must be an array.');
}
this.transports = transports.map(transport=>{
if(typeof transport==='string') {
try {
var Transport = require('./transports/'+transport);
return new Transport;
}
catch(err){
debug(err);
throw new Error('Unknown built-in transport named `'+transport+'`. ');
}
}
if(typeof transport === 'object') {
if(transport.write && typeof transport.write==='function'){
return transport;
}
else if(transport.writeCustom && typeof transport.writeCustom==='function'){
return transport;
}else{
throw new Error('invalid transport provided ('+transport.name+'). Transports must be an object with a function called `write` or `writeCustom` ');
}
}
})
}
isError(level) {
return ['emerg','alert','crit','error'].indexOf(level) !== -1;//tells if a log level is one of the 4 error levels
}
setDateFormat(fn) {
debug(fn);
this.formatDate = fn;
}
write(text,level,date,args) {
this.transports.forEach(transport=>transport.hasOwnProperty('writeCustom')? transport.writeCustom(args,level,date,this):transport.write(text,level,this));
}
format(level, date, message) {
debug(level);
debug(this.levels[level]);
return [ colors[ this.levels[level] ](pad(level,7)), ' [', this.formatDate(date), '] ', message ].join('');
}
log(...args) {
debug(Array.isArray(args));
if(!args.length){
return;
}
const log_level = this.levels.hasOwnProperty(args[0]) ? args.shift() : 'info';
const index = this.getIndex(log_level);
let message = '';
debug(log_level);
debug(index);
if (index >= this.log_level_index) {
if( isFormattableString(args) ) {
debug('logger: formatting message');
message = util.format(...args);
}else{
// join the arguments into a loggable string
args.forEach(arg=> {
if (typeof arg === 'string') {
message += ' ' + arg;
} else {
message += ' ' + util.inspect(arg, false, null);
}
});
}
const date = new Date();
message = this.format(log_level,date, message);
this.write(message + "\n",log_level,date,args);
return message;
}else{
debug("miss\n")
}
return false;
}
}
Logger.prototype.levels = {
emerg:'red',
alert: 'red',
crit: 'red',
error: 'red',
warning:'yellow',
notice:'cyan',
info:'cyan',
debug:'cyan'
};
function createLogger(options) {
const logger = new Logger(options);
const log = (...args) => {
logger.log('info',...args);
};
Object.keys(logger.levels).forEach(level=>log[level] = (...args) => logger.log(level,...args));
log.logger = logger;
return log;
}
var old = {};
var isWrapped = false;
function wrapConsole( logger ) {
if(!isWrapped) {
var c = global.console;
old.log = c.log;
old.warn = c.warn;
old.error = c.error;
old.info = c.info;
c.log = logger.info;
c.warn = logger.warning;
c.error = logger.error;
c.info = logger.info;
isWrapped = true;
}
}
function unwrapConsole() {
if(isWrapped) {
var c = global.console;
c.log = old.log;
c.warn = old.warn;
c.error = old.error;
c.info = old.info;
old = {};
isWrapped = false;
}
}
module.exports = {createLogger,Logger,wrapConsole,unwrapConsole,isFormattableString};