代码如下
- npm i dayjs winston morgan winston-daily-rotate-file
/**
* Created by prgma42 on 2022/9/16.
*/
const { createLogger, format, transports } = require('winston');
const fs = require('fs');
const dayjs = require('dayjs');
const path = require('path');
const _ = require('winston-daily-rotate-file');
// const dateUtil = require('./date_util');
const env = process.env.NODE_ENV || 'development';
const logDir = 'logs/'+ dayjs().format('YYYYMMDD');
const PROJECT_ROOT = path.join(__dirname, '..')
// Create the log directory if it does not exist
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
const filename = path.join(logDir, 'results.log');
const fileErrorRotate = new transports.DailyRotateFile({
filename: "combined-error-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxFiles: "14d",
level:'error',
format: format.combine(
format.printf(
info =>
`${info.timestamp} ${info.level} ${info.message}`
)
)
});
const fileRotate = new transports.DailyRotateFile({
filename: "combined-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxFiles: "14d",
format: format.combine(
format.printf(
info =>
`${info.timestamp} ${info.level} ${info.message}`
)
)
});
const logger = createLogger({
level: env === 'production' ? 'info' : 'debug',
format: format.combine(
format.label({ label: path.basename(process.mainModule.filename) }),
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' })
),
transports: [
new transports.Console({
format: format.combine(
format.colorize(),
format.printf(
info =>
`${info.timestamp} ${info.level} ${info.message}`
)
)
}),
fileRotate, fileErrorRotate
]
});
//module.exports = logger;
module.exports.debug = module.exports.log = function () {
logger.debug.apply(logger, formatLogArguments(arguments))
}
module.exports.info = function () {
logger.info.apply(logger, formatLogArguments(arguments))
}
module.exports.warn = function () {
logger.warn.apply(logger, formatLogArguments(arguments))
}
module.exports.error = function () {
logger.error.apply(logger, formatLogArguments(arguments))
}
//module.exports.stream = logger.stream
/**
* Attempts to add file and line number info to the given log arguments.
*/
function formatLogArguments (args) {
args = Array.prototype.slice.call(args)
const stackInfo = getStackInfo(1)
if (stackInfo) {
// get file path relative to project root
const calleeStr = '[' + stackInfo.relativePath + ':' + stackInfo.line + '] '
let content = '';
for(var i in args){
if (args[i] instanceof Object) {
content = content + ' ' + JSON.stringify(args[i]);
}else{
content = content + ' ' + args[i]
}
}
if (content && content.length>0) {
args[0] = calleeStr + ' ' + content
} else {
args.unshift(calleeStr)
}
}
return args
}
/**
* Parses and returns info about the call stack at the given index.
*/
function getStackInfo (stackIndex) {
// get call stack, and analyze it
// get all file, method, and line numbers
var stacklist = (new Error()).stack.split('\n').slice(3)
// stack trace format:
// http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
// do not remove the regex expresses to outside of this method (due to a BUG in node.js)
var stackReg = /at\s+(.*)\s+\((.*):(\d*):(\d*)\)/gi
var stackReg2 = /at\s+()(.*):(\d*):(\d*)/gi
var s = stacklist[stackIndex] || stacklist[0]
var sp = stackReg.exec(s) || stackReg2.exec(s)
if (sp && sp.length === 5) {
return {
method: sp[1],
relativePath: path.relative(PROJECT_ROOT, sp[2]),
line: sp[3],
pos: sp[4],
file: path.basename(sp[2]),
stack: stacklist.join('\n')
}
}
}
————————————————
版权声明:本文为CSDN博主「paj123456789」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/paj123456789/article/details/126903756
- 记录http访问信息
const morgan = require("morgan");
const morganMiddleware = morgan(
':remote-addr :method :url :status :res[content-length] - :response-time ms',
{
stream: {
// Configure Morgan to use our custom logger with the http severity
write: (message) => logger.info(message.trim()),
},
}
);
app.use(morganMiddleware);
- 设置定时日志转存和清理
const _ = require('winston-daily-rotate-file');
const fileErrorRotate = new transports.DailyRotateFile({
filename: "combined-error-%DATE%.log",
datePattern: "YYYY-MM-DD",
maxFiles: "14d",
level:'error',
format: format.combine(
format.printf(
info =>
`${info.timestamp} ${info.level} ${info.message}`
)
)
});