在Linux环境下收集JavaScript日志有多种方法,下面我将介绍几种常用的方案:
// 重写console方法
['log', 'error', 'warn', 'info'].forEach(method => {
const oldMethod = console[method];
console[method] = function() {
// 发送日志到服务器
fetch('/log', {
method: 'POST',
body: JSON.stringify({
level: method,
message: Array.from(arguments),
timestamp: new Date().toISOString()
})
});
// 保持原console功能
oldMethod.apply(console, arguments);
};
});
// 使用winston示例
const winston = require('winston');
const logger = winston.createLogger({
level: 'info',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
]
});
// 使用示例
logger.info('Info message');
logger.error('Error message');
winston-elasticsearch
等库直接发送到Elasticsearchconst { ElasticsearchTransport } = require('winston-elasticsearch');
const esTransport = new ElasticsearchTransport({
level: 'info',
clientOpts: { node: 'http://localhost:9200' }
});
logger.add(esTransport);
配置Filebeat收集Node.js应用日志并发送到Logstash/Elasticsearch:
filebeat.inputs:
- type: log
enabled: true
paths:
- /var/log/node-app/*.log
output.logstash:
hosts: ["localhost:5044"]
<source>
@type tail
path /var/log/node-app.log
pos_file /var/log/node-app.log.pos
tag node.app
format json
</source>
<match node.app>
@type elasticsearch
host localhost
port 9200
index_name node-app
</match>
docker run --log-driver=syslog --log-opt syslog-address=udp://localhost:514 your-node-app
您需要根据具体应用场景和规模选择合适的方案组合。对于小型应用,简单的文件日志+logrotate可能足够;对于大型分布式系统,ELK或类似的集中式日志系统更为合适。