-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
92 lines (68 loc) · 2.31 KB
/
index.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
var chalk = require('chalk')
, util = require('util')
, mkdirp = require('mkdirp')
, p = require('path')
, fs = require('fs')
var logger = {
out: function(stream) {
if(!stream || typeof stream.write != 'function') {
throw new TypeError('logger expects a writable stream instance')
}
var newline = this.config.newline === false ? '' : '\n'
, child = this.config.child ? '(' + this.config.child + ') ' : ''
var self = this
return function() {
var args = [].slice.call(arguments)
var method = args.shift()
if(process.argv.indexOf('-q') === -1 && process.argv.indexOf('-quiet') === -1) {
stream.write(child + method + util.format.apply(null, args) + newline);
}
return self.logger
}
},
prefix: function(method) {
if(this.config.prefix)
return this.config.prefix
if(this.config.noprefix)
return ''
var prefix = ''
prefix = this.config.nocolors ? method + ': ' : this.config.colors[method](method) + ': '
prefix = this.config.time ? '[' + new Date().toLocaleString() + '] ' + prefix : prefix
return prefix
},
init: function(child, config) {
if(typeof child == 'object') {
config = child
child = ''
}
config = config ? config : {}
config.child = child || config.child || ''
var stdout = config.stdout || process.stdout
, stderr = config.stderr || process.stderr
config.colors = config.colors || {
log: chalk.grey,
info: chalk.blue,
debug: chalk.cyan,
warn: chalk.yellow,
error: chalk.red
}
if(config.cwd) {
var log_path = p.join(config.cwd, 'logs')
if(!fs.existsSync(log_path)) {
mkdirp.sync(log_path)
}
stderr = fs.createWriteStream(p.join(log_path, 'err.log'))
stdout = fs.createWriteStream(p.join(log_path, 'out.log'))
}
this.config = config
this.logger = {}
var self = this
;['log', 'info', 'warn', 'error', 'debug'].forEach(function(method) {
var binder = method == 'log' || method == 'info' || method == 'debug' ? self.out(stdout) : self.out(stderr)
, prefixer = self.prefix(method)
self.logger[method] = prefixer.length === 0 ? binder.bind(self) : binder.bind(self, prefixer)
})
return this.logger
}
}
module.exports = logger.init.bind(logger)