插件窝 干货文章 Linux下JS日志如何收集

Linux下JS日志如何收集

日志 收集 使用 winston 436    来源:    2025-05-06

Linux下JavaScript日志收集方案

在Linux环境下收集JavaScript日志有多种方法,下面我将介绍几种常用的方案:

一、前端日志收集方案

1. 浏览器控制台日志收集

// 重写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);
  };
});

2. 使用前端日志库

  • Sentry: 提供完整的错误监控解决方案
  • LogRocket: 记录用户会话和错误
  • TrackJS: 专注于JavaScript错误跟踪

二、Node.js服务端日志收集

1. 常用日志库

// 使用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');

2. ELK Stack (Elasticsearch + Logstash + Kibana)

  1. 配置Logstash接收Node.js日志
  2. 使用winston-elasticsearch等库直接发送到Elasticsearch
const { ElasticsearchTransport } = require('winston-elasticsearch');

const esTransport = new ElasticsearchTransport({
  level: 'info',
  clientOpts: { node: 'http://localhost:9200' }
});

logger.add(esTransport);

三、日志收集工具

1. Filebeat

配置Filebeat收集Node.js应用日志并发送到Logstash/Elasticsearch:

filebeat.inputs:
- type: log
  enabled: true
  paths:
    - /var/log/node-app/*.log

output.logstash:
  hosts: ["localhost:5044"]

2. Fluentd

<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>

四、容器环境日志收集

1. Docker日志驱动

docker run --log-driver=syslog --log-opt syslog-address=udp://localhost:514 your-node-app

2. Kubernetes日志

  • 使用DaemonSet部署Fluentd/Filebeat
  • 使用sidecar容器收集日志

五、最佳实践建议

  1. 日志分级: 区分debug、info、warn、error等级别
  2. 结构化日志: 使用JSON格式便于解析
  3. 敏感信息过滤: 避免记录密码等敏感信息
  4. 日志轮转: 使用logrotate或日志库自带功能
  5. 上下文信息: 包含请求ID、用户ID等上下文

六、完整示例方案

前端 + Node.js全链路日志收集

  1. 前端使用Sentry捕获错误
  2. Node.js服务使用winston记录日志
  3. Filebeat收集Node.js日志并发送到ELK
  4. 使用Kibana进行日志分析和可视化

您需要根据具体应用场景和规模选择合适的方案组合。对于小型应用,简单的文件日志+logrotate可能足够;对于大型分布式系统,ELK或类似的集中式日志系统更为合适。