在Debian系统上监控JavaScript(JS)日志异常,可以通过以下几种方法来实现:
如果你使用的是Node.js应用程序,可以利用Node.js内置的console
模块来记录日志,并通过配置日志级别来捕获异常。
const fs = require('fs');
const path = require('path');
// 创建一个可写流,用于写入日志文件
const accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' });
// 配置日志格式
const logger = require('morgan')('combined', {
stream: {
write: message => {
accessLogStream.write(message + '\n');
}
}
});
// 使用logger中间件
app.use(logger);
// 捕获未处理的异常
process.on('uncaughtException', (err) => {
console.error('There was an uncaught error', err);
process.exit(1); // 强制退出进程
});
// 捕获未处理的Promise拒绝
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
你可以使用像winston
或pino
这样的第三方日志库来更灵活地记录和管理日志。
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' })
]
});
// 捕获未处理的异常
process.on('uncaughtException', (err) => {
logger.error('Uncaught Exception:', err);
process.exit(1);
});
// 捕获未处理的Promise拒绝
process.on('unhandledRejection', (reason, promise) => {
logger.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
你可以使用像ELK Stack
(Elasticsearch, Logstash, Kibana)或Graylog
这样的日志管理工具来集中管理和监控日志。
安装Elasticsearch:
sudo apt-get update
sudo apt-get install elasticsearch
安装Logstash:
sudo apt-get install logstash
安装Kibana:
sudo apt-get install kibana
配置Logstash:
创建一个Logstash配置文件/etc/logstash/conf.d/js-logs.conf
:
input {
file {
path => "/path/to/your/js/logs/*.log"
start_position => "beginning"
}
}
filter {
# 根据需要添加过滤器
}
output {
elasticsearch {
hosts => ["localhost:9200"]
index => "js-logs-%{+YYYY.MM.dd}"
}
}
启动Logstash:
sudo systemctl start logstash
配置Kibana:
打开Kibana界面(通常是http://your_server_ip:5601
),配置索引模式为js-logs-*
。
你可以使用像Prometheus
和Grafana
这样的系统监控工具来监控应用程序的性能和日志。
安装Prometheus:
wget https://github.com/prometheus/prometheus/releases/download/v2.30.3/prometheus-2.30.3.linux-amd64.tar.gz
tar xvfz prometheus-2.30.3.linux-amd64.tar.gz
cd prometheus-2.30.3.linux-amd64
配置Prometheus:
编辑prometheus.yml
文件,添加你的应用程序的日志端点。
启动Prometheus:
./prometheus --config.file=prometheus.yml
安装Grafana:
sudo apt-get install grafana
配置Grafana:
打开Grafana界面(通常是http://your_server_ip:3000
),添加Prometheus数据源,并创建仪表盘来监控日志。
通过这些方法,你可以在Debian系统上有效地监控和管理JavaScript应用程序的日志异常。