阅读量:2
在 Debian 系统上,Node.js 应用程序的日志格式可以通过多种方式自定义。以下是一些常见的方法:
方法一:使用 morgan 中间件(适用于 Express 应用)
如果你使用的是 Express 框架,可以使用 morgan 中间件来记录请求日志,并自定义日志格式。
-
安装
morgan:npm install morgan -
在你的 Express 应用中配置
morgan:const express = require('express'); const morgan = require('morgan'); const app = express(); // 自定义日志格式 morgan.token('customFormat', function (req, res) { return `${req.method} ${req.url} ${res.statusCode} ${req.ip} - ${req.userAgent}`; }); // 使用自定义格式 app.use(morgan('customFormat')); app.get('/', (req, res) => { res.send('Hello World!'); }); app.listen(3000, () => { console.log('Server is running on port 3000'); });
方法二:使用 winston 日志库
winston 是一个功能强大的日志库,可以用来记录各种级别的日志,并且支持自定义格式。
-
安装
winston:npm install winston -
在你的 Node.js 应用中配置
winston:const winston = require('winston'); // 创建一个自定义的 logger const logger = winston.createLogger({ level: 'info', format: winston.format.combine( winston.format.timestamp(), winston.format.printf(({ timestamp, level, message }) => { return `${timestamp} ${level}: ${message}`; }) ), transports: [ new winston.transports.Console(), new winston.transports.File({ filename: 'error.log', level: 'error' }), new winston.transports.File({ filename: 'combined.log' }) ] }); logger.info('Hello World!');
方法三:使用 pino 日志库
pino 是另一个高性能的日志库,支持自定义格式。
-
安装
pino:npm install pino -
在你的 Node.js 应用中配置
pino:const pino = require('pino'); // 创建一个自定义的 logger const logger = pino({ level: 'info', format: pino.format.combine( pino.format.timestamp(), pino.format.json() ) }); logger.info('Hello World!');
方法四:直接在代码中自定义日志输出
如果你不想使用第三方库,也可以直接在代码中自定义日志输出格式。
const http = require('http');
const server = http.createServer((req, res) => {
const logMessage = `${new Date().toISOString()} ${req.method} ${req.url} ${req.socket.remoteAddress} - ${req.headers['user-agent']}`;
console.log(logMessage);
res.end('Hello World!\n');
});
server.listen(3000, () => {
console.log('Server is running on port 3000');
});
通过这些方法,你可以在 Debian 系统上的 Node.js 应用程序中自定义日志格式。选择哪种方法取决于你的具体需求和偏好。
以上就是关于“Debian Node.js 日志格式如何自定义”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm