在 Ubuntu 上清理 Node.js 應用程序的日志文件,可以通過以下幾種方法實現:
找到日志文件的位置:
app.log
、access.log
等。刪除日志文件:
rm
命令刪除日志文件。例如:cd /path/to/logs
rm app.log
日志輪轉工具可以幫助你自動管理日志文件的大小和數量,防止日志文件過大。
安裝 logrotate
:
sudo apt-get update
sudo apt-get install logrotate
配置 logrotate
:
logrotate
配置文件,例如 /etc/logrotate.d/nodejs
。/path/to/logs/*.log {
daily
missingok
rotate 7
compress
notifempty
create 0640 root adm
}
daily
:每天輪轉一次日志。missingok
:如果日志文件不存在,不會報錯。rotate 7
:保留最近 7 天的日志文件。compress
:壓縮舊的日志文件。notifempty
:如果日志文件為空,不進行輪轉。create 0640 root adm
:創建新的日志文件,權限為 0640
,屬主為 root
,屬組為 adm
。測試配置:
sudo logrotate -f /etc/logrotate.d/nodejs
如果你使用的是 Node.js 的日志庫(如 winston
、morgan
等),可以在代碼中配置日志輪轉。
安裝 winston
和 winston-daily-rotate-file
:
npm install winston winston-daily-rotate-file
配置 winston
:
const winston = require('winston');
const { DailyRotateFile } = require('winston-daily-rotate-file');
const transport = new DailyRotateFile({
filename: 'application-%DATE%.log',
datePattern: 'YYYY-MM-DD-HH',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
});
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
transport
]
});
logger.info('Hello, world!');
通過以上方法,你可以有效地管理和清理 Ubuntu 上 Node.js 應用程序的日志文件。