bandeng-logger
Version: 
Logger from bandeng developer team.
518 lines (484 loc) • 18.4 kB
TypeScript
/**
 * 日志级别枚举
 */
declare type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace'
/**
 * 日志格式枚举
 */
declare type LogFormat = 'json' | 'text'
/**
 * 压缩格式枚举
 */
declare type CompressFormat = 'none' | 'gzip'
/**
 * 框架样式枚举
 */
declare type FrameworkStyle = 'koa' | 'express'
/**
 * 日志颜色配置
 */
declare interface LogColors {
    fatal?: string
    error?: string
    warn?: string
    info?: string
    debug?: string
    trace?: string
    reset?: string
}
/**
 * 强制打印条件函数
 */
declare type ForcePrintCondition = (logData: {level: LogLevel; message: string; timestamp: number}) => boolean
/**
 * 上下文处理器函数类型
 */
declare type CtxProcessor = (ctx: any) => any
/**
 * @description Logger 配置选项
 * @param {Object} [options={}] - 日志记录器配置选项
 * @param {string} [options.logLevel='warn'] - 日志级别 (fatal, error, warn, info, debug, trace)
 *   💡 按需配置:根据环境调整 (dev=debug, prod=warn)
 * @param {string} [options.logFormat='json'] - 日志格式 (json, text)
 *   💡 推荐使用默认值 'json',利于日志分析和监控
 * @param {number} [options.utcFormat] - UTC时区偏移,默认使用本地时区
 *   🚫 不建议修改:除非有特殊时区要求,否则使用默认值
 * @param {number} [options.maxLength=1000] - 单行日志最大长度
 *   🚫 不建议修改:默认值1000经过测试验证的合理长度
 * @param {string} [options.logDir='./logs'] - 日志文件存放目录
 *   🔧 必须配置:根据实际部署环境设置
 * @param {string} [options.logFileName='server.log'] - 主日志文件名
 *   🔧 可选配置:根据应用名称自定义
 * @param {string} [options.errorLogFileName='error.log'] - 错误日志文件名
 *   🚫 不建议修改:保持默认即可
 * @param {boolean} [options.separateErrorLog=true] - 是否分离错误日志
 *   🚫 不建议修改:默认值true有利于错误排查
 * @param {string[]} [options.separateErrorLevels=['error','fatal']] - 需要分离的错误级别
 *   🚫 不建议修改:默认值经过验证的最佳组合
 * @param {boolean} [options.traceLogWrite=false] - 是否跟踪日志写入性能
 *   🚫 不建议修改:生产环境保持false
 * @param {number} [options.rotate=100] - 日志轮转大小(MB)
 *   🔧 可选配置:根据磁盘空间和日志量调整
 * @param {number} [options.interval=3600] - 日志轮转时间间隔(秒)
 *   🚫 不建议修改:默认1小时适合大多数应用
 * @param {string} [options.compress='none'] - 日志压缩格式 (none, gzip)
 *   🔧 可选配置:根据存储需求选择
 * @param {number} [options.maxFiles=15] - 保留的最大日志文件数量
 *   🚫 不建议修改:默认值15平衡存储和历史记录
 * @param {number} [options.bufferSize=65536] - 缓冲区大小(bytes)
 *   🚫 不建议修改:默认值64KB经过性能测试优化
 * @param {number} [options.flushInterval=1000] - 缓冲区刷新间隔(ms)
 *   🚫 不建议修改:默认值1000ms平衡性能和实时性
 * @param {string[]} [options.forceSyncLevels=['fatal']] - 强制同步写入的日志级别
 *   🚫 不建议修改:默认值确保关键错误立即写入
 * @param {Function} [options.ctxProcessor=null] - 上下文数据处理函数
 *   🔧 高级配置:需要时再配置,默认null
 * @param {Function[]} [options.forcePrintConditions=[]] - 强制打印条件函数数组
 *   🔧 高级配置:符合条件的日志无论级别如何都会打印,用于排查特定业务
 * @param {Object} [options.colors] - 控制台颜色配置
 *   🚫 不建议修改:默认配色适合大多数终端
 * @param {string} [options.colors.fatal='brightRed'] - fatal级别颜色
 * @param {string} [options.colors.error='red'] - error级别颜色
 * @param {string} [options.colors.warn='brightYellow'] - warn级别颜色
 * @param {string} [options.colors.info='gray'] - info级别颜色
 * @param {string} [options.colors.debug='blue'] - debug级别颜色
 * @param {string} [options.colors.trace='white'] - trace级别颜色
 *
 * @example
 * // 🚀 推荐:基本使用(使用所有默认配置)
 * const logger = new Logger()
 * // 自动使用经过优化的默认值,无需任何配置
 *
 * @example
 * // 🔧 仅配置必要的参数(推荐方式)
 * const logger = new Logger({
 *   logDir: '/var/log/myapp',     // 根据部署环境配置
 *   logFileName: 'myapp.log'      // 根据应用名称配置
 *   // 其他参数使用默认值即可
 * })
 *
 * @example
 * // 📊 完整配置示例(仅在需要时使用)
 * const logger = new Logger({
 *   // 🔧 必须配置(根据部署环境)
 *   logDir: '/var/log/myapp',
 *
 *   // 💡 按需配置(根据实际需求)
 *   logLevel: 'info',            // dev=debug, prod=warn
 *   logFileName: 'myapp.log',
 *   rotate: 200,                 // 根据日志量调整
 *   compress: 'gzip',            // 启用压缩节省空间
 *
 *   // 🚫 以下参数使用默认值(经过验证的最佳选择)
 *   // logFormat: 'json',        // 默认json格式最佳
 *   // maxLength: 1000,          // 1000长度验证
 *   // separateErrorLog: true,   // true利于排查
 *   // bufferSize: 65536,        // 64KB性能优化
 *   // flushInterval: 1000,      // 1秒平衡配置
 *   // maxFiles: 15,             // 15文件数量平衡
 *   // forceSyncLevels: ['fatal'] // 确保fatal立即写入
 * })
 *
 * @example
 * // 🐛 开发环境调试配置
 * const logger = new Logger({
 *   logLevel: 'debug',           // 开发时使用debug级别
 *   logFormat: 'text',           // 开发时使用text格式便于阅读
 *   traceLogWrite: true          // 开发时启用性能跟踪
 *   // 其他参数保持默认值
 * })
 *
 * @example
 * // 🚀 高性能生产环境配置
 * const logger = new Logger({
 *   logLevel: 'warn',            // 生产环境使用warn级别
 *   bufferSize: 131072,          // 128KB缓冲区(2倍默认值)
 *   flushInterval: 500,          // 500ms刷新(更实时)
 *   compress: 'gzip',            // 必须启用压缩
 *   maxFiles: 30                 // 保留更多日志文件
 *   // 其他参数使用默认值即可
 * })
 *
 * @example
 * // 🔍 强制打印条件示例(用于业务排查)
 * const logger = new Logger({
 *   logLevel: 'error',  // 只打印error及以上的日志
 *   forcePrintConditions: [
 *     // 强制打印所有包含'payment'的日志,无论级别如何
 *     (logData) => logData.message.includes('payment'),
 *     // 强制打印所有debug级别的登录相关日志
 *     (logData) => logData.level === 'debug' && logData.message.includes('login'),
 *     // 强制打印最近5分钟内的所有warning日志
 *     (logData) => logData.level === 'warn' && logData.timestamp > Date.now() - 300000
 *   ]
 * })
 *
 * // 使用示例:
 * logger.error('Payment failed')     // ✅ 正常打印(级别足够)
 * logger.debug('User payment success') // ✅ 强制打印(包含'payment')
 * logger.debug('User login success')   // ✅ 强制打印(debug级别+login)
 * logger.debug('Normal debug')         // ❌ 不打印(级别不够,无匹配条件)
 *
 * @note
 * 🎯 配置参数分类指南:
 *
 * 🔧 必须配置的参数:
 * - logDir: 根据实际部署环境设置日志目录
 *
 * 💡 按需配置的参数:
 * - logLevel: 根据环境调整 (dev=debug, prod=warn)
 * - logFileName: 根据应用名称自定义
 * - rotate: 根据磁盘空间和日志量调整
 * - compress: 根据存储需求选择 (none, gzip)
 * - forcePrintConditions: 业务排查时强制打印特定日志
 * - ctxProcessor: 高级功能,需要时配置
 *
 * 🚫 不建议修改的参数(使用默认值最佳):
 * - utcFormat: 除非特殊时区要求
 * - maxLength: 1000(测试验证长度)
 * - separateErrorLog: true(错误排查利器)
 * - separateErrorLevels: ['error','fatal'](最佳组合)
 * - traceLogWrite: false(生产环境)
 * - interval: 3600秒(1小时)
 * - maxFiles: 15(存储平衡)
 * - bufferSize: 64KB(性能优化)
 * - flushInterval: 1000ms(性能平衡)
 * - forceSyncLevels: ['fatal'](关键错误保障)
 * - errorLogFileName: 'error.log'
 * - colors: 默认配色
 */
declare interface LoggerOptions {
    /** 日志级别 (fatal, error, warn, info, debug, trace) */
    logLevel?: LogLevel
    /** 日志格式 (json, text) */
    logFormat?: LogFormat
    /** UTC时区偏移,默认使用本地时区 */
    utcFormat?: number
    /** 单行日志最大长度 */
    maxLength?: number
    /** 日志文件存放目录 */
    logDir?: string
    /** 主日志文件名 */
    logFileName?: string
    /** 错误日志文件名 */
    errorLogFileName?: string
    /** 是否分离错误日志 */
    separateErrorLog?: boolean
    /** 需要分离的错误级别 */
    separateErrorLevels?: LogLevel[]
    /** 是否跟踪日志写入性能 */
    traceLogWrite?: boolean
    /** 日志轮转大小(MB) */
    rotate?: number
    /** 日志轮转时间间隔(秒) */
    interval?: number
    /** 日志压缩格式 (none, gzip) */
    compress?: CompressFormat
    /** 保留的最大日志文件数量 */
    maxFiles?: number
    /** 缓冲区大小(bytes) */
    bufferSize?: number
    /** 缓冲区刷新间隔(ms) */
    flushInterval?: number
    /** 强制同步写入的日志级别 */
    forceSyncLevels?: LogLevel[]
    /** 强制打印条件函数数组 */
    forcePrintConditions?: ForcePrintCondition[]
    /** 上下文数据处理函数 */
    ctxProcessor?: CtxProcessor
    /** 控制台颜色配置 */
    colors?: LogColors
}
/**
 * HTTP请求日志选项
 */
declare interface HttpRequestOptions {
    /** 框架类型 */
    frameworkStyle: FrameworkStyle
    /** 响应时间(毫秒) */
    responseTime?: number
    /** 额外要打印的参数数组 */
    extraParams?: string[]
}
/**
 * 请求上下文接口
 */
declare interface RequestContext {
    source?: string
    path?: string
    method?: string
    userId?: string | number
    ip?: string
    [key: string]: any
}
/**
 * 性能日志数据接口
 */
declare interface PerformanceLogData {
    level: 'warn' | 'trace'
    data: {
        latency: number
        message: string
        threshold?: number
        [key: string]: any
    }
}
/**
 * 统计信息接口
 */
declare interface LoggerStatistics {
    /** 总日志数 */
    totalLogs: string
    /** 已刷新日志数 */
    flushedLogs: string
    /** 失败刷新次数 */
    failedFlushes: number
    /** 慢写入次数 */
    slowWrites: number
    /** 主缓冲区信息 */
    mainBuffer: {
        currentSize: number
        dataCount: number
        isFlushing: boolean
        maxSize: number
        maxCount: number
        totalWrites: number
    }
    /** 错误缓冲区信息 */
    errorBuffer: {
        currentSize: number
        dataCount: number
        isFlushing: boolean
        maxSize: number
        maxCount: number
        totalWrites: number
    }
    /** 队列大小 */
    queueSize: number
    /** 是否正在写入 */
    isWriting: boolean
    /** 运行时间(ms) */
    uptime: number
    /** 平均刷新间隔 */
    averageFlushInterval: number
    /** 刷新计数 */
    flushCount: number
    /** 是否已销毁 */
    isDestroyed: boolean
    /** 是否正在清理文件 */
    isCleaningFiles: boolean
    /** 最后刷新时间 */
    lastFlushTime: string
    /** 当前时间 */
    currentTime: string
}
/**
 * @description 日志记录器主类 - 高性能的Node.js日志库
 * @description ✨ 核心特性:
 *   • 高性能缓冲区系统,支持异步写入和批量刷新
 *   • 智能日志轮转,支持大小和时间双重限制
 *   • 完整的错误处理和恢复机制
 *   • 强制打印条件:允许特定日志无论级别如何都输出,便于业务排查
 */
declare class LoggerClass {
    /**
     * 创建Logger实例
     * @param options 配置选项
     */
    constructor(options?: LoggerOptions)
    /**
     * @description 致命错误日志
     * @param {string} msg - 日志消息
     * @param {...any} args - 日志参数
     */
    fatal(msg: any, ...args: any[]): void
    /**
     * @description 错误日志
     * @param {string} msg - 日志消息
     * @param {...any} args - 日志参数
     */
    error(msg: any, ...args: any[]): void
    /**
     * @description 警告日志
     * @param {string} msg - 日志消息
     * @param {...any} args - 日志参数
     */
    warn(msg: any, ...args: any[]): void
    /**
     * @description 信息日志
     * @param {string} msg - 日志消息
     * @param {...any} args - 日志参数
     */
    info(msg: any, ...args: any[]): void
    /**
     * @description 记录调试级别日志
     * @param {string} msg - 日志消息(必须为字符串,否则会发出警告)
     * @param {...any} args - 额外参数(对象会被展开,其他类型使用msg键)
     * @example
     * logger.debug('User action', {userId: 123, action: 'login'})
     * logger.debug('Data received', dataArray)
     */
    debug(msg: any, ...args: any[]): void
    /**
     * @description 跟踪日志
     * @param {string} msg - 日志消息
     * @param {...any} args - 日志参数
     */
    trace(msg: any, ...args: any[]): void
    /**
     * @description 创建子日志记录器
     * @param {string} moduleName - 模块名
     * @returns {LoggerClass} 子日志记录器
     */
    createChildLogger(moduleName: string): LoggerClass
    /**
     * 性能日志记录(已废弃,请使用traceRequestPerformance)
     * @param source 来源
     * @param path 路由
     * @param latency 耗时
     * @param timeThreshold 阈值
     * @param reqObj 请求参数对象
     */
    tracePerformance(source: string, path: string, latency: number, timeThreshold: number, reqObj: any): void
    /**
     * 请求性能追踪日志
     * @param {Object} ctx 请求上下文(由外部调用者决定内容格式)
     * @param {Number} latency 请求耗时(毫秒)
     * @param {Number} timeThreshold 生产环境打印请求耗时的阈值(毫秒)
     */
    traceRequestPerformance(ctx: RequestContext, latency: number, timeThreshold: number): PerformanceLogData | null
    /**
     * @description 获取当前配置
     * @returns {Object} 当前配置的副本
     */
    getOptions(): LoggerOptions
    /**
     * @description 获取日志统计信息
     * @returns {Object} 统计信息
     */
    getStatistics(): LoggerStatistics
    /**
     * @description 重置统计信息
     */
    resetStatistics(): void
    /**
     * @description 更新配置(热重载)
     * @param {Object} newOptions - 新的配置选项
     * @returns {boolean} 是否成功更新
     */
    updateOptions(newOptions: Partial<LoggerOptions>): boolean
    /**
     * @description 进程退出前记录日志
     * @param {Error} error - 错误对象
     */
    logBeforeExit(error: Error): Promise<void>
    /**
     * @description 进程启动记录日志
     * @param {Object} info - 进程信息
     */
    logProcessStart(info: any): Promise<void>
    /**
     * @description 关键业务日志记录
     * @param {string} taskname - 任务名
     * @param {Object} info - 进程信息
     */
    logPivotalInfo(taskname: string, info: any): Promise<void>
    /**
     * @description HTTP请求日志记录(仅控制台输出)
     * @param {Object} request - 请求对象(Koa ctx 或 Express req/res)
     * @param {Object} options - 配置选项
     * @param {string} options.frameworkStyle - 框架类型(必填) ('koa' 或 'express')
     * @param {number} [options.responseTime] - 响应时间(毫秒),如果不提供则尝试从请求对象获取
     * @param {Array} [options.extraParams=[]] - 额外要打印的参数数组
     *
     * @example
     * // Koa框架使用
     * app.use(async (ctx, next) => {
     *   const startTime = Date.now()
     *   await next()
     *   logger.logHttpRequest(ctx, {
     *     frameworkStyle: 'koa', // 必填:必须指定框架类型
     *     responseTime: Date.now() - startTime
     *   })
     * })
     *
     * @example
     * // Express框架使用
     * app.use((req, res, next) => {
     *   const startTime = Date.now()
     *   res.on('finish', () => {
     *     logger.logHttpRequest({req, res}, {
     *       frameworkStyle: 'express', // 必填:必须指定框架类型
     *       responseTime: Date.now() - startTime
     *     })
     *   })
     *   next()
     * })
     *
     * @example
     * // 带额外参数(IP自动提取,不需要手动指定)
     * logger.logHttpRequest(ctx, {
     *   frameworkStyle: 'koa', // 必填:必须指定框架类型
     *   responseTime: 123.46,
     *   extraParams: ['userId:123', 'userAgent:Mozilla/5.0']
     * })
     */
    logHttpRequest(request: any, options: HttpRequestOptions): void
    /**
     * @description 清理所有资源(定时器、文件描述符、缓冲区、队列)
     */
    destroy(): Promise<boolean>
    /**
     * @description 获取预定义的 ctx 处理函数
     * @param {string} type - 处理函数类型
     * @param {Object} options - 处理选项
     * @returns {Function} 处理函数
     */
    static getCtxProcessor(type: 'whitelist' | 'blacklist' | 'rename' | 'transform' | 'depthLimit' | 'combine', options?: any): CtxProcessor
}
declare const Logger: {
    new (options?: LoggerOptions): LoggerClass
    getCtxProcessor(type: 'whitelist' | 'blacklist' | 'rename' | 'transform' | 'depthLimit' | 'combine', options?: any): CtxProcessor
}
// CommonJS导出
export = LoggerClass