SSH隧道是一种安全的方式,可将远程服务器上的日志端口映射到本地,通过本地浏览器或工具直接查看。
步骤:
tail -f /path/to/app.log等命令查看。ssh -L local_port:localhost:remote_port user@remote_server_ip
local_port:本地映射端口(如8080);remote_port:远程服务器上日志文件的端口(若日志通过tail -f直接查看,可设为任意未占用端口,如8991);user:远程服务器用户名;remote_server_ip:远程服务器IP地址。http://localhost:local_port,即可实时查看远程日志。将Node.js日志发送到远程日志服务器(如rsyslog、Fluentd),集中存储和管理,适合大规模日志监控。
步骤:
远程服务器(接收端):
sudo apt update && sudo apt install rsyslog。/etc/rsyslog.conf,取消以下行注释(启用UDP模块):module(load="imudp")
input(type="imudp" port="514")
local0.* @remote_log_server_ip:514 # UDP转发(无确认)
# 或使用TCP(更可靠):
# local0.* @@remote_log_server_ip:514
sudo systemctl restart rsyslog。Debian节点(发送端):
syslog模块发送日志到远程rsyslog服务器:const syslog = require('syslog');
const log = syslog.createClient(514, 'remote_log_server_ip', { facility: syslog.facility.local0 });
log.info('This is a remote log message from Node.js');
tail -f /var/log/syslog(或自定义文件)查看。Fluentd是更灵活的日志收集工具,支持多源、多目的地转发。
步骤:
远程服务器(Fluentd接收端):
sudo apt update && sudo apt install fluentd。/etc/fluent/fluent.conf,开启UDP监听并转发到syslog:<source>
@type forward
port 24224
bind 0.0.0.0
</source>
<match **>
@type syslog
host remote_syslog_server_ip
port 514
</match>
sudo systemctl start fluentd。Debian节点(Node.js发送端):
fluent-logger库:npm install fluent-logger。const FluentLogger = require('fluent-logger');
const logger = FluentLogger.createLogger('node_app', { host: 'remote_fluentd_ip', port: 24224 });
logger.emit('info', { message: 'This is a log from Node.js to Fluentd' });
PM2是Node.js常用进程管理工具,支持日志集中管理和远程访问。
步骤:
npm install pm2 -g。pm2 start app.js --name "my-node-app" --log /var/log/node-app.log
pm2 logs my-node-app(本地查看)。--log-url参数,将日志暴露为HTTP接口:pm2 start app.js --name "my-node-app" --log /var/log/node-app.log --log-url http://remote_server_ip:3000/logs
http://remote_server_ip:3000/logs访问日志,或通过SSH反向隧道将端口映射到本地。sudo ufw allow 514/udp开放UDP端口。logrotate(如/etc/logrotate.d/node-app),定期压缩、删除旧日志。