温馨提示×

如何过滤JS日志内容

小樊
32
2026-08-17 16:40:47
栏目: 编程语言

过滤 JS 日志内容,常见场景有 浏览器端过滤Node.js 端过滤构建阶段过滤日志平台过滤。下面按使用场景给你一份实用指南。


一、浏览器端过滤 JS 日志

1️⃣ 使用 console 自带过滤(最简单)

在浏览器 DevTools 中:

  • 按日志类型过滤:log / info / warn / error
  • 按关键词过滤:DevTools 右上角搜索框
  • 按文件名过滤:DevTools → Console → 漏斗图标

✅ 无需改代码,适合调试


2️⃣ 重写 console 方法(常用)

适合生产环境屏蔽或过滤日志

const isDev = process.env.NODE_ENV !== 'production';

if (!isDev) {
  console.log = () => {};
  console.debug = () => {};
}

✅ 优点:简单
❌ 缺点:无法按内容过滤


3️⃣ 按关键词 / 级别过滤日志

function filterLog(...args) {
  const blockWords = ['debug', 'test'];
  const msg = args.join(' ');
  if (blockWords.some(w => msg.includes(w))) return;
  console.log(...args);
}

filterLog('this is debug info'); // 被过滤
filterLog('user login success'); // 正常输出

✅ 可按内容过滤
✅ 可扩展为日志系统


4️⃣ 封装统一日志模块(推荐)

const logger = {
  info(...args) {
    if (process.env.NODE_ENV === 'development') {
      console.log('[INFO]', ...args);
    }
  },
  error(...args) {
    console.error('[ERROR]', ...args);
  }
};

logger.info('debug info'); // 开发环境输出
logger.error('server error'); // 始终输出

✅ 控制粒度更细
✅ 易维护


二、Node.js 端过滤日志

1️⃣ 使用日志库(最推荐)

常用库:

  • winston
  • pino
  • log4js

winston 示例

const winston = require('winston');

const logger = winston.createLogger({
  level: 'info', // 只输出 info 及以上
  transports: [new winston.transports.Console()]
});

logger.debug('debug info'); // 被过滤
logger.info('info msg');
logger.error('error msg');

✅ 支持级别过滤
✅ 支持文件 / 远程日志


2️⃣ 按关键词过滤

function log(msg) {
  if (/secret|password/.test(msg)) return;
  console.log(msg);
}

三、构建阶段过滤(Webpack / Vite)

Webpack 示例

new webpack.DefinePlugin({
  'process.env.NODE_ENV': JSON.stringify('production')
})

配合:

if (process.env.NODE_ENV !== 'production') {
  console.log(xxx);
}

❌ 不能过滤字符串拼接的日志
✅ 可配合 UglifyJS / Terser 删除 console


Terser 删除 console

terserOptions: {
  compress: {
    drop_console: true
  }
}

✅ 生产环境常用


四、日志平台过滤(ELK / Sentry / Grafana)

如果是线上日志系统

  • 在采集端过滤
  • 在查询时过滤

示例(ELK):

{
  "query": {
    "bool": {
      "must_not": [
        { "match": { "message": "debug" } }
      ]
    }
  }
}

五、常见过滤策略总结

场景 推荐方式
浏览器调试 DevTools
生产环境 重写 console / 封装 logger
Node 服务 winston / pino
构建阶段 Terser drop_console
日志平台 查询过滤

六、最佳实践建议 ✅

  • ❌ 不要直接删除 console.error
  • ✅ 使用统一 logger
  • ✅ 生产环境只保留 warn / error
  • ✅ 防止敏感信息被打印

如果你能说明:

  • 浏览器还是 Node
  • 想过滤 类型 / 关键词 / 环境
  • 是否使用 框架(Vue / React / Next)

我可以给你一份更精确的过滤方案或现成代码

0