-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
91 lines (80 loc) · 2.54 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
import { resolve } from 'path'
import { createLogger, format, transports } from 'winston'
import {
checkHeadersAccepts,
checkHeadersContentType,
extractReqInfo,
mkdirIfNotExists,
} from './utils'
const pkg = require('./package.json')
const { combine, timestamp, json, errors } = format
module.exports = function WinstonLog(moduleOptions = {}) {
const winstonOptions = {
logPath: './logs',
logName: `${process.env.NODE_ENV}.log`,
autoCreateLogPath: true,
useDefaultLogger: true,
skipRequestMiddlewareHandler: false,
skipErrorMiddlewareHandler: false,
...this.options.winstonLog,
...moduleOptions,
}
if (winstonOptions.autoCreateLogPath) {
mkdirIfNotExists(resolve(process.cwd(), winstonOptions.logPath))
}
let logger
if (winstonOptions.useDefaultLogger) {
logger = createLogger({
exitOnError: false,
format: combine(timestamp(), errors({ stack: true }), json()),
transports: [
new transports.File({
filename: resolve(winstonOptions.logPath, winstonOptions.logName),
...winstonOptions.transportOptions,
}),
],
...winstonOptions.loggerOptions,
})
} else {
logger = createLogger(winstonOptions.loggerOptions)
}
// Persist a reference to Winston logger instance.
// This is injected by `~/plugin.server.js` for use via Nuxt context objects
process.winstonLog = logger
// Add serverside-only plugin
this.addPlugin({
src: resolve(__dirname, 'plugin.server.js'),
fileName: 'plugin.server.js',
mode: 'server',
})
if (winstonOptions.skipRequestMiddlewareHandler !== true) {
this.nuxt.hook('render:setupMiddleware', (app) =>
app.use((req, res, next) => {
const reqInfo = extractReqInfo(req)
const isHtmlOrJson =
checkHeadersAccepts(reqInfo.headers, ['text/html', 'application/xhtml']) ||
checkHeadersContentType(reqInfo.headers, ['application/json'])
const isInternalNuxtRequest = reqInfo.url && reqInfo.url.includes('/_nuxt/')
if (isHtmlOrJson && !isInternalNuxtRequest) {
logger.info(`Accessed ${req.url}`, {
...reqInfo,
})
}
next()
})
)
}
if (winstonOptions.skipErrorMiddlewareHandler !== true) {
this.nuxt.hook('render:errorMiddleware', (app) =>
app.use((err, req, res, next) => {
const newError = new Error(err)
newError.stack = err.stack
logger.error(newError, {
...extractReqInfo(req),
})
next(err)
})
)
}
}
module.exports.meta = pkg