1.1.7 • Published 5 months ago

console-capturer v1.1.7

Weekly downloads
-
License
ISC
Repository
-
Last release
5 months ago

errorCaptured 工具函数使用文档

请优先下载最新版本库 errorCaptured 是一个用于捕获和管理前端错误、日志、网络请求、性能数据等信息的工具函数。它可以帮助开发者监控应用的运行状态,并在需要时将数据持久化存储 QQ 讨论群:324710217

安装

npm i console-capturer

参数介绍

import errorCaptured from './errorCaptured';

const { logs, currentlogs, disableAllCaptures } = errorCaptured({
  captureConsole: true, // 是否捕获 console 日志
  captureErrors: true, // 是否捕获全局错误
  captureNetwork: true, // 是否捕获网络请求
  capturePerformance: false, // 是否捕获性能数据
  enableStorage: true, // 是否启用持久化存储
  storageType: "local", // 存储类型(可选 'local' 或 'session')
  storageName: "console_logs", // 存储名称
  storageMaxItems: 100, // 存储的最大条目数
  storageInterval: 5000, // 存储间隔时间(毫秒)
  maxLogs: 1000, // 日志的最大条数
  reportError: (newItems, beforePush, afterPush, originalConsole) => {
    // 自定义错误报告逻辑
    这里一定不能使用 console.log,否则会导致循环调用!!!
    如果有接口调用,请使用 try catch 捕获异常,避免错误被循环捕获
    // console.log('New logs:', newItems);
    // 这里可以使用 originalConsole.log打印输出,originalConsole的打印不会被监听,这样也就避免了循环调用
    originalConsole.log('New logs:', newItems);
  },
});

配置参数

示例图片

返回值

errorCaptured 返回一个对象,包含以下属性和方法:

示例图片

示例

const { logs, disableAllCaptures } = errorCaptured({
  captureConsole: true,
  captureNetwork: true,
  enableStorage: true,
});

// 模拟网络请求
fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => console.log(data));

// 打印捕获的日志
setTimeout(() => {
  console.log('Captured logs:', logs);
}, 2000);

// 撤销所有监控
disableAllCaptures();

日志结构

每条日志是一个对象,包含以下字段:

示例图片

注意事项

撤销监控:如果需要恢复原始状态,可以调用 disableAllCaptures 方法。 持久化存储:启用持久化存储后,日志会被定时保存到 localStorage 或 sessionStorage 中。 性能开销:捕获大量日志可能会影响性能,建议根据实际需求配置 maxLogs 和 storageMaxItems 参数。 reportError:在 reportError 回调函数中,不要使用 console.log,否则可能会导致循环调用,请使用 originalConsole.log。 并且如果有接口调用,请使用 try catch 捕获异常,避免错误被循环捕获

输出示例

[
  {
    "type": "LOG",
    "timestamp": "2023-10-01T12:00:00.000Z",
    "messages": ["Hello, World!"]
  },
  {
    "type": "NETWORK",
    "subtype": "FETCH",
    "timestamp": "2023-10-01T12:00:01.000Z",
    "url": "https://jsonplaceholder.typicode.com/todos/1",
    "status": 200,
    "duration": 150
  },
  {
    "type": "ERROR",
    "timestamp": "2023-10-01T12:00:02.000Z",
    "messages": ["ReferenceError: foo is not defined"],
    "stack": "Error stack trace..."
  }
]

相关 API

建议

如果对此工具包有更好的建议或需要支持新的功能,欢迎提 issue 或者加本人的 QQ:1844119859。

1.1.7

5 months ago

1.1.6

5 months ago

1.1.5

5 months ago

1.1.4

5 months ago

1.1.3

5 months ago

1.1.1

5 months ago

1.0.0

5 months ago