-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
186 lines (166 loc) · 4.48 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
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
const colors = require('colors')
const fs = require('fs')
const mkdirp = require('mkdirp')
const moment = require('moment')
const path = require('path')
const winston = require('winston')
const { calculateTime, handleDatum, handleDefault, levels, loggerError } = require('./utils/common')
require('winston-daily-rotate-file')
const localPath = path.join(path.dirname(__dirname), '../logs')
const servePath = `/data/logs/`
const development = process.env.NODE_ENV === 'development'
const production = process.env.NODE_ENV === 'production'
const situation = !(development || production)
const root = !situation ? servePath : localPath
/**
* baseLogger
* @param {Object} config attribute
*/
function baseLogger (config = {}) {
const defaults = {
appName: 'app',
automate: true,
dailyRotateFile: {
datePattern: 'YYYY-MM-DD',
maxFiles: '30d',
maxSize: '100m',
},
fileName: 'app',
format: winston.format.json(),
recordBody: false,
root,
}
const options = Object.assign({}, defaults, config)
let logsPath = path.join(options.root, options.appName)
// log output directory
if (!fs.existsSync(logsPath)) {
try {
mkdirp.sync(logsPath)
} catch (err) {
console.log(colors.red(`Create '${servePath}' directory is failure!`))
logsPath = path.join(localPath, options.appName)
mkdirp.sync(logsPath)
}
}
const createLogger = data => winston.createLogger(data)
const timestamp = () => moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
const { datePattern, maxFiles, maxSize } = options.dailyRotateFile
const openMeans = {}
levels.forEach(data => {
const logger = createLogger({
level: data.type,
format: options.format,
transports: [
new (winston.transports.DailyRotateFile)({
datePattern,
filename: path.join(logsPath, `${options.fileName}.${data.type}-%DATE%.log`),
maxFiles,
maxSize,
}),
],
})
// If it is a local environment
// The log will be displayed in the terminal
if (situation) {
logger.add(new winston.transports.Console({
format: winston.format.combine(
winston.format.printf(info => {
const { message } = info
const news = colors[data.color](JSON.stringify(message))
const response = `[${timestamp()}][${data.type}] ${data.icon} \n${news}`
return response
}),
),
}))
}
openMeans[data.type] = logger
})
/**
* handleLogger
* @param {Object} data
*/
function handleLogger ({ level, datum } = {}) {
const data = Object.assign({}, datum, {
timestamp: timestamp(),
})
openMeans[level.type][level.type](data)
}
/**
* handleDaily
*/
function handleDaily () {
const result = {}
levels.forEach(data => {
const content = {
error: null,
message: null,
}
result[data.type] = (...args) => {
if (args.length > 0) {
const temp = args[0]
if (data.type === 'error') {
content.error = temp
content.message = args[1] || null
} else {
content.message = temp
}
}
const datum = handleDefault({
err: content.error,
message: content.message,
})
handleLogger({
level: data,
datum,
})
}
})
return result
}
/**
* log
* return middleware function
* @param {Object} ctx
* @param {Function} next
*/
async function log (ctx, next) {
const start = Date.now()
const regex = /\.(?:js|css|png|ico|bmp|jpg|jpeg|gif|webp|jpe)/ig
const redirect = /\/redirect?./ig
ctx.logger = handleDaily({ ctx })
if (options.automate) {
ctx.res.on('finish', () => {
if (regex.test(ctx.req.url)) {
return false
}
if (redirect.test(ctx.req.url)) {
return false
}
handleLogger({
level: { type: 'verbose', icon: '✈' },
datum: handleDatum({
ctx,
recordBody: options.recordBody,
responseTime: calculateTime(start),
verbose: true,
}),
})
})
}
return next().catch(err => {
handleLogger({
level: { type: 'error', icon: '✖' },
datum: handleDatum({
ctx,
err,
responseTime: calculateTime(start),
}),
})
})
}
return log
}
module.exports = {
baseLogger,
loggerError,
}