Skip to content

日志SDK v1.0.0

基于Native桥接方法的前端日志SDK,专注于轻量级日志记录,支持WebView会话追踪和日志标准化。

特性

  • 轻量级设计:专注日志记录,减少不必要的复杂性
  • WebView会话追踪:自动生成会话ID,方便追踪同一URL被不同WebView打开的情况
  • 业务域隔离:支持按业务scope打印日志
  • 标准化输出:结构化日志格式,方便排查问题
  • Vue错误捕获:支持Vue2和Vue3的错误监控
  • 错误捕获:JS错误、Promise错误、网络请求错误等
  • 自定义日志:支持自定义日志类型和格式

基本用法

javascript
import { initLogger, LogLevel } from '@wenext/log';

// 初始化日志SDK
const logger = await initLogger({
  app: 'MyApp',
  version: '1.0.0',
  env: 'production',
  scoped: 'H5_GREEDY',
  level: LogLevel.INFO,
  // 自动生成会话ID (WebView实例标识)
  generateSessionId: true,
  // 日志上报间隔,单位毫秒,设为0时立即发送不缓存
  reportInterval: 300,
  // 最大缓存日志数量
  maxCache: 100,
  // 启用错误捕获
  error: {
    enable: true,
    js: true,
    promise: true,
    resource: true,
    ajax: true,
    vue: true,
    fetch: false
  }
});

// 使用logger记录日志
logger.info('应用启动成功', 'app', { startTime: Date.now() });
logger.warn('配置项缺失', 'config', { missingKey: 'apiUrl' });
logger.error(new Error('API请求失败'), {
  scope: 'api',
  data: { url: '/api/users', status: 500 }
});

// 记录自定义日志
logger.custom('用户操作记录', {
  category: 'user_action',
  level: LogLevel.INFO,
  data: { action: 'click_button', elementId: 'submit-btn' }
});

// 按业务域记录日志
const apiLogger = logger.scope('api');
apiLogger.info('API请求开始', { url: '/api/users' });
apiLogger.debug('请求参数', { params: { page: 1, limit: 10 } });

在Vue中使用

Vue 2.x

javascript
import Vue from 'vue';
import { initLogger, getVueErrorHandler } from '@wenext/log';

async function setup() {
  const logger = await initLogger({
    app: 'MyApp',
    version: '1.0.0',
    env: 'production',
    scoped: 'H5_GREEDY',
    level: LogLevel.INFO,
    // 自动生成会话ID (WebView实例标识)
    generateSessionId: true,
    // 日志上报间隔,单位毫秒,设为0时立即发送不缓存
    reportInterval: 300,
    // 最大缓存日志数量
    maxCache: 100,
    // 启用错误捕获
    error: {
      enable: true,
      js: true,
      promise: true,
      resource: true,
      ajax: true,
      vue: true,
      fetch: false
    }
  });

  // 安装Vue错误处理插件
  Vue.use(getVueErrorHandler(logger));
}

setup();

Vue 3.x

javascript
import { createApp } from 'vue';
import App from './App.vue';
import { initLogger, getVueErrorHandler } from '@wenext/log';

async function setup() {
  const app = createApp(App);

  const logger = await initLogger({
    app: 'MyApp',
    version: '1.0.0',
    env: 'production',
    scoped: 'H5_GREEDY',
    level: LogLevel.INFO,
    // 自动生成会话ID (WebView实例标识)
    generateSessionId: true,
    // 日志上报间隔,单位毫秒,设为0时立即发送不缓存
    reportInterval: 300,
    // 最大缓存日志数量
    maxCache: 100,
    // 启用错误捕获
    error: {
      enable: true,
      js: true,
      promise: true,
      resource: true,
      ajax: true,
      vue: true,
      fetch: false
    }
  });

  // 安装Vue错误处理插件
  app.use(getVueErrorHandler(logger, {
    attachProps: false // 是否打印props,默认不打
  }));

  app.mount('#app');
}

setup();

API文档

核心类

  • Logger: 核心日志类,提供日志记录功能
  • ScopedLogger: 特定业务域的日志器,从Logger创建

日志级别

  • LogLevel.DEBUG: 调试信息
  • LogLevel.INFO: 信息
  • LogLevel.WARN: 警告
  • LogLevel.ERROR: 错误

日志类型

  • LogType.NORMAL: 普通日志
  • LogType.ERROR: 错误日志
  • LogType.CUSTOM: 自定义日志

主要方法

  • initLogger(options): 初始化日志SDK
  • logger.debug(message, scope?, data?): 记录调试日志
  • logger.info(message, scope?, data?): 记录信息日志
  • logger.warn(message, scope?, data?): 记录警告日志
  • logger.error(error, options?): 记录错误日志
  • logger.custom(message, options?): 记录自定义日志
  • logger.scope(scope): 创建特定业务域的日志器
  • logger.flush(): 立即上报所有缓存的日志
  • logger.destroy(): 销毁日志实例,清理资源

最佳实践

  1. 使用会话ID标识WebView实例:便于区分同一URL在不同WebView中的日志
  2. 按业务域组织日志:使用scope划分不同的业务模块日志
  3. 注意敏感信息:不要记录用户密码等敏感信息
  4. 结构化数据:使用data字段记录结构化数据,方便查询分析
  5. 合理设置缓存策略
    • 对于普通日志,建议设置适当的reportInterval进行批量上报,减少Native调用次数
    • 对于关键错误日志,可以手动调用flush()立即上报
    • 设置reportInterval: 0可以禁用缓存,所有日志立即发送

效果

javascript
/**
 *
 *  [, , 0]:{"type":"error","level":"error","message":"XHR response status not 200: 400 Bad Request","timestamp":1745826718751,"scope":"H5_SLOT","sessionId":"a397c8e1-50b1-42be-b1f1-c1844f2b273a","data":{"method":"GET","url":"http://43.134.222.242/api/slot/getSlotConfigInfo?channel=gp&platform=android&packageName=com.wenext.wyaklite","status":400,"statusText":"Bad Request","duration":345,"response":"{\"timestamp\":\"2025-04-28 15:51:58\",\"status\":400,\"error\":\"Bad Request\",\"message\":\"\",\"path\":\"/slot/getSlotConfigInfo\"}"},"tags":{"app":"wyak","version":"1.0.0","env":"development","path":"/index","network":"4g_wifi_0"},"error":{"name":"Error","message":"XHR response status not 200: 400 Bad Request","stack":"Error: XHR response status not 200: 400 Bad Request\n    at XMLHttpRequest.eval (webpack-internal:///../../log/dist/index.esm.js:346:26)"},"source":"ajax"}

 *
 *[, , 0]:{"type":"custom","level":"info","message":"应用启动成功","timestamp":1745826717461,"scope":"H5_SLOT","sessionId":"a397c8e1-50b1-42be-b1f1-c1844f2b273a","data":{"startTime":1745826717461},"tags":{"app":"wyak","version":"1.0.0","env":"development","path":"/index","network":"4g_wifi_0"}}
 *
 * {"type":"error","level":"error","message":"Vue错误捕获","timestamp":1745905922629,"scope":"H5_SLOT","sessionId":"1df374ea-b623-49eb-9f37-d3fec715f4f7","data":{"componentName":"<SlotGame>","lifecycleHook":"mounted hook","trace":"\n\nfound in\n\n---> <SlotGame> at src/views/index/index.vue\n       <App> at src/App.vue\n         <Root>"},"tags":{"app":"wyak","version":"1.0.0","env":"development","path":"/index","network":"4g_wifi_0"},"error":{"name":"Error","message":"index mounted error","stack":"Error: index mounted error\n    at VueComponent.mounted (webpack-internal:///../../node_modules/.pnpm/babel-loader@8.4.1_@babel+core@7.26.10_webpack@5.99.5_webpack-cli@4.10.0_webpack@5.99.5__/node_modules/babel-loader/lib/index.js??clonedRuleSet-40.use[0]!../../node_modules/.pnpm/vue-loader@15.11.1_@vue+compiler-sfc@3.5.13_css-loader@6.11.0_@rspack+core@1.3.4_webpac_850212ab919d06ea9273613b32c7979d/node_modules/vue-loader/lib/index.js??vue-loader-options!./src/views/index/index.vue?vue&type=script&lang=js:196:11)\n    at invokeWithErrorHandling (https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.7/vue.js:3649:63)\n    at callHook$1 (https://cdnjs.cloudflare.com/ajax/libs/vue/2.7.7/vue.js:3055:15)\n    ... 更多堆栈信息已省略"},"source":"vue"}
 *
 */