在Debian上設置Node.js應用程序的日志級別,通常取決于你使用的日志庫或框架。以下是一些常見的Node.js日志庫及其設置方法:
console.log
如果你只是使用 console.log
進行簡單的日志記錄,那么日志級別是由你直接在代碼中設置的。例如:
console.log('This is an info message');
console.error('This is an error message');
winston
winston
是一個流行的日志庫,可以通過配置來設置不同的日志級別。以下是一個簡單的配置示例:
const winston = require('winston');
const logger = winston.createLogger({
level: 'info', // 設置默認日志級別
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
logger.info('This is an info message');
logger.error('This is an error message');
pino
pino
是另一個高性能的日志庫,可以通過配置來設置日志級別。以下是一個簡單的配置示例:
const pino = require('pino');
const logger = pino({
level: 'info' // 設置默認日志級別
});
logger.info('This is an info message');
logger.error('This is an error message');
morgan
morgan
是一個HTTP請求日志中間件,通常用于Express應用程序。它本身沒有日志級別設置,但你可以結合其他日志庫來記錄請求日志。例如:
const express = require('express');
const morgan = require('morgan');
const winston = require('winston');
const app = express();
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'access.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');
});
你也可以通過環境變量來動態設置日志級別。例如,使用 winston
:
const winston = require('winston');
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info', // 從環境變量中讀取日志級別
format: winston.format.json(),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' })
]
});
logger.info('This is an info message');
logger.error('This is an error message');
在Debian上運行Node.js應用程序時,可以通過設置環境變量來控制日志級別:
LOG_LEVEL=debug node app.js
通過這些方法,你可以在Debian上靈活地設置Node.js應用程序的日志級別。