阅读量:3
Ubuntu Node.js日志可读性提升实践
一 统一日志格式与级别
- 使用成熟的日志库,统一控制台与文件的输出格式,包含关键信息:时间戳、日志级别、模块/标签、消息、请求ID等。
- 按环境设置日志级别:开发环境用debug,生产环境用info/warn,错误单独落盘。
- 控制台输出可读性强(彩色、简洁),文件输出结构化(便于检索与分析)。
示例 Winston 统一配置(开发/生产可切换 transports 与 level):
// logger.js
const winston = require('winston');
const isProd = process.env.NODE_ENV === 'production';
const logger = winston.createLogger({
level: isProd ? 'info' : 'debug',
format: winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
winston.format.errors({ stack: true }), // 错误堆栈
winston.format.metadata({ fillExcept: ['message', 'level', 'timestamp', 'label'] }),
winston.format.printf(({ timestamp, level, message, label, metadata }) => {
const meta = Object.keys(metadata).length ? JSON.stringify(metadata) : '';
return `[${timestamp}] ${level.toUpperCase()} [${label || 'app'}] ${message} ${meta}`;
})
),
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
}),
new winston.transports.File({ filename: 'logs/error.log', level: 'error' }),
new winston.transports.File({ filename: 'logs/combined.log' })
]
});
module.exports = logger;
要点:
- 结构化字段(如requestId、userId、traceId)放入 metadata,便于检索与聚合。
- 错误日志使用**errors({ stack: true })**保留堆栈,便于定位。
二 控制台与文件差异化输出
- 控制台:面向开发/排障,使用彩色、单行可读格式(如 simple/printf)。
- 文件:面向持久化与检索,使用JSON 或 key=value,便于后续分析、聚合与可视化。
- 高性能场景优先选择Pino/Bunyan,开发期可接入pino-pretty/bunyan-pretty美化输出。
示例 Pino 开发期美化(生产移除 transport 以回归 JSON):
// pino 示例(开发)
const pino = require('pino');
const logger = pino({
level: 'debug',
transport: {
target: 'pino-pretty',
options: {
colorize: true,
translateTime: 'SYS:yyyy-mm-dd HH:MM:ss',
ignore: 'pid,hostname'
}
}
});
要点:
- 生产建议直接输出 JSON 到文件/集中系统;美化仅用于本地/开发。
三 HTTP 请求日志规范化
- Express 使用morgan记录访问日志,选择或自定义格式,包含method、url、status、response-time、content-length等关键字段。
- 将访问日志与业务日志分离,便于独立分析与告警。
示例 morgan 自定义格式:
const express = require('express');
const morgan = require('morgan');
const fs = require('fs');
const path = require('path');
const accessLogStream = fs.createWriteStream(
path.join(__dirname, 'logs', 'access.log'),
{ flags: 'a' }
);
app.use(morgan(':method :url :status :res[content-length] - :response-time ms', {
stream: accessLogStream
}));
要点:
- 常用格式:combined(包含 Referer/User-Agent)、common;也可按需自定义。
四 日志轮转与保留策略
- 文件轮转避免单文件过大、便于按时间/大小归档与清理。
- 方案A:应用内使用winston-daily-rotate-file(按天/大小切分、压缩、保留天数)。
- 方案B:系统级使用logrotate(适合 systemd 服务,统一运维策略)。
示例 winston-daily-rotate-file:
const DailyRotateFile = require('winston-daily-rotate-file');
const rotateTransport = new DailyRotateFile({
filename: 'logs/application-%DATE%.log',
datePattern: 'YYYY-MM-DD',
zippedArchive: true,
maxSize: '20m',
maxFiles: '14d'
});
示例 logrotate(/etc/logrotate.d/nodejs):
/var/log/nodejs/*.log {
daily
missingok
rotate 7
compress
notifempty
create 0640 root adm
}
# 执行:sudo logrotate /etc/logrotate.d/nodejs
要点:
- 按日切分+压缩+保留7–14天是常见实践;systemd 服务优先用 logrotate。
五 集中化与快速检索分析
- 小规模:用grep/awk/sed在服务器上快速检索与统计。
- 中大规模:接入ELK Stack(Elasticsearch/Logstash/Kibana)或Graylog/Fluentd,实现集中存储、搜索、可视化与告警。
示例 ELK Filebeat → Logstash → ES(关键片段):
# /etc/logstash/conf.d/nodejs.conf
input {
file {
path => "/var/log/nodejs/*.log"
start_position => "beginning"
codec => json
}
}
filter {
# 如为文本日志,可用 grok 解析;JSON 可直接使用
}
output {
elasticsearch {
hosts => ["localhost:9200"]
index => "nodejs-logs-%{+YYYY.MM.dd}"
}
}
要点:
- 统一字段命名(如timestamp、level、msg、module、requestId)能显著提升检索与分析效率。
以上就是关于“Ubuntu Node.js日志如何提高可读性”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm