在Ubuntu上使用Node.js时,日志格式化是一个重要的环节,它可以帮助你更好地理解和调试应用程序。以下是一些常用的日志格式化技巧:
morgan中间件morgan是一个流行的HTTP请求日志中间件,可以轻松地格式化日志。
morgannpm install morgan
morgan在你的Node.js应用中引入并使用morgan:
const express = require('express');
const morgan = require('morgan');
const app = express();
// 使用默认的combined格式
app.use(morgan('combined'));
// 或者自定义格式
app.use(morgan(':method :url :status :res[content-length] - :response-time ms'));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
winston进行日志记录winston是一个功能强大的日志库,支持多种传输方式和格式化选项。
winstonnpm install winston
winston创建一个日志记录器并配置不同的传输和格式:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
logger.info('Hello World!');
你可以根据需要自定义日志格式。例如,使用winston的自定义格式:
const winston = require('winston');
const customFormat = winston.format.printf(({ timestamp, level, message }) => {
return `${timestamp} ${level}: ${message}`;
});
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
customFormat,
winston.format.timestamp()
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'custom.log' })
]
});
logger.info('This is a custom formatted log message');
morgan和winston结合你可以将morgan和winston结合起来使用,以便更好地管理和格式化日志:
const express = require('express');
const morgan = require('morgan');
const winston = require('winston');
const app = express();
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' })
]
});
app.use(morgan('combined', { stream: { write: message => logger.info(message.trim()) } }));
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(3000, () => {
logger.info('Server is running on port 3000');
});
通过这些技巧,你可以在Ubuntu上使用Node.js时更好地格式化和记录日志,从而提高应用程序的可维护性和调试效率。