在Ubuntu上自定义Node.js日志格式,你可以使用以下方法:
morgan
中间件:morgan
是一个流行的HTTP请求日志中间件,可以帮助你轻松地记录和自定义日志格式。首先,你需要安装morgan
:
npm install morgan
然后,在你的Node.js应用程序中引入并配置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.responseTime}ms`;
});
app.use(morgan('customFormat'));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
在这个例子中,我们创建了一个名为customFormat
的自定义日志格式,其中包括请求方法、URL、状态码和响应时间。然后,我们将此自定义格式传递给morgan
中间件。
winston
日志库:winston
是一个功能强大的日志库,可以帮助你轻松地记录和自定义日志格式。首先,你需要安装winston
:
npm install winston
然后,在你的Node.js应用程序中引入并配置winston
:
const express = require('express');
const winston = require('winston');
const app = express();
// 创建一个自定义的winston日志格式
const customFormat = winston.format.combine(
winston.format.colorize(),
winston.format.printf(({ timestamp, level, message }) => {
return `[${timestamp}] ${level}: ${message}`;
})
);
// 创建一个winston日志记录器实例
const logger = winston.createLogger({
level: 'info',
format: customFormat,
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'app.log' }),
],
});
app.use((req, res, next) => {
logger.info(`${req.method} ${req.url}`);
next();
});
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
logger.info('Server is running on port 3000');
});
在这个例子中,我们创建了一个名为customFormat
的自定义日志格式,其中包括时间戳、日志级别和消息。然后,我们将此自定义格式传递给winston
日志记录器实例。
这两种方法都可以帮助你在Ubuntu上自定义Node.js日志格式。你可以根据自己的需求选择合适的方法。