nuxt3 winston 收集自定义日志
// nuxt.config.jsimport { resolve } from 'path'import moment from 'moment'import { format, transports } from 'winston'
// nuxt.config.jsconst { combine, timestamp, label, printf } = formatconst myFormat = printf(({ level, message, label, timestamp }) => { return `${timestamp} [${label}] ${level}: ${message}`})
// nuxt.config.js// 日志存放路径const winstonErrorLogPath = resolve('/var/applogs', './', `error_${moment().format('YYYY-MM-DD')}.log`)const winstonInfoLogPath = resolve('/var/applogs', './', `info_${moment().format('YYYY-MM-DD')}.log`)const jsLogPath = resolve('/var/applogs', './', `js_${moment().format('YYYY-MM-DD')}.log`)const winstonLog = process.env.NODE_ENV == 'production' ? { useDefaultLogger: false, loggerOptions: { transports: [ new transports.File({ format: myFormat, level: 'error', filename: winstonErrorLogPath, maxsize: 5 * 1024 * 1024, json: false, }), new transports.File({ format: myFormat, level: 'info', filename: winstonInfoLogPath, maxsize: 5 * 1024 * 1024, // 这个是限制日志文件的大小 json: false, }), new transports.File({ format: myFormat, level: 'silly', filename: jsLogPath, maxsize: 5 * 1024 * 1024, json: false, }), ], }, } : {}
// nuxt.config.jsexport default { modules: ['nuxt-winston-log'], winstonLog,}
// plugins/interceptor.js export default function ({ store, route, redirect, $axios, $winstonLog }) { $axios.onResponse(response => { // 打印日志 先判断是否有$winstonLog,因为该变量只在服务端存在 if ($winstonLog) { $winstonLog.info(`[${response.status}] ${response.request.path}`) } } $axios.onError(error => { // 打印日志 先判断是否有$winstonLog,因为该变量只在服务端存在 if ($winstonLog) { $winstonLog.error(`[${error.status}] | ${error.request.path} | ${error.message}`) $winstonLog.error(error.response && error.response.data) } } }