nodejs写入日志文件
不同日志的结果写入项目目录下的./logs/类型.log
安装项目模块
安装模块
js
npm install winston
logger.js
内容如下
情况一:项目启动时创建日志文件后续不会自动创建文件(不推荐)
这个相当于项目初始化创建日志文件,后续不会自动创建了,例如我在2024年11月07日启动了项目,创建了日志文件error-2024-11-07.log和info-2024-11-07.log,当我在2024-11-08日访问项目时请求到了接口,但是日志还是写入上面两个文件内,并不会根据日期自动创建,因此这种方式不推荐
项目根目录下新建logger.js文件,内容如下:
js
const winston = require('winston');
const fs = require('fs');
const path = require('path');
// 创建一个日志目录,如果不存在的话
const logDir = path.join(__dirname, 'logs');
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
const logger = winston.createLogger({
// 定义日志级别
levels: winston.config.npm.levels,
// 自定义日志格式
format: winston.format.combine(
winston.format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss'
}),
winston.format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
),
// 定义不同的日志处理器(仅支持info,error,warn,http,verbose,debug,silly)
transports: [
// 日志处理器info
new winston.transports.File({
// 写入到./logs/info.log
filename: path.join(logDir, 'info.log'),
level: 'info'
}),
// 日志处理器error
new winston.transports.File({
// 写入到./logs/error.log
filename: path.join(logDir, 'error.log'),
level: 'error'
}),
// 日志处理器warn
new winston.transports.File({
// 写入到./logs/warn.log
filename: path.join(logDir, 'warn.log'),
level: 'warn'
}),
// 日志处理器http
new winston.transports.File({
// 写入到./logs/http.log
filename: path.join(logDir, 'http.log'),
level: 'http'
}),
// 日志处理器verbose
new winston.transports.File({
// 写入到./logs/verbose.log
filename: path.join(logDir, 'verbose.log'),
level: 'verbose'
}),
// 日志处理器debug
new winston.transports.File({
// 写入到./logs/debug.log
filename: path.join(logDir, 'debug.log'),
level: 'debug'
}),
// 日志处理器silly
new winston.transports.File({
// 写入到./logs/silly.log
filename: path.join(logDir, 'silly.log'),
level: 'silly'
}),
// 控制台输出
new winston.transports.Console({
// 控制台输出日志级别为 debug 或以上级别,写入到控制台
level: 'debug',
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
})
],
exitOnError: false // 禁止在日志写入失败时退出程序
});
// 异常处理
process.on('unhandledRejection', (ex) => {
throw ex;
});
// 捕获未捕获的异常
process.on('uncaughtException', (ex) => {
logger.error('Uncaught Exception:', ex);
process.exit(1);
});
module.exports = logger;
情况二:要根据当前访问项目的日期自动创建日志文件(推荐)
安装一个新模块
js
npm install winston-daily-rotate-file
项目根目录下新建logger.js文件,内容如下:
js
const winston = require('winston');
const fs = require('fs');
require('winston-daily-rotate-file');
const path = require('path');
// 获取当前目录的上一级目录路径
const parentDir = path.dirname(__dirname);
// 构建到上一级目录中的 'image' 文件夹的路径
const logDir = path.join(parentDir, 'logs');
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir);
}
function getCurrentFormattedDate() {
const now = new Date();
const year = now.getFullYear();
const month = (now.getMonth() + 1).toString().padStart(2, '0');
const day = now.getDate().toString().padStart(2, '0');
return `${year}-${month}-${day}`;
}
const logger = winston.createLogger({
levels: winston.config.npm.levels,
format: winston.format.combine(
winston.format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss'
}),
winston.format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`)
),
transports: [
new winston.transports.DailyRotateFile({
filename: path.join(logDir, `info-%DATE%.log`),
level: 'info',
datePattern: 'YYYY-MM-DD-HH',
}),
new winston.transports.DailyRotateFile({
filename: path.join(logDir, `error-%DATE%.log`),
level: 'error',
datePattern: 'YYYY-MM-DD-HH',
}),
new winston.transports.Console({
level: 'debug',
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
})
],
exitOnError: false
});
process.on('unhandledRejection', (ex) => {
throw ex;
});
process.on('uncaughtException', (ex) => {
logger.error('Uncaught Exception:', ex);
process.exit(1);
});
module.exports = logger;
使用日志打印文件
在需要使用打印的地方只需要如下导入使用即可
js
const logger = require('./logger');
// (仅支持info,error,warn,http,verbose,debug,silly)
logger.info('This is a successful operation.');
logger.error('This is an error operation.');
logger.warn('This is a warning operation.');
logger.http('This is a http operation.')
logger.verbose('This is a verbose operation.')
logger.debug('This is a debug operation.')
logger.silly('This is a silly operation.')
运行项目
不同的级别的日志打印的内容分别如下(一般使用info.log【打印成功和错误和警告级别】和error.log【仅仅打印错误级别】):
控制台级别输出打印如下(在控制台打印的结果):
js
info: This is a successful operation. {"timestamp":"2024-10-25 11:29:51"}
error: This is an error operation. {"timestamp":"2024-10-25 11:29:51"}
warn: This is a warning operation. {"timestamp":"2024-10-25 11:29:51"}
http: This is a http operation. {"timestamp":"2024-10-25 11:29:51"}
verbose: This is a verbose operation. {"timestamp":"2024-10-25 11:29:51"}
debug: This is a debug operation. {"timestamp":"2024-10-25 11:29:51"}
logs/info.log
内容如下:
js
2024-10-25 11:29:51 info: This is a successful operation.
2024-10-25 11:29:51 error: This is an error operation.
2024-10-25 11:29:51 warn: This is a warning operation.
logs/error.log
内容如下:
js
2024-10-25 11:29:51 error: This is an error operation.
logs/warn.log
内容如下:
js
2024-10-25 11:29:51 error: This is an error operation.
2024-10-25 11:29:51 warn: This is a warning operation.
logs/http.log
内容如下:
js
2024-10-25 11:29:51 info: This is a successful operation.
2024-10-25 11:29:51 error: This is an error operation.
2024-10-25 11:29:51 warn: This is a warning operation.
2024-10-25 11:29:51 http: This is a http operation.
logs/verbose.log
内容如下:
js
2024-10-25 11:29:51 info: This is a successful operation.
2024-10-25 11:29:51 error: This is an error operation.
2024-10-25 11:29:51 warn: This is a warning operation.
2024-10-25 11:29:51 http: This is a http operation.
2024-10-25 11:29:51 verbose: This is a verbose operation.
logs/debug.log
内容如下:
js
2024-10-25 11:29:51 info: This is a successful operation.
2024-10-25 11:29:51 error: This is an error operation.
2024-10-25 11:29:51 warn: This is a warning operation.
2024-10-25 11:29:51 http: This is a http operation.
2024-10-25 11:29:51 verbose: This is a verbose operation.
2024-10-25 11:29:51 debug: This is a debug operation.
logs/silly.log
内容如下:
js
2024-10-25 11:29:51 info: This is a successful operation.
2024-10-25 11:29:51 error: This is an error operation.
2024-10-25 11:29:51 warn: This is a warning operation.
2024-10-25 11:29:51 http: This is a http operation.
2024-10-25 11:29:51 verbose: This is a verbose operation.
2024-10-25 11:29:51 debug: This is a debug operation.
2024-10-25 11:29:51 silly: This is a silly operation.