logger

package module
v0.4.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 16, 2025 License: Apache-2.0 Imports: 26 Imported by: 15

README

Go Logger - 企业级高性能日志库

go-logger 是一个现代化、高性能的 Go 日志库,专为企业级应用设计。它提供了强大的模块化架构、内存监控、性能分析、分布式追踪等企业级功能,并通过极致性能优化实现了业界领先的性能表现

stable license download release commit issues pull fork star go size contributors codecov Go Report Card Go Reference Sourcegraph

📚 文档导航

📖 官方文档
📋 技术文档
🔗 代码资源
💬 社区支持

🚀 为什么选择 go-logger?

⚡ 极致性能
  • 🏆 业界领先: 相比标准库 slog 快 7.7倍 (75.8ns vs 585.2ns)
  • 💾 内存优化: 83% 内存减少 (144B → 24B),50% 分配减少 (2 → 1 allocs)
  • 🔧 分层设计: 三层性能架构满足不同性能需求
  • 📊 零开销: 级别过滤接近零性能开销
核心功能
  • 📊 内存监控系统:实时监控内存使用、GC性能、堆分析,支持内存泄漏检测
  • 🔍 分布式追踪:统一的Context服务架构,支持TraceID、SpanID、CorrelationID等多维度追踪
  • 🔌 自定义上下文提取器:灵活的上下文信息提取机制,支持完全自定义链路追踪字段
  • 🎯 多级日志系统:支持24种日志级别,从TRACE到PROFILING,满足不同场景需求
  • 📈 性能监控:实时统计操作性能、延迟分析、吞吐量监控
  • ⚡ 架构重构:Context管理代码减少88%,从1059行优化到128行,性能显著提升
企业级功能
  • 🛡️ 内存安全:智能内存管理、GC优化、内存压力检测与自动释放
  • 📊 统计分析:详细的运行时统计、性能指标收集、趋势分析
  • 🔧 配置管理:细粒度配置系统,支持动态配置更新
  • ⚙️ 适配器模式:支持多种输出适配器,灵活扩展输出目标
  • 🧪 完善测试:基于测试套件的全面测试,覆盖率90%+
🔌 自定义上下文提取器

支持灵活提取和自定义上下文信息,满足不同场景需求:

核心能力

  • 🎯 预定义提取器: SimpleTraceIDExtractor、SimpleRequestIDExtractor、NoOpContextExtractor
  • 🔧 自定义字段: CustomFieldExtractor - 从 context 或 gRPC metadata 提取任意字段
  • 🔗 链式组合: ChainContextExtractors - 组合多个提取器
  • 🏗️ 构建器模式: ContextExtractorBuilder - 流式 API 构建复杂提取器
  • 完全自定义: 支持自定义 ContextExtractor 函数

性能表现: NoOp (137ns) | 默认 (466ns) | 链式 (430ns)

适用场景: 微服务追踪 | 多租户系统 | API 网关 | 分布式链路追踪

📖 查看完整文档和示例 →

监控能力 ⚡ 极致性能优化
  • 🔥 内存实时监控: 堆内存、栈内存、GC统计、对象计数
  • 📊 性能分析: 操作延迟、吞吐量、错误率统计
  • 🛡️ 泄漏检测: 智能内存泄漏检测、趋势分析、告警机制
  • 💡 健康检查: 系统健康状态监控、自动优化建议
  • 🎯 分层架构: 根据性能需求选择不同监控级别
    • UltraLight: 3.134ns/op - 极致性能,原子操作
    • Optimized: 3.094ns/op - 缓存优化,零分配
    • Standard: 24.075μs/op - 全功能监控
分层性能架构
// 🏆 极致性能 - UltraFastLogger (推荐)
ultraLogger := logger.NewUltraFast()

// 或使用完整配置
config := logger.DefaultConfig()
config.Level = logger.INFO
config.Colorful = false
config.ShowCaller = false
ultraLogger = logger.NewUltraFastLogger(config)

// ⚡ 高性能 - 优化版标准Logger  
optimizedLogger := logger.NewOptimized()

// 🛡️ 全功能 - 企业级Logger (默认)
fullLogger := logger.New()

// 或使用完整配置
enterpriseConfig := logger.DefaultConfig()
enterpriseConfig.Level = logger.INFO
enterpriseConfig.ShowCaller = true
enterpriseConfig.Colorful = true
fullLogger = logger.NewLogger(enterpriseConfig)
🛡️ 监控架构 - 三层性能设计
// ⚡ 超轻量级监控 - 3.134ns/op,零分配
ultraMonitor := metrics.NewUltraLightMonitor()
ultraMonitor.Enable()
done := ultraMonitor.Track()
// ... 业务逻辑 ...
done(nil) // 完成追踪

// 🔥 优化监控 - 3.094ns/op,智能缓存
optimizedConfig := metrics.OptimizedConfig{
    CacheExpiry:     100 * time.Millisecond,
    EnableCaching:   true,
    LightweightMode: true,
}
monitor := metrics.NewOptimizedMonitor(optimizedConfig)
monitor.Start()
heap, stack, used, numGC := monitor.FastMemoryInfo()

// 📊 内存追踪器 - 53ns/op,原子操作
tracker := metrics.NewMemoryTracker(512) // 512MB阈值
exceeded := tracker.Update(heapBytes)
if exceeded {
    log.Warn("Memory threshold exceeded")
}

// 🎯 智能健康检查
healthy, pressure := monitor.QuickCheck()
fmt.Printf("系统健康: %v, 内存压力: %s", healthy, pressure)

📖 查看详细性能分析 →

🏗️ 模块化架构

go-logger/
├── config/              # 配置管理模块
│   ├── base.go          # 基础配置
│   ├── adapter.go       # 适配器配置
│   ├── output.go        # 输出配置
│   └── level.go         # 日志级别配置
├── context_service.go   # 统一上下文服务(新架构核心)
├── level/               # 日志级别管理
│   ├── constants.go     # 级别常量定义
│   └── manager.go       # 级别管理器
├── metrics/             # 监控指标模块
│   ├── stats.go         # 统计收集
│   ├── performance.go   # 性能监控
│   └── memory.go        # 内存监控
├── docs/                # 文档目录
│   ├── CONTEXT_USAGE.md # Context使用指南
│   ├── PERFORMANCE.md   # 性能详解
│   └── MIGRATION.md     # 迁移指南
└── examples/            # 示例代码

📦 快速开始

环境要求

建议需要 Go 版本 1.20 或更高版本

安装

使用 Go 的模块支持,当您在代码中添加导入时,go [build|run|test] 将自动获取所需的依赖项:

import "github.com/kamalyes/go-logger"

或者,使用 go get 命令:

go get -u github.com/kamalyes/go-logger

🚀 使用示例

基础用法
package main

import (
    "context"
    "github.com/kamalyes/go-logger"
)

func main() {
    // 🏆 极致性能版本 (推荐高并发场景)
    ultraLogger := logger.NewUltraFast()
    ultraLogger.Info("High performance logging")
    ultraLogger.InfoKV("High performance with fields", "key", "value")
    
    // ⚡ 优化版标准Logger
    optimizedLogger := logger.NewOptimized()
    optimizedLogger.Info("Optimized logging with features")
    
    // 🛡️ 全功能企业版 (默认)
    fullLogger := logger.New()
    fullLogger.Info("Full featured logging")
    
    // 🎯 使用现有的Context ID管理
    ctx := context.Background()
    
    // 直接使用日志记录(结构化字段通过WithField添加)
    fullLogger.WithField("trace_id", "trace-123").
               WithField("user_id", "user-456").
               Info("带上下文的日志")
    
    // 🔌 自定义上下文提取器 (灵活提取链路信息)
    ctx = context.WithValue(ctx, "trace_id", "trace-12345")
    ctx = context.WithValue(ctx, "request_id", "req-67890")
    
    // 使用默认提取器
    ultraLogger.InfoContext(ctx, "用户登录成功")
    // 输出: [TraceID=trace-12345 RequestID=req-67890] 用户登录成功
    
    // 自定义提取器(详见文档)
    extractor := logger.NewContextExtractorBuilder().
        AddTraceID().
        AddRequestID().
        AddContextValue("user_id", "User").
        Build()
    ultraLogger.SetContextExtractor(extractor)
}

🤝 社区贡献

我们欢迎各种形式的贡献!请遵循以下指南:

提交代码
  1. Fork 项目

    git clone https://github.com/kamalyes/go-logger.git
    cd go-logger
    
  2. 创建特性分支

    git checkout -b feature/your-amazing-feature
    
  3. 编写代码和测试

    • 确保新功能有完整的测试套件
    • 运行 go test ./... 确保所有测试通过
    • 保持代码覆盖率 > 90%
  4. 提交更改

    git commit -m 'feat: add amazing new feature'
    
  5. 推送并创建 Pull Request

    git push origin feature/your-amazing-feature
    
代码规范
  • 遵循 Go 官方代码风格
  • 使用有意义的函数和变量名
  • 添加必要的注释和文档
  • 使用测试套件编写测试
  • 确保并发安全
测试要求
  • 新功能必须有对应的测试套件
  • 测试覆盖率不得低于当前水平
  • 包含性能基准测试(如适用)
  • 验证并发安全性

📊 性能基准

最新性能测试结果:

BenchmarkUltraFastLogger-8       157894737     7.56 ns/op     0 B/op     0 allocs/op
BenchmarkStandardLogger-8         52631578    22.85 ns/op     8 B/op     1 allocs/op
BenchmarkMemoryMonitor-8           9803921   122.4 ns/op    48 B/op     2 allocs/op

详细性能分析请参考 性能文档

⭐ Star 历史

Star History Chart

许可证

该项目使用 MIT 许可证,详见 LICENSE 文件

Documentation

Overview

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-07 00:00:00 * @FilePath: \go-logger\adapters.go * @Description: 第三方日志库适配器和管理器 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-07 00:00:00 * @FilePath: \go-logger\config.go * @Description: 日志配置 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-24 10:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-24 11:00:00 * @FilePath: \go-logger\context_extractors.go * @Description: 预定义的上下文提取器和辅助函数 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-22 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-22 09:21:28 * @FilePath: \go-logger\context_logger.go * @Description: 上下文日志集成 - 统一入口设计 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-22 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-22 09:53:31 * @FilePath: \go-logger\context_service.go * @Description: Trace 上下文管理器测试 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-09-18 11:15:58 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-09 09:29:33 * @FilePath: \go-logger\empty.go * @Description: 空日志实现,用于禁用日志输出的场景 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-07 00:00:00 * @FilePath: \go-logger\errors.go * @Description: 统一的错误处理包 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-08 02:03:28 * @FilePath: \go-logger\factory.go * @Description: 工厂模式 - 统一管理各种组件的创建 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-07 00:00:00 * @FilePath: \go-logger\formatter.go * @Description: 日志格式化器实现 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-07 00:00:00 * @FilePath: \go-logger\hooks.go * @Description: 日志钩子系统实现 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-09 16:00:00 * @FilePath: \go-logger\interfaces.go * @Description: 日志接口定义 - 增强版本,支持多种日志框架的参数格式 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-22 12:33:32 * @FilePath: \go-logger\level.go * @Description: 统一的日志级别定义和管理 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-09 09:42:37 * @FilePath: \go-logger\logger.go * @Description: 统一的日志工具包,支持 emoji 和结构化日志 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-07 00:00:00 * @FilePath: \go-logger\specialty.go * @Description: 特殊场景的日志方法 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-09 16:30:00 * @FilePath: \go-logger\standard_adapter.go * @Description: 标准库日志适配器实现 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-08 02:07:30 * @FilePath: \go-logger\types.go * @Description: 核心类型定义 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-09 16:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-24 10:19:58 * @FilePath: \go-logger\ultra_fast_logger.go * @Description: 极致性能优化的日志实现 - 零拷贝、对象池、内联优化 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-07 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-07 23:19:49 * @FilePath: \go-logger\writer.go * @Description: 日志输出器实现 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

Index

Constants

View Source
const (
	ColorBlack   = "\033[30m"
	ColorRed     = "\033[31m"
	ColorGreen   = "\033[32m"
	ColorYellow  = "\033[33m"
	ColorBlue    = "\033[34m"
	ColorMagenta = "\033[35m"
	ColorCyan    = "\033[36m"
	ColorWhite   = "\033[37m"
	ColorGray    = "\033[90m"

	// 亮色版本
	ColorBrightRed     = "\033[91m"
	ColorBrightGreen   = "\033[92m"
	ColorBrightYellow  = "\033[93m"
	ColorBrightBlue    = "\033[94m"
	ColorBrightMagenta = "\033[95m"
	ColorBrightCyan    = "\033[96m"
	ColorBrightWhite   = "\033[97m"
)

预定义颜色常量

View Source
const ColorReset = "\033[0m"

ColorReset 颜色重置代码

Variables

View Source
var (
	SuccessType     = SpecialLogType{"✅", "SUCCESS"}
	LoadingType     = SpecialLogType{"⏳", "LOADING"}
	ConfigType      = SpecialLogType{"⚙️", "CONFIG"}
	StartType       = SpecialLogType{"🚀", "START"}
	StopType        = SpecialLogType{"🛑", "STOP"}
	DatabaseType    = SpecialLogType{"💾", "DATABASE"}
	NetworkType     = SpecialLogType{"🌐", "NETWORK"}
	SecurityType    = SpecialLogType{"🔒", "SECURITY"}
	CacheType       = SpecialLogType{"🗄️", "CACHE"}
	EnvironmentType = SpecialLogType{"🌍", "ENV"}
)

特殊日志类型定义

View Source
var AllLevels = HookLevel{DEBUG, INFO, WARN, ERROR, FATAL}

AllLevels 所有级别

View Source
var ErrorLevels = HookLevel{ERROR, FATAL}

ErrorLevels 错误级别

View Source
var GlobalLevel = struct {
	// Set 设置全局级别
	Set func(level LogLevel)
	// Get 获取全局级别
	Get func() LogLevel
	// SetComponent 设置组件级别
	SetComponent func(component string, level LogLevel)
	// GetComponent 获取组件级别
	GetComponent func(component string) LogLevel
	// SetPackage 设置包级别
	SetPackage func(pkg string, level LogLevel)
	// GetPackage 获取包级别
	GetPackage func(pkg string) LogLevel
	// IsEnabled 检查级别是否启用
	IsEnabled func(level LogLevel, component, pkg string) bool
	// GetEffective 获取有效级别
	GetEffective func(component, pkg string) LogLevel
	// RecordUsage 记录级别使用
	RecordUsage func(level LogLevel)
	// GetStats 获取级别统计
	GetStats func(level LogLevel) *LevelStats
}{
	Set: func(level LogLevel) {
		GetLevelManager().SetGlobalLevel(level)
	},
	Get: func() LogLevel {
		return GetLevelManager().GetGlobalLevel()
	},
	SetComponent: func(component string, level LogLevel) {
		GetLevelManager().SetComponentLevel(component, level)
	},
	GetComponent: func(component string) LogLevel {
		return GetLevelManager().GetComponentLevel(component)
	},
	SetPackage: func(pkg string, level LogLevel) {
		GetLevelManager().SetPackageLevel(pkg, level)
	},
	GetPackage: func(pkg string) LogLevel {
		return GetLevelManager().GetPackageLevel(pkg)
	},
	IsEnabled: func(level LogLevel, component, pkg string) bool {
		return GetLevelManager().IsLevelEnabled(level, component, pkg)
	},
	GetEffective: func(component, pkg string) LogLevel {
		return GetLevelManager().GetEffectiveLevel(component, pkg)
	},
	RecordUsage: func(level LogLevel) {
		GetLevelManager().RecordLevelUsage(level)
	},
	GetStats: func(level LogLevel) *LevelStats {
		return GetLevelManager().GetLevelStats(level)
	},
}

GlobalLevel 全局级别管理接口

View Source
var WarnLevels = HookLevel{WARN, ERROR, FATAL}

WarnLevels 警告级别

Functions

func AddErrorHook

func AddErrorHook(hook func(*AppError))

AddErrorHook 添加全局错误处理钩子

func Audit

func Audit(action string, user string, resource string, result string)

Audit 审计日志

func Cache

func Cache(format string, args ...interface{})

Cache 缓存日志

func ConfigLogger

func ConfigLogger(format string, args ...interface{})

ConfigLogger 配置日志

func CreateSpan added in v0.4.0

func CreateSpan(ctx context.Context, operation string) context.Context

func Database

func Database(format string, args ...interface{})

Database 数据库日志

func Debug

func Debug(format string, args ...interface{})

全局方法

func DebugWithContext added in v0.4.0

func DebugWithContext(ctx context.Context, logger ILogger, msg string, kvs ...interface{})

func EndCorrelationChain added in v0.4.0

func EndCorrelationChain(chain *CorrelationChain)

func EndOperation added in v0.4.0

func EndOperation(ctx context.Context, baseLogger ILogger, chain *CorrelationChain, keysAndValues ...interface{})

EndOperation 结束一个操作并记录

func Environment

func Environment(format string, args ...interface{})

Environment 环境日志

func Error

func Error(format string, args ...interface{})

func ErrorWithContext added in v0.4.0

func ErrorWithContext(ctx context.Context, logger ILogger, msg string, kvs ...interface{})

func ExtractFields added in v0.4.0

func ExtractFields(ctx context.Context) map[string]interface{}

func FastMemory added in v0.4.0

func FastMemory() uint64

FastMemory 全局内存检查

func Fatal

func Fatal(format string, args ...interface{})

func FatalWithContext added in v0.4.0

func FatalWithContext(ctx context.Context, logger ILogger, msg string, kvs ...interface{})

func GenerateCorrelationID added in v0.4.0

func GenerateCorrelationID() string

func GenerateRequestID added in v0.4.0

func GenerateRequestID() string

func GenerateSpanID added in v0.4.0

func GenerateSpanID() string

func GenerateTraceID added in v0.4.0

func GenerateTraceID() string

func GetAllCategories added in v0.4.0

func GetAllCategories() []string

GetAllCategories 获取所有类别

func GetAllLevelNames added in v0.4.0

func GetAllLevelNames() []string

GetAllLevelNames 获取所有级别名称(包括扩展级别)

func GetCorrelationID added in v0.4.0

func GetCorrelationID(ctx context.Context) string

func GetLevelNames

func GetLevelNames() []string

GetLevelNames 获取基础级别名称 (保持向后兼容)

func GetLevelShortNames added in v0.4.0

func GetLevelShortNames() []string

GetLevelShortNames 获取所有级别短名称

func GetOrGenerateTraceID added in v0.4.0

func GetOrGenerateTraceID(ctx context.Context) (context.Context, string)

func GetRequestID added in v0.4.0

func GetRequestID(ctx context.Context) string

func GetSessionID added in v0.4.0

func GetSessionID(ctx context.Context) string

func GetSpanID added in v0.4.0

func GetSpanID(ctx context.Context) string

func GetString added in v0.4.0

func GetString(ctx context.Context, key ContextKey) string

func GetTenantID added in v0.4.0

func GetTenantID(ctx context.Context) string

func GetTraceID added in v0.4.0

func GetTraceID(ctx context.Context) string

func GetUserID added in v0.4.0

func GetUserID(ctx context.Context) string

func GetValue added in v0.4.0

func GetValue(ctx context.Context, key ContextKey) interface{}

func HandleError

func HandleError(err error)

HandleError 使用全局错误处理器处理错误

func Health

func Health(service string, status bool, details string)

Health 健康检查日志

func Info

func Info(format string, args ...interface{})

func InfoWithContext added in v0.4.0

func InfoWithContext(ctx context.Context, logger ILogger, msg string, kvs ...interface{})

func InitErrorHandler

func InitErrorHandler(logger ILogger)

InitErrorHandler 初始化全局错误处理器

func IsEmptyLogger

func IsEmptyLogger(logger ILogger) bool

IsEmptyLogger 检查给定的logger是否是空日志实现

func IsError

func IsError(err error, code ErrorCode) bool

IsError 检查错误是否为指定的错误代码

func Loading

func Loading(format string, args ...interface{})

Loading 加载日志

func LogWithContext added in v0.4.0

func LogWithContext(ctx context.Context, baseLogger ILogger, level interface{}, msg string, keysAndValues ...interface{})

LogWithContext 统一的日志记录入口

func Milestone

func Milestone(message string)

Milestone 里程碑日志

func Network

func Network(format string, args ...interface{})

Network 网络日志

func NoOpContextExtractor added in v0.4.1

func NoOpContextExtractor(ctx context.Context) string

NoOpContextExtractor 空操作提取器,不提取任何上下文信息

func Performance

func Performance(operation string, duration time.Duration)

Performance 性能日志

func PerformanceWithDetails

func PerformanceWithDetails(operation string, duration time.Duration, details map[string]interface{})

PerformanceWithDetails 带详细信息的性能日志

func Progress

func Progress(current, total int, operation string)

Progress 进度日志

func QuickCheck added in v0.4.0

func QuickCheck() (bool, string)

QuickCheck 全局健康检查

func Security

func Security(format string, args ...interface{})

Security 安全日志

func SetGlobalConfig

func SetGlobalConfig(config *LogConfig)

SetGlobalConfig 设置全局配置

func SetGlobalFactory

func SetGlobalFactory(factory *LoggerFactory)

SetGlobalFactory 设置全局工厂实例

func SetGlobalLevel

func SetGlobalLevel(level LogLevel)

SetGlobalLevel 设置全局日志级别

func SetGlobalShowCaller

func SetGlobalShowCaller(show bool)

SetGlobalShowCaller 设置全局是否显示调用者信息

func SetThreshold added in v0.4.0

func SetThreshold(mb uint64)

SetThreshold 设置全局阈值

func SimpleRequestIDExtractor added in v0.4.1

func SimpleRequestIDExtractor(ctx context.Context) string

SimpleRequestIDExtractor 只提取 RequestID

func SimpleTraceIDExtractor added in v0.4.1

func SimpleTraceIDExtractor(ctx context.Context) string

SimpleTraceIDExtractor 只提取 TraceID

func Start

func Start(format string, args ...interface{})

Start 启动日志

func Stop

func Stop(format string, args ...interface{})

Stop 停止日志

func Success

func Success(format string, args ...interface{})

Success 成功日志

func TraceWithContext added in v0.4.0

func TraceWithContext(ctx context.Context, logger ILogger, msg string, kvs ...interface{})

便捷函数 - 所有日志级别都通过统一入口

func Track added in v0.4.0

func Track() func(error)

Track 全局追踪

func Update added in v0.4.0

func Update(heap uint64) bool

Update 全局内存更新

func Warn

func Warn(format string, args ...interface{})

func WarnWithContext added in v0.4.0

func WarnWithContext(ctx context.Context, logger ILogger, msg string, kvs ...interface{})

func WithCorrelation added in v0.4.0

func WithCorrelation(ctx context.Context, baseLogger ILogger) (ILogger, *CorrelationChain)

WithCorrelation 创建带相关性链的日志记录器

func WithCorrelationID added in v0.4.0

func WithCorrelationID(ctx context.Context, id string) context.Context

func WithRequestID added in v0.4.0

func WithRequestID(ctx context.Context, id string) context.Context

func WithSessionID added in v0.4.0

func WithSessionID(ctx context.Context, id string) context.Context

func WithSpanID added in v0.4.0

func WithSpanID(ctx context.Context, id string) context.Context

func WithTenantID added in v0.4.0

func WithTenantID(ctx context.Context, id string) context.Context

func WithTraceID added in v0.4.0

func WithTraceID(ctx context.Context, id string) context.Context

ID 操作便捷函数

func WithUserID added in v0.4.0

func WithUserID(ctx context.Context, id string) context.Context

func WithValue added in v0.4.0

func WithValue(ctx context.Context, key ContextKey, val interface{}) context.Context

Types

type AdapterConfig

type AdapterConfig struct {
	// 基础配置
	Type   AdapterType `json:"type" yaml:"type"`
	Name   string      `json:"name" yaml:"name"`
	Level  LogLevel    `json:"level" yaml:"level"`
	Output io.Writer   `json:"-" yaml:"-"`

	// 文件配置
	File       string `json:"file,omitempty" yaml:"file,omitempty"`
	MaxSize    int    `json:"max_size,omitempty" yaml:"max_size,omitempty"` // MB
	MaxBackups int    `json:"max_backups,omitempty" yaml:"max_backups,omitempty"`
	MaxAge     int    `json:"max_age,omitempty" yaml:"max_age,omitempty"` // days
	Compress   bool   `json:"compress,omitempty" yaml:"compress,omitempty"`

	// 格式化配置
	Format     string `json:"format,omitempty" yaml:"format,omitempty"` // json, text, xml, csv
	TimeFormat string `json:"time_format,omitempty" yaml:"time_format,omitempty"`
	Colorful   bool   `json:"colorful,omitempty" yaml:"colorful,omitempty"`
	ShowCaller bool   `json:"show_caller,omitempty" yaml:"show_caller,omitempty"`

	// 性能配置
	BufferSize   int           `json:"buffer_size,omitempty" yaml:"buffer_size,omitempty"`
	AsyncWrite   bool          `json:"async_write,omitempty" yaml:"async_write,omitempty"`
	BatchSize    int           `json:"batch_size,omitempty" yaml:"batch_size,omitempty"`
	BatchTimeout time.Duration `json:"batch_timeout,omitempty" yaml:"batch_timeout,omitempty"`

	// 网络配置(用于网络适配器)
	Network NetworkAdapterConfig `json:"network,omitempty" yaml:"network,omitempty"`

	// 字段配置
	Fields map[string]interface{} `json:"fields,omitempty" yaml:"fields,omitempty"`

	// Elasticsearch配置(用于ES适配器)
	Elasticsearch ElasticsearchAdapterConfig `json:"elasticsearch,omitempty" yaml:"elasticsearch,omitempty"`

	// 钩子配置
	Hooks []HookConfig `json:"hooks,omitempty" yaml:"hooks,omitempty"`

	// 中间件配置
	Middlewares []MiddlewareConfig `json:"middlewares,omitempty" yaml:"middlewares,omitempty"`
}

AdapterConfig 适配器配置

func DefaultAdapterConfig

func DefaultAdapterConfig() *AdapterConfig

DefaultAdapterConfig 创建默认适配器配置

func (*AdapterConfig) Validate

func (c *AdapterConfig) Validate() error

Validate 验证适配器配置

type AdapterFactory

type AdapterFactory func(config *AdapterConfig) (IAdapter, error)

AdapterFactory 适配器工厂函数

type AdapterRegistry

type AdapterRegistry struct {
	// contains filtered or unexported fields
}

AdapterRegistry 适配器注册表

func NewAdapterRegistry

func NewAdapterRegistry() *AdapterRegistry

NewAdapterRegistry 创建适配器注册表

func (*AdapterRegistry) Create

func (r *AdapterRegistry) Create(name string, config *AdapterConfig) (IAdapter, error)

Create 创建适配器

func (*AdapterRegistry) List

func (r *AdapterRegistry) List() []string

List 列出所有注册的适配器

func (*AdapterRegistry) Register

func (r *AdapterRegistry) Register(name string, factory AdapterFactory)

Register 注册适配器工厂

type AdapterType

type AdapterType string

AdapterType 适配器类型

const (
	StandardAdapter AdapterType = "standard" // 标准库适配器
	LogrusAdapter   AdapterType = "logrus"   // Logrus适配器 (需要额外安装)
	ZapAdapter      AdapterType = "zap"      // Zap适配器 (需要额外安装)
	ZerologAdapter  AdapterType = "zerolog"  // Zerolog适配器 (需要额外安装)
)

type AppError

type AppError struct {
	Code     ErrorCode              `json:"code"`
	Message  string                 `json:"message"`
	Details  string                 `json:"details"`
	Cause    error                  `json:"-"`
	File     string                 `json:"file"`
	Line     int                    `json:"line"`
	Function string                 `json:"function"`
	Context  map[string]interface{} `json:"context,omitempty"`
}

AppError 应用错误

func NewAlreadyExists

func NewAlreadyExists(resource string) *AppError

NewAlreadyExists 创建已存在错误

func NewConfigError

func NewConfigError(code ErrorCode, path string) *AppError

NewConfigError 创建配置相关错误

func NewError

func NewError(code ErrorCode, details string) *AppError

NewError 创建新的应用错误

func NewErrorf

func NewErrorf(code ErrorCode, format string, args ...interface{}) *AppError

NewErrorf 创建带格式化详情的应用错误

func NewFileError

func NewFileError(code ErrorCode, filepath string) *AppError

NewFileError 创建文件相关错误

func NewInvalidInput

func NewInvalidInput(details string) *AppError

NewInvalidInput 创建无效输入错误

func NewLoggerError

func NewLoggerError(code ErrorCode, component string) *AppError

NewLoggerError 创建日志器相关错误

func NewNotFound

func NewNotFound(resource string) *AppError

NewNotFound 创建未找到错误

func NewPermissionDenied

func NewPermissionDenied(action string) *AppError

NewPermissionDenied 创建权限拒绝错误

func NewTimeout

func NewTimeout(operation string, duration string) *AppError

NewTimeout 创建超时错误

func WrapError

func WrapError(code ErrorCode, details string, cause error) *AppError

WrapError 包装已有错误

func WrapErrorf

func WrapErrorf(code ErrorCode, cause error, format string, args ...interface{}) *AppError

WrapErrorf 包装已有错误,带格式化详情

func (*AppError) Error

func (e *AppError) Error() string

Error 实现error接口

func (*AppError) String

func (e *AppError) String() string

String 返回详细的错误信息

func (*AppError) Unwrap

func (e *AppError) Unwrap() error

Unwrap 返回原始错误

func (*AppError) WithContext

func (e *AppError) WithContext(key string, value interface{}) *AppError

WithContext 添加上下文信息

type AuthConfig added in v0.4.0

type AuthConfig struct {
	Type     string            `json:"type" yaml:"type"` // basic, bearer, api_key
	Username string            `json:"username" yaml:"username"`
	Password string            `json:"password" yaml:"password"`
	Token    string            `json:"token" yaml:"token"`
	APIKey   string            `json:"api_key" yaml:"api_key"`
	Headers  map[string]string `json:"headers" yaml:"headers"`
}

AuthConfig 认证配置

type BaseFormatter

type BaseFormatter struct {
	TimeFormat   string            `json:"time_format"`
	ShowCaller   bool              `json:"show_caller"`
	ShowLevel    bool              `json:"show_level"`
	ShowEmoji    bool              `json:"show_emoji"`
	Colorful     bool              `json:"colorful"`
	PrettyPrint  bool              `json:"pretty_print"`
	CustomFields map[string]string `json:"custom_fields"`
}

BaseFormatter 基础格式化器

func NewBaseFormatter

func NewBaseFormatter() *BaseFormatter

NewBaseFormatter 创建基础格式化器

type BaseHook

type BaseHook struct {
	Name    string `json:"name"`
	Enabled bool   `json:"enabled"`

	Async   bool          `json:"async"`
	Timeout time.Duration `json:"timeout"`
	// contains filtered or unexported fields
}

BaseHook 基础钩子

func NewBaseHook

func NewBaseHook(name string, levels HookLevel) *BaseHook

NewBaseHook 创建基础钩子

func (*BaseHook) IsEnabled

func (h *BaseHook) IsEnabled() bool

IsEnabled 检查钩子是否启用

func (*BaseHook) Levels

func (h *BaseHook) Levels() []LogLevel

Levels 返回支持的日志级别

func (*BaseHook) SetEnabled

func (h *BaseHook) SetEnabled(enabled bool)

SetEnabled 设置钩子启用状态

func (*BaseHook) SupportsLevel

func (h *BaseHook) SupportsLevel(level LogLevel) bool

SupportsLevel 检查是否支持指定级别

type BaseWriter

type BaseWriter struct {
	Level   LogLevel     `json:"level"`
	Healthy bool         `json:"healthy"`
	Stats   *WriterStats `json:"-"`
	// contains filtered or unexported fields
}

BaseWriter 基础输出器

type BufferPool

type BufferPool struct {
	// contains filtered or unexported fields
}

BufferPool 缓冲区池

func NewBufferPool

func NewBufferPool() *BufferPool

NewBufferPool 创建缓冲区池

func (*BufferPool) Get

func (bp *BufferPool) Get() []byte

Get 获取缓冲区

func (*BufferPool) Put

func (bp *BufferPool) Put(buf []byte)

Put 归还缓冲区

type BufferedWriter

type BufferedWriter struct {
	BaseWriter
	// contains filtered or unexported fields
}

BufferedWriter 缓冲输出器

func (*BufferedWriter) Close

func (w *BufferedWriter) Close() error

Close 关闭输出器

func (*BufferedWriter) Flush

func (w *BufferedWriter) Flush() error

Flush 刷新缓冲区

func (*BufferedWriter) GetStats

func (w *BufferedWriter) GetStats() interface{}

GetStats 获取统计信息

func (*BufferedWriter) IsHealthy

func (w *BufferedWriter) IsHealthy() bool

IsHealthy 检查健康状态

func (*BufferedWriter) Write

func (w *BufferedWriter) Write(p []byte) (n int, err error)

Write 实现io.Writer接口

func (*BufferedWriter) WriteLevel

func (w *BufferedWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)

WriteLevel 按级别写入

type CPUStats added in v0.4.0

type CPUStats struct {
	Usage             float64   `json:"usage"`        // CPU使用率 (%)
	UserTime          float64   `json:"user_time"`    // 用户CPU时间 (秒)
	SystemTime        float64   `json:"system_time"`  // 系统CPU时间 (秒)
	IdleTime          float64   `json:"idle_time"`    // 空闲CPU时间 (秒)
	LoadAverage       float64   `json:"load_average"` // 负载平均值
	Cores             int       `json:"cores"`        // CPU核心数
	Threshold         float64   `json:"threshold"`    // CPU阈值 (%)
	ThresholdExceeded uint64    `json:"threshold_exceeded"`
	History           []float64 `json:"history"` // 历史数据
}

CPUStats CPU统计

type CSVLogFormatter

type CSVLogFormatter struct {
	*BaseFormatter
	Headers   []string `json:"headers"`
	Delimiter string   `json:"delimiter"`
}

CSVLogFormatter CSV格式化器

func (*CSVLogFormatter) Format

func (f *CSVLogFormatter) Format(entry *LogEntry) ([]byte, error)

Format 格式化日志条目

func (*CSVLogFormatter) GetName

func (f *CSVLogFormatter) GetName() string

GetName 获取格式化器名称

type CallerInfo

type CallerInfo struct {
	File     string `json:"file"`
	Line     int    `json:"line"`
	Function string `json:"function"`
}

CallerInfo 调用者信息

func GetCallerInfo

func GetCallerInfo(skip int) *CallerInfo

GetCallerInfo 获取调用者信息

type ComponentFactory

type ComponentFactory interface {
	GetName() string
	GetVersion() string
	CreateComponent(config interface{}) (interface{}, error)
	ValidateConfig(config interface{}) error
}

ComponentFactory 组件工厂接口

type Config added in v0.4.0

type Config struct {
	// 基础设置
	Level      LogLevel   `json:"level" yaml:"level"`
	Output     io.Writer  `json:"-" yaml:"-"`
	TimeFormat TimeFormat `json:"time_format" yaml:"time_format"`
	Colorful   bool       `json:"colorful" yaml:"colorful"`

	// 性能设置
	BufferSize   int           `json:"buffer_size" yaml:"buffer_size"`
	AsyncWrite   bool          `json:"async_write" yaml:"async_write"`
	PoolSize     int           `json:"pool_size" yaml:"pool_size"`
	BatchSize    int           `json:"batch_size" yaml:"batch_size"`
	BatchTimeout time.Duration `json:"batch_timeout" yaml:"batch_timeout"`

	// 企业功能
	EnableMemoryStats bool `json:"enable_memory_stats" yaml:"enable_memory_stats"`
	EnableDistributed bool `json:"enable_distributed" yaml:"enable_distributed"`
	EnableMetrics     bool `json:"enable_metrics" yaml:"enable_metrics"`
	EnableHooks       bool `json:"enable_hooks" yaml:"enable_hooks"`

	// 输出格式
	Format        FormatType `json:"format" yaml:"format"`
	TimestampKey  string     `json:"timestamp_key" yaml:"timestamp_key"`
	LevelKey      string     `json:"level_key" yaml:"level_key"`
	MessageKey    string     `json:"message_key" yaml:"message_key"`
	CallerKey     string     `json:"caller_key" yaml:"caller_key"`
	StacktraceKey string     `json:"stacktrace_key" yaml:"stacktrace_key"`

	// 字段设置
	Fields        map[string]interface{} `json:"fields" yaml:"fields"`
	ContextFields []string               `json:"context_fields" yaml:"context_fields"`

	// 调用者信息配置
	ShowCaller     bool `json:"show_caller" yaml:"show_caller"`
	CallerDepth    int  `json:"caller_depth" yaml:"caller_depth"`
	ShowStacktrace bool `json:"show_stacktrace" yaml:"show_stacktrace"`

	// 组件配置
	Adapters []AdapterConfig `json:"adapters" yaml:"adapters"`

	// 监控配置
	Monitoring MonitoringConfig `json:"monitoring" yaml:"monitoring"`
}

Config 主配置结构

func (*Config) Clone added in v0.4.0

func (c *Config) Clone() *Config

Clone 克隆配置

func (*Config) EnableMemoryMonitoring added in v0.4.0

func (c *Config) EnableMemoryMonitoring() *Config

EnableMemoryMonitoring 启用内存监控

func (*Config) EnableMonitoring added in v0.4.0

func (c *Config) EnableMonitoring() *Config

EnableMonitoring 启用监控

func (*Config) EnablePerformanceMonitoring added in v0.4.0

func (c *Config) EnablePerformanceMonitoring() *Config

EnablePerformanceMonitoring 启用性能监控

func (*Config) Validate added in v0.4.0

func (c *Config) Validate() error

Validate 验证配置

func (*Config) WithAsyncWrite added in v0.4.0

func (c *Config) WithAsyncWrite(async bool) *Config

WithAsyncWrite 设置是否异步写入

func (*Config) WithBufferSize added in v0.4.0

func (c *Config) WithBufferSize(size int) *Config

WithBufferSize 设置缓冲区大小

func (*Config) WithCallerDepth added in v0.4.0

func (c *Config) WithCallerDepth(depth int) *Config

WithCallerDepth 设置调用者深度

func (*Config) WithColorful added in v0.4.0

func (c *Config) WithColorful(colorful bool) *Config

WithColorful 设置是否使用彩色输出

func (*Config) WithField added in v0.4.0

func (c *Config) WithField(key string, value interface{}) *Config

WithField 添加单个字段

func (*Config) WithFields added in v0.4.0

func (c *Config) WithFields(fields map[string]interface{}) *Config

WithFields 设置额外字段

func (*Config) WithLevel added in v0.4.0

func (c *Config) WithLevel(level LogLevel) *Config

WithLevel 设置日志级别

func (*Config) WithOutput added in v0.4.0

func (c *Config) WithOutput(output io.Writer) *Config

WithOutput 设置输出目标

func (*Config) WithPoolSize added in v0.4.0

func (c *Config) WithPoolSize(size int) *Config

WithPoolSize 设置对象池大小

func (*Config) WithShowCaller added in v0.4.0

func (c *Config) WithShowCaller(show bool) *Config

WithShowCaller 设置是否显示调用者信息

func (*Config) WithTimeFormat added in v0.4.0

func (c *Config) WithTimeFormat(format TimeFormat) *Config

WithTimeFormat 设置时间格式

type ConsoleHook

type ConsoleHook struct {
	*BaseHook
	Prefix string `json:"prefix"`
	Color  bool   `json:"color"`
}

ConsoleHook 控制台钩子(用于特殊输出)

func (*ConsoleHook) Fire

func (h *ConsoleHook) Fire(entry *LogEntry) error

Fire 执行钩子

type ConsoleLogWriter

type ConsoleLogWriter struct {
	BaseWriter
	Output io.Writer `json:"-"`
	Color  bool      `json:"color"`
}

ConsoleLogWriter 控制台输出器

func (*ConsoleLogWriter) Close

func (w *ConsoleLogWriter) Close() error

Close 关闭输出器

func (*ConsoleLogWriter) Flush

func (w *ConsoleLogWriter) Flush() error

Flush 刷新缓冲区

func (*ConsoleLogWriter) GetStats

func (w *ConsoleLogWriter) GetStats() interface{}

GetStats 获取统计信息

func (*ConsoleLogWriter) IsHealthy

func (w *ConsoleLogWriter) IsHealthy() bool

IsHealthy 检查健康状态

func (*ConsoleLogWriter) Write

func (w *ConsoleLogWriter) Write(p []byte) (n int, err error)

Write 实现io.Writer接口

func (*ConsoleLogWriter) WriteLevel

func (w *ConsoleLogWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)

WriteLevel 按级别写入

type ContextExtractor added in v0.4.1

type ContextExtractor func(ctx context.Context) string

ContextExtractor 上下文信息提取器函数类型 用于从 context.Context 中提取自定义信息(如 TraceID、RequestID 等)

func CachedContextExtractor added in v0.4.1

func CachedContextExtractor(cacheKey string, extractor ContextExtractor) ContextExtractor

CachedContextExtractor 缓存提取器 在同一个 context 中只提取一次,结果缓存在 context 中

func ChainContextExtractors added in v0.4.1

func ChainContextExtractors(extractors ...ContextExtractor) ContextExtractor

ChainContextExtractors 链接多个提取器 按顺序调用所有提取器,并合并结果

func ConditionalContextExtractor added in v0.4.1

func ConditionalContextExtractor(condition func(context.Context) bool, extractor ContextExtractor) ContextExtractor

ConditionalContextExtractor 条件提取器 只有当条件函数返回 true 时才调用提取器

func CustomFieldExtractor added in v0.4.1

func CustomFieldExtractor(contextKeys []string, metadataKeys []string) ContextExtractor

CustomFieldExtractor 自定义字段提取器生成器 用于从 context 中提取指定的字段

func ExtractFromContextValue added in v0.4.1

func ExtractFromContextValue(key string, label string) ContextExtractor

ExtractFromContextValue 从 context.Value 提取指定键的值

func ExtractFromGRPCMetadata added in v0.4.1

func ExtractFromGRPCMetadata(key string, label string) ContextExtractor

ExtractFromGRPCMetadata 从 gRPC metadata 提取指定键的值

func GetDefaultPresetExtractor added in v0.4.1

func GetDefaultPresetExtractor() ContextExtractor

GetDefaultPresetExtractor 获取默认预设提取器 提取: TraceID, RequestID

func GetFullPresetExtractor added in v0.4.1

func GetFullPresetExtractor() ContextExtractor

GetFullPresetExtractor 获取完整预设提取器 提取所有标准字段

func GetGRPCPresetExtractor added in v0.4.1

func GetGRPCPresetExtractor() ContextExtractor

GetGRPCPresetExtractor 获取 gRPC 预设提取器 从 gRPC metadata 提取: TraceID, RequestID, UserID, TenantID

func GetGatewayPresetExtractor added in v0.4.1

func GetGatewayPresetExtractor() ContextExtractor

GetGatewayPresetExtractor 获取网关预设提取器 提取: TraceID, RequestID, UserID, TenantID

func GetPresetExtractor added in v0.4.1

func GetPresetExtractor(presetType PresetExtractorType) ContextExtractor

GetPresetExtractor 获取预设的上下文提取器

func GetServicePresetExtractor added in v0.4.1

func GetServicePresetExtractor() ContextExtractor

GetServicePresetExtractor 获取服务预设提取器 提取: TraceID, RequestID, UserID, TenantID

func GetWebSocketPresetExtractor added in v0.4.1

func GetWebSocketPresetExtractor() ContextExtractor

GetWebSocketPresetExtractor 获取 WebSocket 预设提取器 提取: TraceID, UserID, SessionID

func PrefixedContextExtractor added in v0.4.1

func PrefixedContextExtractor(prefix string, extractor ContextExtractor) ContextExtractor

PrefixedContextExtractor 带前缀的提取器 为提取的信息添加自定义前缀

type ContextExtractorBuilder added in v0.4.1

type ContextExtractorBuilder struct {
	// contains filtered or unexported fields
}

CreateContextExtractor 创建自定义上下文提取器的构建器

func NewContextExtractorBuilder added in v0.4.1

func NewContextExtractorBuilder() *ContextExtractorBuilder

NewContextExtractorBuilder 创建新的提取器构建器

func (*ContextExtractorBuilder) AddContextValue added in v0.4.1

func (b *ContextExtractorBuilder) AddContextValue(key, label string) *ContextExtractorBuilder

AddContextValue 添加从 context.Value 提取的字段

func (*ContextExtractorBuilder) AddExtractor added in v0.4.1

AddExtractor 添加提取器

func (*ContextExtractorBuilder) AddGRPCMetadata added in v0.4.1

func (b *ContextExtractorBuilder) AddGRPCMetadata(key, label string) *ContextExtractorBuilder

AddGRPCMetadata 添加从 gRPC metadata 提取的字段

func (*ContextExtractorBuilder) AddRequestID added in v0.4.1

AddRequestID 添加 RequestID 提取器

func (*ContextExtractorBuilder) AddTraceID added in v0.4.1

AddTraceID 添加 TraceID 提取器

func (*ContextExtractorBuilder) Build added in v0.4.1

Build 构建最终的提取器

type ContextKey added in v0.4.0

type ContextKey string

ContextKey 统一键类型

const (
	KeyTraceID       ContextKey = "trace_id"
	KeySpanID        ContextKey = "span_id"
	KeySessionID     ContextKey = "session_id"
	KeyUserID        ContextKey = "user_id"
	KeyRequestID     ContextKey = "request_id"
	KeyCorrelationID ContextKey = "correlation_id"
	KeyOperation     ContextKey = "operation"
	KeyTenantID      ContextKey = "tenant_id"
)

常用键定义

type ContextLogger added in v0.4.0

type ContextLogger struct {
	// contains filtered or unexported fields
}

ContextLogger 上下文日志门面 - 统一入口

func NewContextLogger added in v0.4.0

func NewContextLogger(ctx context.Context, logger ILogger) *ContextLogger

NewContextLogger 创建上下文日志记录器(统一入口)

func (*ContextLogger) Debug added in v0.4.0

func (cl *ContextLogger) Debug(msg string, kvs ...interface{})

func (*ContextLogger) Error added in v0.4.0

func (cl *ContextLogger) Error(msg string, kvs ...interface{})

func (*ContextLogger) Fatal added in v0.4.0

func (cl *ContextLogger) Fatal(msg string, kvs ...interface{})

func (*ContextLogger) Info added in v0.4.0

func (cl *ContextLogger) Info(msg string, kvs ...interface{})

func (*ContextLogger) Log added in v0.4.0

func (cl *ContextLogger) Log(level string, msg string, keysAndValues ...interface{})

Log 统一的日志记录入口

func (*ContextLogger) Trace added in v0.4.0

func (cl *ContextLogger) Trace(msg string, kvs ...interface{})

Trace/Debug/Info/Warn/Error/Fatal 便捷方法

func (*ContextLogger) Warn added in v0.4.0

func (cl *ContextLogger) Warn(msg string, kvs ...interface{})

type ContextService added in v0.4.0

type ContextService struct {
	// contains filtered or unexported fields
}

ContextService 单一核心服务

func NewContextService added in v0.4.0

func NewContextService(gen idgen.IDGenerator) *ContextService

NewContextService 创建服务

func (*ContextService) CreateCorrelationChain added in v0.4.0

func (cs *ContextService) CreateCorrelationChain(ctx context.Context) (*CorrelationChain, context.Context)

CreateCorrelationChain 创建相关性链

func (*ContextService) CreateSpan added in v0.4.0

func (cs *ContextService) CreateSpan(ctx context.Context, operation string) context.Context

CreateSpan 创建 span (继承 trace, 新 spanID)

func (*ContextService) EndChain added in v0.4.0

func (cs *ContextService) EndChain(chain *CorrelationChain)

EndChain 结束相关性链

func (*ContextService) EnsureID added in v0.4.0

func (cs *ContextService) EnsureID(ctx context.Context, key ContextKey) (context.Context, string)

EnsureID 确保某个 ID 存在

func (*ContextService) ExtractFields added in v0.4.0

func (cs *ContextService) ExtractFields(ctx context.Context) map[string]interface{}

ExtractFields 提取已注册字段

type CorrelationChain added in v0.4.0

type CorrelationChain struct {
	ID        string
	TraceID   string
	StartTime time.Time
	EndTime   time.Time
	Tags      map[string]string
	Metrics   map[string]interface{}
	// contains filtered or unexported fields
}

CorrelationChain 简化后的相关链

func CreateCorrelationChain added in v0.4.0

func CreateCorrelationChain(ctx context.Context) (*CorrelationChain, context.Context)

Correlation 操作

func LogWithCorrelation added in v0.4.0

func LogWithCorrelation(ctx context.Context, baseLogger ILogger, lvl LogLevel, msg string, keysAndValues ...interface{}) *CorrelationChain

LogWithCorrelation 使用相关性链记录日志

func StartOperation added in v0.4.0

func StartOperation(ctx context.Context, baseLogger ILogger, operation string, keysAndValues ...interface{}) (context.Context, *CorrelationChain)

StartOperation 开始一个操作并记录

func (*CorrelationChain) GetDuration added in v0.4.0

func (c *CorrelationChain) GetDuration() time.Duration

func (*CorrelationChain) SetMetric added in v0.4.0

func (c *CorrelationChain) SetMetric(k string, v interface{})

func (*CorrelationChain) SetTag added in v0.4.0

func (c *CorrelationChain) SetTag(k, v string)

type DefaultMemoryMonitor added in v0.4.0

type DefaultMemoryMonitor struct {
	// contains filtered or unexported fields
}

DefaultMemoryMonitor 默认内存监控器实现

func NewDefaultMemoryMonitor added in v0.4.0

func NewDefaultMemoryMonitor() *DefaultMemoryMonitor

NewDefaultMemoryMonitor 创建一个具有默认设置的 DefaultMemoryMonitor

func (*DefaultMemoryMonitor) AnalyzeMemoryLeaks added in v0.4.0

func (mm *DefaultMemoryMonitor) AnalyzeMemoryLeaks() *MemoryLeakReport

AnalyzeMemoryLeaks 分析内存泄漏

func (*DefaultMemoryMonitor) Cleanup added in v0.4.0

func (mm *DefaultMemoryMonitor) Cleanup()

Cleanup 清理内存监控器

func (*DefaultMemoryMonitor) ForceGC added in v0.4.0

func (mm *DefaultMemoryMonitor) ForceGC()

ForceGC 强制执行GC

func (*DefaultMemoryMonitor) GetGCInfo added in v0.4.0

func (mm *DefaultMemoryMonitor) GetGCInfo() *GCInfo

GetGCInfo 获取GC信息

func (*DefaultMemoryMonitor) GetHeapInfo added in v0.4.0

func (mm *DefaultMemoryMonitor) GetHeapInfo() *HeapInfo

GetHeapInfo 获取堆信息

func (*DefaultMemoryMonitor) GetMemoryInfo added in v0.4.0

func (mm *DefaultMemoryMonitor) GetMemoryInfo() *MemoryInfo

GetMemoryInfo 获取当前内存信息

func (*DefaultMemoryMonitor) GetMemoryStats added in v0.4.0

func (mm *DefaultMemoryMonitor) GetMemoryStats() *MemoryStats

GetMemoryStats 获取内存统计

func (*DefaultMemoryMonitor) OnMemoryThresholdExceeded added in v0.4.0

func (mm *DefaultMemoryMonitor) OnMemoryThresholdExceeded(callback func(info *MemoryInfo))

OnMemoryThresholdExceeded 设置内存阈值超出回调

func (*DefaultMemoryMonitor) Optimize added in v0.4.0

func (mm *DefaultMemoryMonitor) Optimize()

Optimize 优化内存使用

func (*DefaultMemoryMonitor) SetGCPercent added in v0.4.0

func (mm *DefaultMemoryMonitor) SetGCPercent(percent int) int

SetGCPercent 设置GC百分比

func (*DefaultMemoryMonitor) SetMaxMemory added in v0.4.0

func (mm *DefaultMemoryMonitor) SetMaxMemory(maxBytes uint64)

SetMaxMemory 设置最大内存限制

func (*DefaultMemoryMonitor) SetMemoryThreshold added in v0.4.0

func (mm *DefaultMemoryMonitor) SetMemoryThreshold(threshold float64)

SetMemoryThreshold 设置内存阈值

func (*DefaultMemoryMonitor) Start added in v0.4.0

func (mm *DefaultMemoryMonitor) Start() error

Start 开始监控

func (*DefaultMemoryMonitor) Stop added in v0.4.0

func (mm *DefaultMemoryMonitor) Stop() error

Stop 停止监控

func (*DefaultMemoryMonitor) String added in v0.4.0

func (mm *DefaultMemoryMonitor) String() string

String 字符串表示

func (*DefaultMemoryMonitor) TakeHeapSnapshot added in v0.4.0

func (mm *DefaultMemoryMonitor) TakeHeapSnapshot() (*HeapSnapshot, error)

TakeHeapSnapshot 创建堆快照

type DefaultPerformanceMonitor added in v0.4.0

type DefaultPerformanceMonitor struct {
	// contains filtered or unexported fields
}

DefaultPerformanceMonitor 默认性能监控器实现

func NewDefaultPerformanceMonitor added in v0.4.0

func NewDefaultPerformanceMonitor() *DefaultPerformanceMonitor

NewDefaultPerformanceMonitor 创建默认性能监控器

func (*DefaultPerformanceMonitor) GetLatencyStats added in v0.4.0

func (pm *DefaultPerformanceMonitor) GetLatencyStats() *LatencyStats

GetLatencyStats 获取延迟统计

func (*DefaultPerformanceMonitor) GetPerformanceData added in v0.4.0

func (pm *DefaultPerformanceMonitor) GetPerformanceData() *PerformanceData

GetPerformanceData 获取性能数据

func (*DefaultPerformanceMonitor) GetResourceStats added in v0.4.0

func (pm *DefaultPerformanceMonitor) GetResourceStats() *ResourceStats

GetResourceStats 获取资源统计

func (*DefaultPerformanceMonitor) GetThroughputStats added in v0.4.0

func (pm *DefaultPerformanceMonitor) GetThroughputStats() *ThroughputStats

GetThroughputStats 获取吞吐量统计

func (*DefaultPerformanceMonitor) OnLatencyThresholdExceeded added in v0.4.0

func (pm *DefaultPerformanceMonitor) OnLatencyThresholdExceeded(callback func(operation string, latency time.Duration))

OnLatencyThresholdExceeded 设置延迟阈值超出回调

func (*DefaultPerformanceMonitor) OnResourceThresholdExceeded added in v0.4.0

func (pm *DefaultPerformanceMonitor) OnResourceThresholdExceeded(callback func(usage *ResourceUsage))

OnResourceThresholdExceeded 设置资源阈值超出回调

func (*DefaultPerformanceMonitor) OnThroughputThresholdExceeded added in v0.4.0

func (pm *DefaultPerformanceMonitor) OnThroughputThresholdExceeded(callback func(operation string, throughput float64))

OnThroughputThresholdExceeded 设置吞吐量阈值超出回调

func (*DefaultPerformanceMonitor) RecordLatency added in v0.4.0

func (pm *DefaultPerformanceMonitor) RecordLatency(operation string, latency time.Duration)

RecordLatency 记录延迟

func (*DefaultPerformanceMonitor) RecordResourceUsage added in v0.4.0

func (pm *DefaultPerformanceMonitor) RecordResourceUsage()

RecordResourceUsage 记录资源使用情况

func (*DefaultPerformanceMonitor) RecordThroughput added in v0.4.0

func (pm *DefaultPerformanceMonitor) RecordThroughput(operation string, count uint64)

RecordThroughput 记录吞吐量

func (*DefaultPerformanceMonitor) SetLatencyThreshold added in v0.4.0

func (pm *DefaultPerformanceMonitor) SetLatencyThreshold(operation string, threshold time.Duration)

SetLatencyThreshold 设置延迟阈值

func (*DefaultPerformanceMonitor) SetResourceThreshold added in v0.4.0

func (pm *DefaultPerformanceMonitor) SetResourceThreshold(cpu, memory float64)

SetResourceThreshold 设置资源阈值

func (*DefaultPerformanceMonitor) SetThroughputThreshold added in v0.4.0

func (pm *DefaultPerformanceMonitor) SetThroughputThreshold(operation string, threshold float64)

SetThroughputThreshold 设置吞吐量阈值

func (*DefaultPerformanceMonitor) Start added in v0.4.0

func (pm *DefaultPerformanceMonitor) Start() error

Start 开始监控

func (*DefaultPerformanceMonitor) Stop added in v0.4.0

func (pm *DefaultPerformanceMonitor) Stop() error

Stop 停止监控

type DefaultStatsCollector added in v0.4.0

type DefaultStatsCollector struct {
	// contains filtered or unexported fields
}

DefaultStatsCollector 默认统计收集器实现

func NewDefaultStatsCollector added in v0.4.0

func NewDefaultStatsCollector() *DefaultStatsCollector

NewDefaultStatsCollector 创建默认统计收集器

func (*DefaultStatsCollector) Cleanup added in v0.4.0

func (sc *DefaultStatsCollector) Cleanup(age time.Duration)

Cleanup 清理旧数据

func (*DefaultStatsCollector) GetErrorStats added in v0.4.0

func (sc *DefaultStatsCollector) GetErrorStats() *ErrorStats

GetErrorStats 获取错误统计

func (*DefaultStatsCollector) GetMetricStats added in v0.4.0

func (sc *DefaultStatsCollector) GetMetricStats(metric string) *MetricStats

GetMetricStats 获取特定指标统计

func (*DefaultStatsCollector) GetOperationStats added in v0.4.0

func (sc *DefaultStatsCollector) GetOperationStats(operation string) *OperationStats

GetOperationStats 获取特定操作统计

func (*DefaultStatsCollector) GetStats added in v0.4.0

func (sc *DefaultStatsCollector) GetStats() *Stats

GetStats 获取综合统计

func (*DefaultStatsCollector) Record added in v0.4.0

func (sc *DefaultStatsCollector) Record(operation string, duration time.Duration, size uint64)

Record 记录操作

func (*DefaultStatsCollector) RecordCount added in v0.4.0

func (sc *DefaultStatsCollector) RecordCount(metric string, value uint64)

RecordCount 记录计数指标

func (*DefaultStatsCollector) RecordError added in v0.4.0

func (sc *DefaultStatsCollector) RecordError(operation string, err error)

RecordError 记录错误

func (*DefaultStatsCollector) RecordGauge added in v0.4.0

func (sc *DefaultStatsCollector) RecordGauge(metric string, value float64)

RecordGauge 记录仪表指标

func (*DefaultStatsCollector) RecordHistogram added in v0.4.0

func (sc *DefaultStatsCollector) RecordHistogram(metric string, value float64)

RecordHistogram 记录直方图指标

func (*DefaultStatsCollector) Reset added in v0.4.0

func (sc *DefaultStatsCollector) Reset()

Reset 重置统计

func (*DefaultStatsCollector) SetMaxRecentErrors added in v0.4.0

func (sc *DefaultStatsCollector) SetMaxRecentErrors(max int)

SetMaxRecentErrors 设置最大最近错误数

func (*DefaultStatsCollector) SetPercentiles added in v0.4.0

func (sc *DefaultStatsCollector) SetPercentiles(percentiles []int)

SetPercentiles 设置百分位数

type ElasticsearchAdapterConfig added in v0.4.0

type ElasticsearchAdapterConfig struct {
	Addresses       []string      `json:"addresses" yaml:"addresses"`
	Index           string        `json:"index" yaml:"index"`
	DocType         string        `json:"doc_type" yaml:"doc_type"`
	Username        string        `json:"username" yaml:"username"`
	Password        string        `json:"password" yaml:"password"`
	CloudID         string        `json:"cloud_id" yaml:"cloud_id"`
	APIKey          string        `json:"api_key" yaml:"api_key"`
	Timeout         time.Duration `json:"timeout" yaml:"timeout"`
	RetryOnConflict int           `json:"retry_on_conflict" yaml:"retry_on_conflict"`
	BufferSize      int           `json:"buffer_size" yaml:"buffer_size"`
	FlushInterval   time.Duration `json:"flush_interval" yaml:"flush_interval"`
	TLS             TLSConfig     `json:"tls" yaml:"tls"`
}

ElasticsearchAdapterConfig Elasticsearch适配器配置

type EmailHook

type EmailHook struct {
	*BaseHook
	SMTPHost     string        `json:"smtp_host"`
	SMTPPort     string        `json:"smtp_port"`
	Username     string        `json:"username"`
	Password     string        `json:"password"`
	From         string        `json:"from"`
	To           []string      `json:"to"`
	Subject      string        `json:"subject"`
	BatchSize    int           `json:"batch_size"`
	FlushTimeout time.Duration `json:"flush_timeout"`
	// contains filtered or unexported fields
}

EmailHook 邮件钩子

func (*EmailHook) Fire

func (h *EmailHook) Fire(entry *LogEntry) error

Fire 执行钩子

type EmptyAdapter

type EmptyAdapter struct {
	*EmptyLogger
	// contains filtered or unexported fields
}

EmptyAdapter 是 IAdapter 接口的空实现

func NewEmptyAdapter

func NewEmptyAdapter(name string) *EmptyAdapter

NewEmptyAdapter 创建一个新的空适配器

func (*EmptyAdapter) Close

func (e *EmptyAdapter) Close() error

Close 关闭适配器(空实现)

func (*EmptyAdapter) Flush

func (e *EmptyAdapter) Flush() error

Flush 刷新缓冲区(空实现)

func (*EmptyAdapter) GetAdapterName

func (e *EmptyAdapter) GetAdapterName() string

GetAdapterName 获取适配器名称

func (*EmptyAdapter) GetAdapterVersion

func (e *EmptyAdapter) GetAdapterVersion() string

GetAdapterVersion 获取适配器版本

func (*EmptyAdapter) Initialize

func (e *EmptyAdapter) Initialize() error

Initialize 初始化适配器(空实现)

func (*EmptyAdapter) IsHealthy

func (e *EmptyAdapter) IsHealthy() bool

IsHealthy 检查适配器健康状态

func (*EmptyAdapter) SetHealthy

func (e *EmptyAdapter) SetHealthy(healthy bool)

SetHealthy 设置适配器健康状态

type EmptyFormatter

type EmptyFormatter struct {
	// contains filtered or unexported fields
}

EmptyFormatter 是 IFormatter 接口的空实现

func NewEmptyFormatter

func NewEmptyFormatter() *EmptyFormatter

NewEmptyFormatter 创建一个新的空格式化器

func (*EmptyFormatter) Format

func (e *EmptyFormatter) Format(entry *LogEntry) ([]byte, error)

Format 格式化日志条目(返回空字节)

func (*EmptyFormatter) GetName

func (e *EmptyFormatter) GetName() string

GetName 获取格式化器名称

type EmptyHook

type EmptyHook struct {
	// contains filtered or unexported fields
}

EmptyHook 是 IHook 接口的空实现

func NewEmptyHook

func NewEmptyHook(levels []LogLevel) *EmptyHook

NewEmptyHook 创建一个新的空钩子

func (*EmptyHook) Fire

func (e *EmptyHook) Fire(entry *LogEntry) error

Fire 执行钩子(空实现)

func (*EmptyHook) Levels

func (e *EmptyHook) Levels() []LogLevel

Levels 获取支持的级别

type EmptyLogger

type EmptyLogger struct {
	// contains filtered or unexported fields
}

EmptyLogger 是 ILogger 接口的空实现,所有方法都不执行任何操作 常用于测试环境或需要禁用日志输出的场景

func NewEmptyLogger

func NewEmptyLogger() *EmptyLogger

NewEmptyLogger 创建一个新的 EmptyLogger 实例

func NewEmptyLoggerWithLevel

func NewEmptyLoggerWithLevel(level LogLevel) *EmptyLogger

NewEmptyLoggerWithLevel 创建一个指定级别的空日志实例

func (*EmptyLogger) Clone

func (e *EmptyLogger) Clone() ILogger

实用方法

func (*EmptyLogger) Debug

func (e *EmptyLogger) Debug(format string, args ...interface{})

基本日志方法 - 所有方法都是空实现

func (*EmptyLogger) DebugContext

func (e *EmptyLogger) DebugContext(ctx context.Context, format string, args ...interface{})

带上下文的日志方法

func (*EmptyLogger) DebugContextKV added in v0.4.3

func (e *EmptyLogger) DebugContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

带上下文的结构化日志方法

func (*EmptyLogger) DebugKV

func (e *EmptyLogger) DebugKV(msg string, keysAndValues ...interface{})

结构化日志方法(键值对)

func (*EmptyLogger) DebugLines added in v0.4.2

func (e *EmptyLogger) DebugLines(lines ...string)

func (*EmptyLogger) DebugMsg

func (e *EmptyLogger) DebugMsg(msg string)

纯文本日志方法

func (*EmptyLogger) Debugf added in v0.3.0

func (e *EmptyLogger) Debugf(format string, args ...interface{})

Printf风格方法(与上面相同,但命名更明确)

func (*EmptyLogger) Error

func (e *EmptyLogger) Error(format string, args ...interface{})

func (*EmptyLogger) ErrorContext

func (e *EmptyLogger) ErrorContext(ctx context.Context, format string, args ...interface{})

func (*EmptyLogger) ErrorContextKV added in v0.4.3

func (e *EmptyLogger) ErrorContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*EmptyLogger) ErrorKV

func (e *EmptyLogger) ErrorKV(msg string, keysAndValues ...interface{})

func (*EmptyLogger) ErrorLines added in v0.4.2

func (e *EmptyLogger) ErrorLines(lines ...string)

func (*EmptyLogger) ErrorMsg

func (e *EmptyLogger) ErrorMsg(msg string)

func (*EmptyLogger) Errorf added in v0.3.0

func (e *EmptyLogger) Errorf(format string, args ...interface{})

func (*EmptyLogger) Fatal

func (e *EmptyLogger) Fatal(format string, args ...interface{})

func (*EmptyLogger) FatalContext

func (e *EmptyLogger) FatalContext(ctx context.Context, format string, args ...interface{})

func (*EmptyLogger) FatalContextKV added in v0.4.3

func (e *EmptyLogger) FatalContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*EmptyLogger) FatalKV

func (e *EmptyLogger) FatalKV(msg string, keysAndValues ...interface{})

func (*EmptyLogger) FatalMsg

func (e *EmptyLogger) FatalMsg(msg string)

func (*EmptyLogger) Fatalf added in v0.3.0

func (e *EmptyLogger) Fatalf(format string, args ...interface{})

func (*EmptyLogger) GetLevel

func (e *EmptyLogger) GetLevel() LogLevel

func (*EmptyLogger) GetStats

func (e *EmptyLogger) GetStats() *LoggerStats

GetStats 返回统计信息

func (*EmptyLogger) Info

func (e *EmptyLogger) Info(format string, args ...interface{})

func (*EmptyLogger) InfoContext

func (e *EmptyLogger) InfoContext(ctx context.Context, format string, args ...interface{})

func (*EmptyLogger) InfoContextKV added in v0.4.3

func (e *EmptyLogger) InfoContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*EmptyLogger) InfoKV

func (e *EmptyLogger) InfoKV(msg string, keysAndValues ...interface{})

func (*EmptyLogger) InfoLines added in v0.4.2

func (e *EmptyLogger) InfoLines(lines ...string)

多行日志方法

func (*EmptyLogger) InfoMsg

func (e *EmptyLogger) InfoMsg(msg string)

func (*EmptyLogger) Infof added in v0.3.0

func (e *EmptyLogger) Infof(format string, args ...interface{})

func (*EmptyLogger) IsLevelEnabled

func (e *EmptyLogger) IsLevelEnabled(level LogLevel) bool

func (*EmptyLogger) IsShowCaller

func (e *EmptyLogger) IsShowCaller() bool

func (*EmptyLogger) Log

func (e *EmptyLogger) Log(level LogLevel, msg string)

原始日志条目方法

func (*EmptyLogger) LogContext

func (e *EmptyLogger) LogContext(ctx context.Context, level LogLevel, msg string)

func (*EmptyLogger) LogKV

func (e *EmptyLogger) LogKV(level LogLevel, msg string, keysAndValues ...interface{})

func (*EmptyLogger) LogWithFields

func (e *EmptyLogger) LogWithFields(level LogLevel, msg string, fields map[string]interface{})

func (*EmptyLogger) Print

func (e *EmptyLogger) Print(args ...interface{})

兼容标准log包的方法

func (*EmptyLogger) Printf

func (e *EmptyLogger) Printf(format string, args ...interface{})

func (*EmptyLogger) Println

func (e *EmptyLogger) Println(args ...interface{})

func (*EmptyLogger) SetLevel

func (e *EmptyLogger) SetLevel(level LogLevel)

配置方法

func (*EmptyLogger) SetShowCaller

func (e *EmptyLogger) SetShowCaller(show bool)

func (*EmptyLogger) Warn

func (e *EmptyLogger) Warn(format string, args ...interface{})

func (*EmptyLogger) WarnContext

func (e *EmptyLogger) WarnContext(ctx context.Context, format string, args ...interface{})

func (*EmptyLogger) WarnContextKV added in v0.4.3

func (e *EmptyLogger) WarnContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*EmptyLogger) WarnKV

func (e *EmptyLogger) WarnKV(msg string, keysAndValues ...interface{})

func (*EmptyLogger) WarnLines added in v0.4.2

func (e *EmptyLogger) WarnLines(lines ...string)

func (*EmptyLogger) WarnMsg

func (e *EmptyLogger) WarnMsg(msg string)

func (*EmptyLogger) Warnf added in v0.3.0

func (e *EmptyLogger) Warnf(format string, args ...interface{})

func (*EmptyLogger) WithContext

func (e *EmptyLogger) WithContext(ctx context.Context) ILogger

func (*EmptyLogger) WithError

func (e *EmptyLogger) WithError(err error) ILogger

func (*EmptyLogger) WithField

func (e *EmptyLogger) WithField(key string, value interface{}) ILogger

结构化日志构建器方法 - 返回自身以保持链式调用

func (*EmptyLogger) WithFields

func (e *EmptyLogger) WithFields(fields map[string]interface{}) ILogger

type EmptyMiddleware

type EmptyMiddleware struct {
	// contains filtered or unexported fields
}

EmptyMiddleware 是 IMiddleware 接口的空实现

func NewEmptyMiddleware

func NewEmptyMiddleware(name string, priority int) *EmptyMiddleware

NewEmptyMiddleware 创建一个新的空中间件

func (*EmptyMiddleware) GetName

func (e *EmptyMiddleware) GetName() string

GetName 获取中间件名称

func (*EmptyMiddleware) GetPriority

func (e *EmptyMiddleware) GetPriority() int

GetPriority 获取中间件优先级

func (*EmptyMiddleware) Process

func (e *EmptyMiddleware) Process(entry *LogEntry, next func(*LogEntry) error) error

Process 处理日志条目(空实现,直接调用下一个处理器)

type EmptyWriter

type EmptyWriter struct {
	// contains filtered or unexported fields
}

EmptyWriter 是 IWriter 接口的空实现

func NewEmptyWriter

func NewEmptyWriter() *EmptyWriter

NewEmptyWriter 创建一个新的空写入器

func (*EmptyWriter) Close

func (e *EmptyWriter) Close() error

Close 关闭写入器(空实现)

func (*EmptyWriter) Flush

func (e *EmptyWriter) Flush() error

Flush 刷新缓冲区(空实现)

func (*EmptyWriter) GetStats

func (e *EmptyWriter) GetStats() interface{}

GetStats 获取统计信息

func (*EmptyWriter) IsHealthy

func (e *EmptyWriter) IsHealthy() bool

IsHealthy 检查写入器健康状态

func (*EmptyWriter) Write

func (e *EmptyWriter) Write(p []byte) (n int, err error)

Write 写入数据(空实现)

func (*EmptyWriter) WriteLevel

func (e *EmptyWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)

WriteLevel 按级别写入数据(空实现)

type EnvironmentConfig added in v0.4.0

type EnvironmentConfig struct {
	Development *LogConfig `json:"development" yaml:"development"`
	Testing     *LogConfig `json:"testing" yaml:"testing"`
	Production  *LogConfig `json:"production" yaml:"production"`
}

EnvironmentConfig 环境配置

func NewEnvironmentConfig added in v0.4.0

func NewEnvironmentConfig() *EnvironmentConfig

NewEnvironmentConfig 创建环境配置

type ErrorCode

type ErrorCode int

ErrorCode 错误代码

const (
	// 通用错误
	ErrUnknown ErrorCode = iota + 1000
	ErrInvalidInput
	ErrNotFound
	ErrAlreadyExists
	ErrPermissionDenied
	ErrTimeout
	ErrInternal

	// 日志相关错误
	ErrLoggerNotInitialized ErrorCode = iota + 2000
	ErrFormatterNotFound
	ErrWriterNotFound
	ErrHookNotFound
	ErrFilterNotFound
	ErrMiddlewareNotFound

	// 配置相关错误
	ErrConfigInvalid ErrorCode = iota + 3000
	ErrConfigNotFound
	ErrConfigLoadFailed
	ErrConfigSaveFailed

	// IO相关错误
	ErrFileNotFound ErrorCode = iota + 4000
	ErrFilePermission
	ErrFileWrite
	ErrFileRead
	ErrDiskFull
)

func GetErrorCode

func GetErrorCode(err error) ErrorCode

GetErrorCode 获取错误代码

type ErrorHandler

type ErrorHandler struct {
	// contains filtered or unexported fields
}

ErrorHandler 错误处理器

func NewErrorHandler

func NewErrorHandler(logger ILogger) *ErrorHandler

NewErrorHandler 创建错误处理器

func (*ErrorHandler) AddHook

func (eh *ErrorHandler) AddHook(hook func(*AppError))

AddHook 添加错误处理钩子

func (*ErrorHandler) Handle

func (eh *ErrorHandler) Handle(err error)

Handle 处理错误

type ErrorRecord added in v0.4.0

type ErrorRecord struct {
	Operation string    `json:"operation"`
	Error     string    `json:"error"`
	Timestamp time.Time `json:"timestamp"`
	Count     uint64    `json:"count"`
}

ErrorRecord 错误记录

type ErrorStats added in v0.4.0

type ErrorStats struct {
	TotalErrors       uint64            `json:"total_errors"`
	ErrorsByType      map[string]uint64 `json:"errors_by_type"`
	ErrorsByOperation map[string]uint64 `json:"errors_by_operation"`
	RecentErrors      []ErrorRecord     `json:"recent_errors"`
	FirstError        time.Time         `json:"first_error"`
	LastError         time.Time         `json:"last_error"`
}

ErrorStats 错误统计

type EventType

type EventType int

EventType 事件类型

const (
	EventLogCreated EventType = iota
	EventLogProcessed
	EventLogWritten
	EventLogError
	EventLoggerStarted
	EventLoggerStopped
	EventLoggerConfigChanged
)

type Field added in v0.4.0

type Field struct {
	Key       ContextKey
	LogName   string
	Generator func() string
}

Field 定义一个可提取字段

type FieldMap

type FieldMap map[string]interface{}

FieldMap 字段映射类型

type FileAdapterConfig added in v0.4.0

type FileAdapterConfig struct {
	Path         string        `json:"path" yaml:"path"`
	MaxSize      int64         `json:"max_size" yaml:"max_size"` // 单位:字节
	MaxBackups   int           `json:"max_backups" yaml:"max_backups"`
	MaxAge       time.Duration `json:"max_age" yaml:"max_age"` // 单位:天
	Compress     bool          `json:"compress" yaml:"compress"`
	LocalTime    bool          `json:"local_time" yaml:"local_time"`
	BufferSize   int           `json:"buffer_size" yaml:"buffer_size"`
	SyncInterval time.Duration `json:"sync_interval" yaml:"sync_interval"`
}

FileAdapterConfig 文件适配器配置

type FileHook

type FileHook struct {
	*BaseHook
	FilePath   string `json:"file_path"`
	MaxSize    int64  `json:"max_size"`
	MaxBackups int    `json:"max_backups"`
	// contains filtered or unexported fields
}

FileHook 文件钩子

func (*FileHook) Fire

func (h *FileHook) Fire(entry *LogEntry) error

Fire 执行钩子

type FileLogWriter

type FileLogWriter struct {
	BaseWriter
	FilePath string `json:"file_path"`

	Permission os.FileMode `json:"permission"`
	// contains filtered or unexported fields
}

FileLogWriter 文件输出器

func (*FileLogWriter) Close

func (w *FileLogWriter) Close() error

Close 关闭文件

func (*FileLogWriter) Flush

func (w *FileLogWriter) Flush() error

Flush 刷新文件缓冲区

func (*FileLogWriter) GetStats

func (w *FileLogWriter) GetStats() interface{}

GetStats 获取统计信息

func (*FileLogWriter) IsHealthy

func (w *FileLogWriter) IsHealthy() bool

IsHealthy 检查健康状态

func (*FileLogWriter) Write

func (w *FileLogWriter) Write(p []byte) (n int, err error)

Write 实现io.Writer接口

func (*FileLogWriter) WriteLevel

func (w *FileLogWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)

WriteLevel 按级别写入

type FormatRegistry

type FormatRegistry struct {
	// contains filtered or unexported fields
}

FormatRegistry 格式化器注册表

func NewFormatRegistry

func NewFormatRegistry() *FormatRegistry

NewFormatRegistry 创建格式化器注册表

func (*FormatRegistry) Create

func (r *FormatRegistry) Create(formatterType FormatterType) (IFormatter, error)

Create 创建格式化器

func (*FormatRegistry) List

func (r *FormatRegistry) List() []FormatterType

List 列出所有注册的格式化器

func (*FormatRegistry) Register

func (r *FormatRegistry) Register(formatterType FormatterType, factory func() IFormatter)

Register 注册格式化器

type FormatType added in v0.4.0

type FormatType string

FormatType 输出格式类型

const (
	FormatText FormatType = "text"
	FormatJSON FormatType = "json"
	FormatXML  FormatType = "xml"
	FormatCSV  FormatType = "csv"
)

type FormatterType

type FormatterType string

FormatterType 格式化器类型

const (
	TextFormatter FormatterType = "text"
	JSONFormatter FormatterType = "json"
	XMLFormatter  FormatterType = "xml"
	CSVFormatter  FormatterType = "csv"
)

type GCInfo added in v0.4.0

type GCInfo struct {
	Timestamp time.Time `json:"timestamp"`

	// GC统计
	NumGC         uint32  `json:"num_gc"`          // GC次数
	NumForcedGC   uint32  `json:"num_forced_gc"`   // 强制GC次数
	GCCPUFraction float64 `json:"gc_cpu_fraction"` // GC CPU占用比例

	// GC时间
	TotalPauseNs uint64        `json:"total_pause_ns"` // 总暂停时间(纳秒)
	TotalPause   time.Duration `json:"total_pause"`    // 总暂停时间
	LastPause    time.Duration `json:"last_pause"`     // 最后暂停时间
	AvgPause     time.Duration `json:"avg_pause"`      // 平均暂停时间
	MinPause     time.Duration `json:"min_pause"`      // 最小暂停时间
	MaxPause     time.Duration `json:"max_pause"`      // 最大暂停时间

	// GC触发
	NextGC    uint64    `json:"next_gc"`    // 下次GC阈值
	LastGC    time.Time `json:"last_gc"`    // 最后GC时间
	GCTrigger string    `json:"gc_trigger"` // GC触发原因

	// GC详细统计
	PauseHistory []time.Duration `json:"pause_history"` // 暂停历史
	GCFrequency  float64         `json:"gc_frequency"`  // GC频率 (次/秒)

	// GC效率
	GCEfficiency float64 `json:"gc_efficiency"` // GC效率 (回收字节/暂停时间)
	HeapReleased uint64  `json:"heap_released"` // 释放的堆内存
}

GCInfo GC信息

type GCStats added in v0.4.0

type GCStats struct {
	NumGC         uint32          `json:"num_gc"`          // GC次数
	TotalPause    time.Duration   `json:"total_pause"`     // 总暂停时间
	LastPause     time.Duration   `json:"last_pause"`      // 最后一次暂停时间
	AvgPause      time.Duration   `json:"avg_pause"`       // 平均暂停时间
	MaxPause      time.Duration   `json:"max_pause"`       // 最大暂停时间
	GCCPUFraction float64         `json:"gc_cpu_fraction"` // GC CPU占用比例
	NextGC        uint64          `json:"next_gc"`         // 下次GC触发内存量
	LastGC        time.Time       `json:"last_gc"`         // 最后一次GC时间
	RecentPauses  []time.Duration `json:"recent_pauses"`   // 最近的暂停时间
}

GCStats 垃圾回收统计

type HeapInfo added in v0.4.0

type HeapInfo struct {
	Timestamp time.Time `json:"timestamp"`

	// 堆大小
	HeapAlloc    uint64 `json:"heap_alloc"`    // 堆已分配
	HeapSys      uint64 `json:"heap_sys"`      // 堆系统内存
	HeapIdle     uint64 `json:"heap_idle"`     // 堆空闲内存
	HeapInuse    uint64 `json:"heap_inuse"`    // 堆使用中内存
	HeapReleased uint64 `json:"heap_released"` // 堆释放内存
	HeapObjects  uint64 `json:"heap_objects"`  // 堆对象数量

	// 堆统计
	HeapUsage         float64 `json:"heap_usage"`         // 堆使用率
	HeapFragmentation float64 `json:"heap_fragmentation"` // 堆碎片率

	// 分配统计
	TotalAlloc uint64  `json:"total_alloc"` // 总分配字节数
	AllocRate  float64 `json:"alloc_rate"`  // 分配速率 (字节/秒)
	Mallocs    uint64  `json:"mallocs"`     // 分配次数
	Frees      uint64  `json:"frees"`       // 释放次数

	// 大对象
	LargeObjects     uint64 `json:"large_objects"`      // 大对象数量
	LargeObjectBytes uint64 `json:"large_object_bytes"` // 大对象字节数
}

HeapInfo 堆信息

type HeapSnapshot added in v0.4.0

type HeapSnapshot struct {
	Timestamp     time.Time            `json:"timestamp"`
	TotalSize     uint64               `json:"total_size"`
	ObjectCount   uint64               `json:"object_count"`
	TypeStats     map[string]*TypeStat `json:"type_stats"`
	SizeHistogram map[string]uint64    `json:"size_histogram"`
	AgeHistogram  map[string]uint64    `json:"age_histogram"`
}

HeapSnapshot 堆快照

type HookConfig added in v0.4.0

type HookConfig struct {
	Name    string                 `json:"name" yaml:"name"`
	Type    string                 `json:"type" yaml:"type"` // prometheus, webhook, slack, email
	Level   LogLevel               `json:"level" yaml:"level"`
	Enabled bool                   `json:"enabled" yaml:"enabled"`
	Config  map[string]interface{} `json:"config" yaml:"config"`
}

HookConfig 钩子配置

type HookLevel

type HookLevel []LogLevel

HookLevel 钩子触发级别

type HookManager

type HookManager struct {
	// contains filtered or unexported fields
}

HookManager 钩子管理器

func NewHookManager

func NewHookManager() *HookManager

NewHookManager 创建钩子管理器

func (*HookManager) AddHook

func (hm *HookManager) AddHook(name string, hook IHook)

AddHook 添加钩子

func (*HookManager) FireHooks

func (hm *HookManager) FireHooks(entry *LogEntry)

FireHooks 触发所有适用的钩子

func (*HookManager) GetHook

func (hm *HookManager) GetHook(name string) (IHook, bool)

GetHook 获取钩子

func (*HookManager) ListHooks

func (hm *HookManager) ListHooks() []string

ListHooks 列出所有钩子名称

func (*HookManager) RemoveHook

func (hm *HookManager) RemoveHook(name string)

RemoveHook 移除钩子

type IAdapter

type IAdapter interface {
	ILogger

	// 生命周期管理
	Initialize() error
	Close() error
	Flush() error

	// 适配器特定功能
	GetAdapterName() string
	GetAdapterVersion() string
	IsHealthy() bool
}

IAdapter 日志适配器接口

func CreateAdapter

func CreateAdapter(config *AdapterConfig) (IAdapter, error)

CreateAdapter 创建适配器的工厂方法

func NewStandardAdapter

func NewStandardAdapter(config *AdapterConfig) (IAdapter, error)

NewStandardAdapter 创建标准库适配器

type IAdvancedLogger

type IAdvancedLogger interface {
	ILogger

	// 采样和限流
	Sample(every int) ILogger
	RateLimit(rate float64) ILogger

	// 异步日志
	Async() ILogger
	Sync() error

	// 缓冲控制
	Buffer(size int) ILogger
	Flush() error

	// 条件日志
	If(condition bool) ILogger
	Unless(condition bool) ILogger
}

高级日志功能接口

type IFileWriter

type IFileWriter interface {
	io.WriteCloser

	// 文件管理
	Rotate() error
	GetCurrentFile() string
	GetFileSize() int64

	// 配置
	SetMaxSize(size int64)
	SetMaxBackups(backups int)
	SetMaxAge(days int)
	SetCompress(compress bool)
}

IFileWriter 文件写入器接口

type IFormatter

type IFormatter interface {
	Format(entry *LogEntry) ([]byte, error)
	GetName() string
}

IFormatter 日志格式化器接口

func NewCSVFormatter

func NewCSVFormatter() IFormatter

NewCSVFormatter 创建CSV格式化器

func NewJSONFormatter

func NewJSONFormatter() IFormatter

NewJSONFormatter 创建JSON格式化器

func NewTextFormatter

func NewTextFormatter() IFormatter

NewTextFormatter 创建文本格式化器

func NewXMLFormatter

func NewXMLFormatter() IFormatter

NewXMLFormatter 创建XML格式化器

type IFrameworkAdapter

type IFrameworkAdapter interface {
	ILogger

	// 框架检测
	GetFrameworkName() string
	GetFrameworkVersion() string

	// 原生框架实例
	GetNativeLogger() interface{}

	// 配置同步
	SyncConfig() error
}

通用日志适配器接口

type IHook

type IHook interface {
	Fire(entry *LogEntry) error
	Levels() []LogLevel
}

IHook 日志钩子接口

func NewConsoleHook

func NewConsoleHook(levels HookLevel) IHook

NewConsoleHook 创建控制台钩子

func NewEmailHook

func NewEmailHook(host, port, username, password, from string, to []string) IHook

NewEmailHook 创建邮件钩子

func NewFileHook

func NewFileHook(filePath string, levels HookLevel) IHook

NewFileHook 创建文件钩子

func NewWebhookHook

func NewWebhookHook(url string, levels HookLevel) IHook

NewWebhookHook 创建Webhook钩子

type ILogBuilder

type ILogBuilder interface {
	Level(level LogLevel) ILogBuilder
	Message(msg string) ILogBuilder
	Field(key string, value interface{}) ILogBuilder
	Fields(fields map[string]interface{}) ILogBuilder
	Error(err error) ILogBuilder
	Context(ctx context.Context) ILogBuilder
	Caller(skip int) ILogBuilder
	Timestamp(t interface{}) ILogBuilder
	Build() *LogEntry
	Log()
}

构建器模式接口

type ILogger

type ILogger interface {
	// 基本日志方法(Printf风格)
	Debug(format string, args ...interface{})
	Info(format string, args ...interface{})
	Warn(format string, args ...interface{})
	Error(format string, args ...interface{})
	Fatal(format string, args ...interface{})

	// Printf风格日志方法(与上面相同,但命名更明确)
	Debugf(format string, args ...interface{})
	Infof(format string, args ...interface{})
	Warnf(format string, args ...interface{})
	Errorf(format string, args ...interface{})
	Fatalf(format string, args ...interface{})

	// 纯文本日志方法(支持单个消息)
	DebugMsg(msg string)
	InfoMsg(msg string)
	WarnMsg(msg string)
	ErrorMsg(msg string)
	FatalMsg(msg string)

	// 带上下文的日志方法
	DebugContext(ctx context.Context, format string, args ...interface{})
	InfoContext(ctx context.Context, format string, args ...interface{})
	WarnContext(ctx context.Context, format string, args ...interface{})
	ErrorContext(ctx context.Context, format string, args ...interface{})
	FatalContext(ctx context.Context, format string, args ...interface{})

	// 结构化日志方法(键值对)
	DebugKV(msg string, keysAndValues ...interface{})
	InfoKV(msg string, keysAndValues ...interface{})
	WarnKV(msg string, keysAndValues ...interface{})
	ErrorKV(msg string, keysAndValues ...interface{})
	FatalKV(msg string, keysAndValues ...interface{})

	// 带上下文的结构化日志方法(键值对)
	DebugContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
	InfoContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
	WarnContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
	ErrorContextKV(ctx context.Context, msg string, keysAndValues ...interface{})
	FatalContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

	// 多行日志方法(自动处理多行格式)
	InfoLines(lines ...string)
	ErrorLines(lines ...string)
	WarnLines(lines ...string)
	DebugLines(lines ...string)

	// 原始日志条目方法(最灵活)
	Log(level LogLevel, msg string)
	LogContext(ctx context.Context, level LogLevel, msg string)
	LogKV(level LogLevel, msg string, keysAndValues ...interface{})
	LogWithFields(level LogLevel, msg string, fields map[string]interface{})

	// 配置方法
	SetLevel(level LogLevel)
	GetLevel() LogLevel
	SetShowCaller(show bool)
	IsShowCaller() bool
	IsLevelEnabled(level LogLevel) bool

	// 结构化日志构建器
	WithField(key string, value interface{}) ILogger
	WithFields(fields map[string]interface{}) ILogger
	WithError(err error) ILogger
	WithContext(ctx context.Context) ILogger

	// 实用方法
	Clone() ILogger
	Print(args ...interface{})                 // 兼容标准log包
	Printf(format string, args ...interface{}) // 兼容标准log包
	Println(args ...interface{})               // 兼容标准log包
}

ILogger 增强的日志记录器接口,支持多种参数格式

var (
	// NoLogger 全局的空日志实例,用于禁用所有日志输出
	NoLogger ILogger = NewEmptyLogger()

	// DiscardLogger 废弃所有日志的实例,与NoLogger功能相同
	DiscardLogger ILogger = NewEmptyLogger()

	// NullLogger 空日志实例,用于测试场景
	NullLogger ILogger = NewEmptyLogger()
)

全局空日志实例

func WithError

func WithError(err error) ILogger

WithError 全局添加错误信息

func WithField

func WithField(key string, value interface{}) ILogger

WithField 全局添加字段

func WithFields

func WithFields(fields map[string]interface{}) ILogger

WithFields 全局添加多个字段

func WithLogger added in v0.4.0

func WithLogger(ctx context.Context, baseLogger ILogger) ILogger

WithLogger 从 context 创建带所有注册字段的 logger

func WrapWithEmpty

func WrapWithEmpty(original ILogger) ILogger

WrapWithEmpty 将任何日志器包装为空实现(用于临时禁用日志)

type ILogrusLogger

type ILogrusLogger interface {
	// Logrus特有方法
	Trace(args ...interface{})
}

ILogrusLogger Logrus日志框架兼容接口

type IManager

type IManager interface {
	// 适配器管理
	AddAdapter(name string, adapter IAdapter) error
	GetAdapter(name string) (IAdapter, bool)
	RemoveAdapter(name string) error
	ListAdapters() []string

	// 生命周期管理
	CloseAll() error
	FlushAll() error

	// 全局设置
	SetLevelAll(level LogLevel)
	Broadcast(level LogLevel, format string, args ...interface{})

	// 健康检查
	HealthCheck() map[string]bool
}

IManager 日志管理器接口

func NewLoggerManager

func NewLoggerManager() IManager

NewLoggerManager 创建日志管理器

type IMiddleware

type IMiddleware interface {
	Process(entry *LogEntry, next func(*LogEntry) error) error
	GetName() string
	GetPriority() int
}

IMiddleware 日志中间件接口

type IOMonitoringConfig added in v0.4.0

type IOMonitoringConfig struct {
	Enabled     bool `json:"enabled" yaml:"enabled"`
	TrackWrites bool `json:"track_writes" yaml:"track_writes"`
	TrackReads  bool `json:"track_reads" yaml:"track_reads"`
	TrackErrors bool `json:"track_errors" yaml:"track_errors"`
}

IOMonitoringConfig IO监控配置

type ISlogLogger

type ISlogLogger interface {
	// slog特有方法
	LogAttrs(ctx context.Context, level LogLevel, msg string, attrs ...interface{})
	With(args ...interface{}) ISlogLogger
	WithGroup(name string) ISlogLogger
}

ISlogLogger 标准库slog兼容接口

type IWriter

type IWriter interface {
	io.Writer

	// 写入控制
	WriteLevel(level LogLevel, data []byte) (n int, err error)
	Flush() error
	Close() error

	// 状态查询
	IsHealthy() bool
	GetStats() interface{}
}

IWriter 日志写入器接口

func NewBufferedWriter

func NewBufferedWriter(underlying IWriter, bufferSize int) IWriter

NewBufferedWriter 创建缓冲输出器

func NewConsoleWriter

func NewConsoleWriter(output io.Writer) IWriter

NewConsoleWriter 创建控制台输出器

func NewFileWriter

func NewFileWriter(filePath string) IWriter

NewFileWriter 创建文件输出器

func NewMultiWriter

func NewMultiWriter(writers ...IWriter) IWriter

NewMultiWriter 创建多输出器

func NewRotateWriter

func NewRotateWriter(filePath string, maxSize int64, maxFiles int) IWriter

NewRotateWriter 创建轮转文件输出器

type IZapLogger

type IZapLogger interface {
	// Zap特有方法
	DPanic(msg string, fields ...interface{})
	Sync() error
	Sugar() ILogger
}

IZapLogger Zap日志框架兼容接口

type IZerologLogger

type IZerologLogger interface {
	// Zerolog链式方法
	Str(key, val string) IZerologLogger
	Int(key string, i int) IZerologLogger
	Float64(key string, f float64) IZerologLogger
	Bool(key string, b bool) IZerologLogger
	Time(key string, t interface{}) IZerologLogger
	Dur(key string, d interface{}) IZerologLogger
	Msg(msg string)
	Msgf(format string, v ...interface{})
}

IZerologLogger Zerolog兼容接口

type JSONLogFormatter

type JSONLogFormatter struct {
	*BaseFormatter
	FieldMap map[string]string `json:"field_map"`
}

JSONLogFormatter JSON格式化器

func (*JSONLogFormatter) Format

func (f *JSONLogFormatter) Format(entry *LogEntry) ([]byte, error)

Format 格式化日志条目

func (*JSONLogFormatter) GetName

func (f *JSONLogFormatter) GetName() string

GetName 获取格式化器名称

type LatencyMetrics added in v0.4.0

type LatencyMetrics struct {
	AvgLatency    time.Duration `json:"avg_latency"`
	MedianLatency time.Duration `json:"median_latency"`
	P90Latency    time.Duration `json:"p90_latency"`
	P95Latency    time.Duration `json:"p95_latency"`
	P99Latency    time.Duration `json:"p99_latency"`
}

LatencyMetrics 延迟指标

type LatencyStats added in v0.4.0

type LatencyStats struct {
	Operations map[string]*OperationLatency `json:"operations"`
	Overall    *LatencyMetrics              `json:"overall"`
}

LatencyStats 延迟统计

type LevelInfo added in v0.4.0

type LevelInfo struct {
	Name        string `json:"name"`        // 级别名称
	ShortName   string `json:"short_name"`  // 短名称
	Emoji       string `json:"emoji"`       // 表情符号
	Color       string `json:"color"`       // 颜色代码
	Priority    int    `json:"priority"`    // 优先级
	Description string `json:"description"` // 描述
	Category    string `json:"category"`    // 类别
}

LevelInfo 级别信息结构

type LevelManager added in v0.4.0

type LevelManager struct {
	// contains filtered or unexported fields
}

LevelManager 级别管理器

func GetLevelManager added in v0.4.0

func GetLevelManager() *LevelManager

GetLevelManager 获取全局级别管理器实例 (单例模式)

func NewLevelManager added in v0.4.0

func NewLevelManager() *LevelManager

NewLevelManager 创建新的级别管理器实例 (可选)

func (*LevelManager) GetComponentLevel added in v0.4.0

func (lm *LevelManager) GetComponentLevel(component string) LogLevel

GetComponentLevel 获取组件级别

func (*LevelManager) GetEffectiveLevel added in v0.4.0

func (lm *LevelManager) GetEffectiveLevel(component, pkg string) LogLevel

GetEffectiveLevel 获取有效级别

func (*LevelManager) GetGlobalLevel added in v0.4.0

func (lm *LevelManager) GetGlobalLevel() LogLevel

GetGlobalLevel 获取全局级别

func (*LevelManager) GetLevelStats added in v0.4.0

func (lm *LevelManager) GetLevelStats(level LogLevel) *LevelStats

GetLevelStats 获取级别统计

func (*LevelManager) GetPackageLevel added in v0.4.0

func (lm *LevelManager) GetPackageLevel(pkg string) LogLevel

GetPackageLevel 获取包级别

func (*LevelManager) IsLevelEnabled added in v0.4.0

func (lm *LevelManager) IsLevelEnabled(level LogLevel, component, pkg string) bool

IsLevelEnabled 检查级别是否启用

func (*LevelManager) RecordLevelUsage added in v0.4.0

func (lm *LevelManager) RecordLevelUsage(level LogLevel)

RecordLevelUsage 记录级别使用

func (*LevelManager) SetComponentLevel added in v0.4.0

func (lm *LevelManager) SetComponentLevel(component string, level LogLevel) *LevelManager

SetComponentLevel 设置组件级别

func (*LevelManager) SetGlobalLevel added in v0.4.0

func (lm *LevelManager) SetGlobalLevel(level LogLevel) *LevelManager

SetGlobalLevel 设置全局级别

func (*LevelManager) SetPackageLevel added in v0.4.0

func (lm *LevelManager) SetPackageLevel(pkg string, level LogLevel) *LevelManager

SetPackageLevel 设置包级别

func (*LevelManager) String added in v0.4.0

func (lm *LevelManager) String() string

String 字符串表示

type LevelStats added in v0.4.0

type LevelStats struct {
	Level     LogLevel  `json:"level"`
	Count     uint64    `json:"count"`
	LastUsed  time.Time `json:"last_used"`
	FirstUsed time.Time `json:"first_used"`
}

LevelStats 级别统计

type LogArgs

type LogArgs struct {
	Format  string
	Args    []interface{}
	Fields  map[string]interface{}
	Context context.Context
}

日志参数辅助类型

type LogConfig

type LogConfig struct {
	Level      LogLevel  `json:"level"`       // 日志级别
	ShowCaller bool      `json:"show_caller"` // 是否显示调用者信息
	Prefix     string    `json:"prefix"`      // 日志前缀
	Output     io.Writer `json:"-"`           // 输出目标
	Colorful   bool      `json:"colorful"`    // 是否使用彩色输出
	TimeFormat string    `json:"time_format"` // 时间格式
}

LogConfig 日志配置(兼容旧版本)

func DefaultConfig

func DefaultConfig() *LogConfig

DefaultConfig 默认配置

func DisableLogging

func DisableLogging() *LogConfig

DisableLogging 创建一个完全禁用日志的配置

func GetGlobalConfig

func GetGlobalConfig() *LogConfig

GetGlobalConfig 获取全局配置

func NewDevelopmentConfig added in v0.4.0

func NewDevelopmentConfig() *LogConfig

NewDevelopmentConfig 创建开发环境配置

func NewLogConfig added in v0.4.0

func NewLogConfig() *LogConfig

NewLogConfig 创建新的日志配置(兼容旧版本)

func NewProductionConfig added in v0.4.0

func NewProductionConfig() *LogConfig

NewProductionConfig 创建生产环境配置

func NewTestingConfig added in v0.4.0

func NewTestingConfig() *LogConfig

NewTestingConfig 创建测试环境配置

func (*LogConfig) Clone

func (c *LogConfig) Clone() *LogConfig

Clone 克隆配置(兼容旧版本)

func (*LogConfig) ToConfig added in v0.4.0

func (c *LogConfig) ToConfig() *Config

ToConfig 转换为新的配置结构

func (*LogConfig) Validate

func (c *LogConfig) Validate() error

Validate 验证配置(兼容旧版本)

func (*LogConfig) WithColorful

func (c *LogConfig) WithColorful(colorful bool) *LogConfig

WithColorful 设置是否使用彩色输出(兼容旧版本)

func (*LogConfig) WithLevel

func (c *LogConfig) WithLevel(level LogLevel) *LogConfig

WithLevel 设置日志级别(兼容旧版本)

func (*LogConfig) WithOutput

func (c *LogConfig) WithOutput(output io.Writer) *LogConfig

WithOutput 设置输出目标(兼容旧版本)

func (*LogConfig) WithPrefix

func (c *LogConfig) WithPrefix(prefix string) *LogConfig

WithPrefix 设置日志前缀(兼容旧版本)

func (*LogConfig) WithShowCaller

func (c *LogConfig) WithShowCaller(show bool) *LogConfig

WithShowCaller 设置是否显示调用者信息(兼容旧版本)

func (*LogConfig) WithTimeFormat

func (c *LogConfig) WithTimeFormat(format string) *LogConfig

WithTimeFormat 设置时间格式(兼容旧版本)

type LogEntry

type LogEntry struct {
	Level     LogLevel               `json:"level"`
	Message   string                 `json:"message"`
	Timestamp int64                  `json:"timestamp"`
	Fields    map[string]interface{} `json:"fields,omitempty"`
	Caller    *CallerInfo            `json:"caller,omitempty"`
}

LogEntry 日志条目

type LogEvent

type LogEvent struct {
	Type      EventType `json:"type"`
	Timestamp time.Time `json:"timestamp"`
	Level     LogLevel  `json:"level"`
	Message   string    `json:"message"`
	Fields    FieldMap  `json:"fields,omitempty"`
	Error     error     `json:"error,omitempty"`
}

LogEvent 日志事件

func NewLogEvent

func NewLogEvent(eventType EventType, level LogLevel, message string) *LogEvent

NewLogEvent 创建日志事件

type LogLevel

type LogLevel int

LogLevel 日志级别类型 (保持向后兼容)

const (
	DEBUG LogLevel = iota // 调试级别 - 最详细的信息
	INFO                  // 信息级别 - 一般信息
	WARN                  // 警告级别 - 警告信息
	ERROR                 // 错误级别 - 错误信息
	FATAL                 // 致命级别 - 致命错误,程序将退出
)

基础日志级别常量 (保持现有API兼容性)

const (
	TRACE LogLevel = -1 // 跟踪级别 - 更详细的调试信息
	OFF   LogLevel = 99 // 关闭级别 - 禁用所有日志
)

扩展级别常量 (新增的高级功能)

const (
	SYSTEM      LogLevel = 100 + iota // 系统级信息
	KERNEL                            // 内核级信息
	DRIVER                            // 驱动级信息
	APPLICATION                       // 应用级信息
	SERVICE                           // 服务级信息
	COMPONENT                         // 组件级信息
	MODULE                            // 模块级信息
)

系统级扩展级别

const (
	BUSINESS    LogLevel = 200 + iota // 业务级信息
	TRANSACTION                       // 事务级信息
	WORKFLOW                          // 工作流信息
	PROCESS                           // 流程级信息
)

业务级扩展级别

const (
	SECURITY   LogLevel = 300 + iota // 安全级信息
	AUDIT                            // 审计级信息
	COMPLIANCE                       // 合规级信息
	THREAT                           // 威胁级信息
)

安全级扩展级别

const (
	PERFORMANCE LogLevel = 400 + iota // 性能级信息
	METRIC                            // 指标级信息
	BENCHMARK                         // 基准测试信息
	PROFILING                         // 性能分析信息
)

性能级扩展级别

func GetAllExtendedLevels added in v0.4.0

func GetAllExtendedLevels() []LogLevel

GetAllExtendedLevels 获取所有级别(包括扩展级别)

func GetAllLevels

func GetAllLevels() []LogLevel

GetAllLevels 获取所有基础级别 (保持向后兼容)

func GetBasicLevels added in v0.4.0

func GetBasicLevels() []LogLevel

GetBasicLevels 获取基础级别

func GetExtendedLevels added in v0.4.0

func GetExtendedLevels() []LogLevel

GetExtendedLevels 获取扩展级别(不包括基础级别)

func GetLevelsByCategory added in v0.4.0

func GetLevelsByCategory(category string) []LogLevel

GetLevelsByCategory 根据类别获取级别

func ParseLevel

func ParseLevel(level string) (LogLevel, error)

ParseLevel 从字符串解析日志级别

func (LogLevel) Category added in v0.4.0

func (l LogLevel) Category() string

Category 返回级别的类别

func (LogLevel) Color

func (l LogLevel) Color() string

Color 返回日志级别的颜色代码

func (LogLevel) Description added in v0.4.0

func (l LogLevel) Description() string

Description 返回级别的描述

func (LogLevel) Emoji

func (l LogLevel) Emoji() string

Emoji 返回日志级别的emoji

func (LogLevel) Info added in v0.4.0

func (l LogLevel) Info() LevelInfo

Info 返回级别的完整信息

func (LogLevel) IsApplication added in v0.4.0

func (l LogLevel) IsApplication() bool

IsApplication 检查是否为应用级别

func (LogLevel) IsBasic added in v0.4.0

func (l LogLevel) IsBasic() bool

IsBasic 检查是否为基础级别

func (LogLevel) IsBusiness added in v0.4.0

func (l LogLevel) IsBusiness() bool

IsBusiness 检查是否为业务级别

func (LogLevel) IsEnabled

func (l LogLevel) IsEnabled(target LogLevel) bool

IsEnabled 检查当前级别是否启用目标级别

func (LogLevel) IsPerformance added in v0.4.0

func (l LogLevel) IsPerformance() bool

IsPerformance 检查是否为性能级别

func (LogLevel) IsSecurity added in v0.4.0

func (l LogLevel) IsSecurity() bool

IsSecurity 检查是否为安全级别

func (LogLevel) IsSystem added in v0.4.0

func (l LogLevel) IsSystem() bool

IsSystem 检查是否为系统级别

func (LogLevel) IsValid added in v0.4.0

func (l LogLevel) IsValid() bool

IsValid 检查级别是否有效

func (LogLevel) Priority added in v0.4.0

func (l LogLevel) Priority() int

Priority 返回级别的优先级

func (LogLevel) ShortString added in v0.4.0

func (l LogLevel) ShortString() string

ShortString 返回级别的短字符串表示

func (LogLevel) String

func (l LogLevel) String() string

String 返回日志级别的字符串表示

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger 主要的日志记录器结构体

func CreateFileLogger

func CreateFileLogger(filePath string, level LogLevel) *Logger

CreateFileLogger 创建文件日志器

func CreateProductionLogger

func CreateProductionLogger(logDir string) *Logger

CreateProductionLogger 创建生产环境日志器

func CreateSimpleLogger

func CreateSimpleLogger(level LogLevel) *Logger

CreateSimpleLogger 创建简单的日志器

func GetGlobalLogger

func GetGlobalLogger() *Logger

GetGlobalLogger 获取全局Logger

func New added in v0.4.0

func New() *Logger

New 创建新的日志记录器(简化版本) 使用默认配置创建日志记录器,支持链式调用配置

func NewLogger

func NewLogger(config *LogConfig) *Logger

NewLogger 创建新的日志记录器

func NewLoggerWithOptions

func NewLoggerWithOptions(options *LoggerOptions) *Logger

NewLoggerWithOptions 使用选项创建Logger

func NewOptimized added in v0.4.0

func NewOptimized() *Logger

NewOptimized 创建优化日志器(便利函数) 使用平衡性能与功能的配置创建Logger

func (*Logger) Clone

func (l *Logger) Clone() ILogger

Clone 克隆当前Logger

func (*Logger) Debug

func (l *Logger) Debug(format string, args ...interface{})

Debug 调试日志

func (*Logger) DebugContext

func (l *Logger) DebugContext(ctx context.Context, format string, args ...interface{})

带上下文的日志方法

func (*Logger) DebugContextKV added in v0.4.3

func (l *Logger) DebugContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*Logger) DebugKV

func (l *Logger) DebugKV(msg string, keysAndValues ...interface{})

结构化日志方法(键值对)

func (*Logger) DebugLines added in v0.4.2

func (l *Logger) DebugLines(lines ...string)

func (*Logger) DebugMsg

func (l *Logger) DebugMsg(msg string)

纯文本日志方法

func (*Logger) Debugf added in v0.3.0

func (l *Logger) Debugf(format string, args ...interface{})

Printf风格方法(与上面相同,但命名更明确)

func (*Logger) Error

func (l *Logger) Error(format string, args ...interface{})

Error 错误日志

func (*Logger) ErrorContext

func (l *Logger) ErrorContext(ctx context.Context, format string, args ...interface{})

func (*Logger) ErrorContextKV added in v0.4.3

func (l *Logger) ErrorContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*Logger) ErrorKV

func (l *Logger) ErrorKV(msg string, keysAndValues ...interface{})

func (*Logger) ErrorLines added in v0.4.2

func (l *Logger) ErrorLines(lines ...string)

func (*Logger) ErrorMsg

func (l *Logger) ErrorMsg(msg string)

func (*Logger) Errorf added in v0.3.0

func (l *Logger) Errorf(format string, args ...interface{})

func (*Logger) Fatal

func (l *Logger) Fatal(format string, args ...interface{})

Fatal 致命错误日志

func (*Logger) FatalContext

func (l *Logger) FatalContext(ctx context.Context, format string, args ...interface{})

func (*Logger) FatalContextKV added in v0.4.3

func (l *Logger) FatalContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*Logger) FatalKV

func (l *Logger) FatalKV(msg string, keysAndValues ...interface{})

func (*Logger) FatalMsg

func (l *Logger) FatalMsg(msg string)

func (*Logger) Fatalf added in v0.3.0

func (l *Logger) Fatalf(format string, args ...interface{})

func (*Logger) GetConfig

func (l *Logger) GetConfig() *LogConfig

GetConfig 获取日志配置的副本

func (*Logger) GetLevel

func (l *Logger) GetLevel() LogLevel

GetLevel 获取当前日志级别

func (*Logger) Info

func (l *Logger) Info(format string, args ...interface{})

Info 信息日志

func (*Logger) InfoContext

func (l *Logger) InfoContext(ctx context.Context, format string, args ...interface{})

func (*Logger) InfoContextKV added in v0.4.3

func (l *Logger) InfoContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*Logger) InfoKV

func (l *Logger) InfoKV(msg string, keysAndValues ...interface{})

func (*Logger) InfoLines added in v0.4.2

func (l *Logger) InfoLines(lines ...string)

多行日志方法 - 自动处理换行符

func (*Logger) InfoMsg

func (l *Logger) InfoMsg(msg string)

func (*Logger) Infof added in v0.3.0

func (l *Logger) Infof(format string, args ...interface{})

func (*Logger) IsLevelEnabled

func (l *Logger) IsLevelEnabled(level LogLevel) bool

IsLevelEnabled 检查给定级别是否启用

func (*Logger) IsShowCaller

func (l *Logger) IsShowCaller() bool

IsShowCaller 检查是否显示调用者信息

func (*Logger) Log

func (l *Logger) Log(level LogLevel, msg string)

原始日志条目方法

func (*Logger) LogContext

func (l *Logger) LogContext(ctx context.Context, level LogLevel, msg string)

func (*Logger) LogKV

func (l *Logger) LogKV(level LogLevel, msg string, keysAndValues ...interface{})

func (*Logger) LogWithFields

func (l *Logger) LogWithFields(level LogLevel, msg string, fields map[string]interface{})

func (*Logger) Print

func (l *Logger) Print(args ...interface{})

兼容标准log包的方法

func (*Logger) Printf

func (l *Logger) Printf(format string, args ...interface{})

func (*Logger) Println

func (l *Logger) Println(args ...interface{})

func (*Logger) SetLevel

func (l *Logger) SetLevel(level LogLevel)

SetLevel 设置日志级别

func (*Logger) SetShowCaller

func (l *Logger) SetShowCaller(show bool)

SetShowCaller 设置是否显示调用者信息

func (*Logger) UpdateConfig

func (l *Logger) UpdateConfig(config *LogConfig)

UpdateConfig 更新日志配置

func (*Logger) Warn

func (l *Logger) Warn(format string, args ...interface{})

Warn 警告日志

func (*Logger) WarnContext

func (l *Logger) WarnContext(ctx context.Context, format string, args ...interface{})

func (*Logger) WarnContextKV added in v0.4.3

func (l *Logger) WarnContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*Logger) WarnKV

func (l *Logger) WarnKV(msg string, keysAndValues ...interface{})

func (*Logger) WarnLines added in v0.4.2

func (l *Logger) WarnLines(lines ...string)

func (*Logger) WarnMsg

func (l *Logger) WarnMsg(msg string)

func (*Logger) Warnf added in v0.3.0

func (l *Logger) Warnf(format string, args ...interface{})

func (*Logger) WithColorful added in v0.4.0

func (l *Logger) WithColorful(colorful bool) *Logger

WithColorful 设置是否使用彩色输出并返回自身(链式调用)

func (*Logger) WithContext

func (l *Logger) WithContext(ctx context.Context) ILogger

WithContext 带上下文的logger(当前实现返回自身)

func (*Logger) WithError

func (l *Logger) WithError(err error) ILogger

WithError 添加错误信息

func (*Logger) WithField

func (l *Logger) WithField(key string, value interface{}) ILogger

WithField 添加字段信息(结构化日志)

func (*Logger) WithFields

func (l *Logger) WithFields(fields map[string]interface{}) ILogger

WithFields 添加多个字段信息(结构化日志)

func (*Logger) WithLevel added in v0.4.0

func (l *Logger) WithLevel(level LogLevel) *Logger

WithLevel 设置日志级别并返回自身(链式调用)

func (*Logger) WithPrefix added in v0.4.0

func (l *Logger) WithPrefix(prefix string) *Logger

WithPrefix 设置日志前缀并返回自身(链式调用)

func (*Logger) WithShowCaller added in v0.4.0

func (l *Logger) WithShowCaller(show bool) *Logger

WithShowCaller 设置是否显示调用者信息并返回自身(链式调用)

type LoggerBuilder

type LoggerBuilder struct {
	// contains filtered or unexported fields
}

LoggerBuilder 日志器构建器

func NewLoggerBuilder

func NewLoggerBuilder() *LoggerBuilder

NewLoggerBuilder 创建日志器构建器

func (*LoggerBuilder) Build

func (b *LoggerBuilder) Build() *Logger

Build 构建日志器

func (*LoggerBuilder) WithConfig

func (b *LoggerBuilder) WithConfig(config *LogConfig) *LoggerBuilder

WithConfig 设置配置

func (*LoggerBuilder) WithFormatter

func (b *LoggerBuilder) WithFormatter(formatterType FormatterType) *LoggerBuilder

WithFormatter 设置格式化器

func (*LoggerBuilder) WithHook

func (b *LoggerBuilder) WithHook(name string, config interface{}) *LoggerBuilder

WithHook 添加钩子

func (*LoggerBuilder) WithMiddleware

func (b *LoggerBuilder) WithMiddleware(name string, config interface{}) *LoggerBuilder

WithMiddleware 添加中间件

func (*LoggerBuilder) WithWriter

func (b *LoggerBuilder) WithWriter(name string, config interface{}) *LoggerBuilder

WithWriter 添加写入器

type LoggerFactory

type LoggerFactory struct {
	// contains filtered or unexported fields
}

LoggerFactory 日志器工厂

func GetGlobalFactory

func GetGlobalFactory() *LoggerFactory

GetGlobalFactory 获取全局工厂实例

func NewLoggerFactory

func NewLoggerFactory() *LoggerFactory

NewLoggerFactory 创建日志器工厂

func (*LoggerFactory) CreateAdapter

func (f *LoggerFactory) CreateAdapter(name string, config *AdapterConfig) (IAdapter, error)

CreateAdapter 创建适配器

func (*LoggerFactory) CreateFormatter

func (f *LoggerFactory) CreateFormatter(formatterType FormatterType) (IFormatter, error)

CreateFormatter 创建格式化器

func (*LoggerFactory) CreateHook

func (f *LoggerFactory) CreateHook(name string, config interface{}) (IHook, error)

CreateHook 创建钩子

func (*LoggerFactory) CreateMiddleware

func (f *LoggerFactory) CreateMiddleware(name string, config interface{}) (IMiddleware, error)

CreateMiddleware 创建中间件

func (*LoggerFactory) CreateWriter

func (f *LoggerFactory) CreateWriter(name string, config interface{}) (IWriter, error)

CreateWriter 创建写入器

func (*LoggerFactory) RegisterHook

func (f *LoggerFactory) RegisterHook(name string, factory func(config interface{}) (IHook, error))

RegisterHook 注册钩子工厂

func (*LoggerFactory) RegisterMiddleware

func (f *LoggerFactory) RegisterMiddleware(name string, factory func(config interface{}) (IMiddleware, error))

RegisterMiddleware 注册中间件工厂

func (*LoggerFactory) RegisterWriter

func (f *LoggerFactory) RegisterWriter(name string, factory func(config interface{}) (IWriter, error))

RegisterWriter 注册写入器工厂

type LoggerManager

type LoggerManager struct {
	// contains filtered or unexported fields
}

LoggerManager 日志管理器实现

func (*LoggerManager) AddAdapter

func (lm *LoggerManager) AddAdapter(name string, adapter IAdapter) error

AddAdapter 添加适配器

func (*LoggerManager) Broadcast

func (lm *LoggerManager) Broadcast(level LogLevel, format string, args ...interface{})

Broadcast 广播日志到所有适配器

func (*LoggerManager) CloseAll

func (lm *LoggerManager) CloseAll() error

CloseAll 关闭所有适配器

func (*LoggerManager) FlushAll

func (lm *LoggerManager) FlushAll() error

FlushAll 刷新所有适配器

func (*LoggerManager) GetAdapter

func (lm *LoggerManager) GetAdapter(name string) (IAdapter, bool)

GetAdapter 获取适配器

func (*LoggerManager) HealthCheck

func (lm *LoggerManager) HealthCheck() map[string]bool

HealthCheck 检查所有适配器的健康状态

func (*LoggerManager) ListAdapters

func (lm *LoggerManager) ListAdapters() []string

ListAdapters 列出所有适配器名称

func (*LoggerManager) RemoveAdapter

func (lm *LoggerManager) RemoveAdapter(name string) error

RemoveAdapter 移除适配器

func (*LoggerManager) SetLevelAll

func (lm *LoggerManager) SetLevelAll(level LogLevel)

SetLevelAll 设置所有适配器的日志级别

type LoggerOptions

type LoggerOptions struct {
	Config     *LogConfig      `json:"config"`
	Formatter  IFormatter      `json:"-"`
	Writers    []IWriter       `json:"-"`
	Hooks      []IHook         `json:"-"`
	Middleware []IMiddleware   `json:"-"`
	Context    context.Context `json:"-"`
}

LoggerOptions 创建Logger时的选项

func DefaultLoggerOptions

func DefaultLoggerOptions() *LoggerOptions

DefaultLoggerOptions 默认Logger选项

type LoggerStats

type LoggerStats struct {
	StartTime    time.Time          `json:"start_time"`
	TotalLogs    int64              `json:"total_logs"`
	LevelCounts  map[LogLevel]int64 `json:"level_counts"`
	ErrorCount   int64              `json:"error_count"`
	LastLogTime  time.Time          `json:"last_log_time"`
	Uptime       time.Duration      `json:"uptime"`
	BytesWritten int64              `json:"bytes_written"`
	// contains filtered or unexported fields
}

LoggerStats 日志统计信息

func NewLoggerStats

func NewLoggerStats() *LoggerStats

NewLoggerStats 创建新的统计信息

func (*LoggerStats) AddBytes

func (s *LoggerStats) AddBytes(bytes int64)

AddBytes 增加字节数

func (*LoggerStats) GetStats

func (s *LoggerStats) GetStats() LoggerStatsSnapshot

GetStats 获取统计信息快照

func (*LoggerStats) IncrementLevel

func (s *LoggerStats) IncrementLevel(level LogLevel)

IncrementLevel 增加级别计数

type LoggerStatsSnapshot

type LoggerStatsSnapshot struct {
	StartTime    time.Time          `json:"start_time"`
	TotalLogs    int64              `json:"total_logs"`
	LevelCounts  map[LogLevel]int64 `json:"level_counts"`
	ErrorCount   int64              `json:"error_count"`
	LastLogTime  time.Time          `json:"last_log_time"`
	Uptime       time.Duration      `json:"uptime"`
	BytesWritten int64              `json:"bytes_written"`
}

LoggerStatsSnapshot 统计信息快照

type MemoryInfo added in v0.4.0

type MemoryInfo struct {
	Timestamp time.Time `json:"timestamp"`

	// 总体内存
	TotalMemory uint64  `json:"total_memory"` // 总内存
	UsedMemory  uint64  `json:"used_memory"`  // 已使用内存
	FreeMemory  uint64  `json:"free_memory"`  // 空闲内存
	MemoryUsage float64 `json:"memory_usage"` // 内存使用率 (%)

	// 进程内存
	ProcessRSS   uint64 `json:"process_rss"`   // 进程物理内存
	ProcessVSS   uint64 `json:"process_vss"`   // 进程虚拟内存
	ProcessHeap  uint64 `json:"process_heap"`  // 进程堆内存
	ProcessStack uint64 `json:"process_stack"` // 进程栈内存

	// Go运行时内存
	GoAllocated uint64 `json:"go_allocated"` // Go已分配内存
	GoSys       uint64 `json:"go_sys"`       // Go系统内存
	GoHeap      uint64 `json:"go_heap"`      // Go堆内存
	GoStack     uint64 `json:"go_stack"`     // Go栈内存
	GoMSpan     uint64 `json:"go_mspan"`     // Go MSpan内存
	GoMCache    uint64 `json:"go_mcache"`    // Go MCache内存
	GoBuckHash  uint64 `json:"go_buckhash"`  // Go哈希表内存
	GoGC        uint64 `json:"go_gc"`        // Go GC内存
	GoOther     uint64 `json:"go_other"`     // Go其他内存

	// 内存压力
	MemoryPressure string `json:"memory_pressure"` // low/medium/high/critical

	// 阈值状态
	ThresholdExceeded bool    `json:"threshold_exceeded"`
	Threshold         float64 `json:"threshold"`
}

MemoryInfo 内存信息

type MemoryLeakReport added in v0.4.0

type MemoryLeakReport struct {
	Timestamp          time.Time         `json:"timestamp"`
	SuspiciousTypes    []*SuspiciousType `json:"suspicious_types"`
	GrowthTrend        string            `json:"growth_trend"` // stable/growing/leaking
	RecommendedActions []string          `json:"recommended_actions"`
	MemoryGrowthRate   float64           `json:"memory_growth_rate"` // 字节/秒
}

MemoryLeakReport 内存泄漏报告

type MemoryMonitor added in v0.4.0

type MemoryMonitor interface {
	// 开始监控
	Start() error
	Stop() error

	// 获取内存信息
	GetMemoryInfo() *MemoryInfo
	GetMemoryStats() *MemoryStats
	GetGCInfo() *GCInfo
	GetHeapInfo() *HeapInfo

	// 内存管理
	ForceGC()
	SetGCPercent(percent int) int
	SetMaxMemory(maxBytes uint64)

	// 内存警报
	SetMemoryThreshold(threshold float64)
	OnMemoryThresholdExceeded(callback func(info *MemoryInfo))

	// 内存分析
	TakeHeapSnapshot() (*HeapSnapshot, error)
	AnalyzeMemoryLeaks() *MemoryLeakReport

	// 清理和优化
	Cleanup()
	Optimize()
}

MemoryMonitor 内存监控器接口

type MemoryMonitoringConfig added in v0.4.0

type MemoryMonitoringConfig struct {
	Enabled   bool          `json:"enabled" yaml:"enabled"`
	Interval  time.Duration `json:"interval" yaml:"interval"`
	Threshold int64         `json:"threshold" yaml:"threshold"`
}

MemoryMonitoringConfig 内存监控配置

type MemoryStats added in v0.4.0

type MemoryStats struct {
	Used              uint64    `json:"used"`      // 已使用内存 (字节)
	Available         uint64    `json:"available"` // 可用内存 (字节)
	Total             uint64    `json:"total"`     // 总内存 (字节)
	Usage             float64   `json:"usage"`     // 内存使用率 (%)
	Heap              uint64    `json:"heap"`      // 堆内存 (字节)
	Stack             uint64    `json:"stack"`     // 栈内存 (字节)
	RSS               uint64    `json:"rss"`       // 物理内存 (字节)
	VMS               uint64    `json:"vms"`       // 虚拟内存 (字节)
	Threshold         float64   `json:"threshold"` // 内存阈值 (%)
	ThresholdExceeded uint64    `json:"threshold_exceeded"`
	History           []float64 `json:"history"` // 历史数据
}

MemoryStats 内存统计

type MemoryTracker added in v0.4.0

type MemoryTracker struct {
	// contains filtered or unexported fields
}

MemoryTracker 专门用于内存跟踪的超轻量级实现

func NewMemoryTracker added in v0.4.0

func NewMemoryTracker(thresholdMB uint64) *MemoryTracker

NewMemoryTracker 创建内存追踪器

func (*MemoryTracker) Status added in v0.4.0

func (mt *MemoryTracker) Status() (current, peak, threshold uint64, warnings uint64)

Status 获取状态

func (*MemoryTracker) Update added in v0.4.0

func (mt *MemoryTracker) Update(heapBytes uint64) bool

Update 更新内存使用 - 超快速

type MetricStats added in v0.4.0

type MetricStats struct {
	Name        string          `json:"name"`
	Type        string          `json:"type"` // counter, gauge, histogram
	Count       uint64          `json:"count"`
	Sum         float64         `json:"sum"`
	Min         float64         `json:"min"`
	Max         float64         `json:"max"`
	Mean        float64         `json:"mean"`
	StdDev      float64         `json:"std_dev"`
	Percentiles map[int]float64 `json:"percentiles"` // P50, P90, P95, P99
	LastUpdate  time.Time       `json:"last_update"`
}

MetricStats 指标统计

type MiddlewareConfig added in v0.4.0

type MiddlewareConfig struct {
	Name    string                 `json:"name" yaml:"name"`
	Type    string                 `json:"type" yaml:"type"`
	Enabled bool                   `json:"enabled" yaml:"enabled"`
	Order   int                    `json:"order" yaml:"order"`
	Config  map[string]interface{} `json:"config" yaml:"config"`
}

MiddlewareConfig 中间件配置

type Monitor added in v0.4.0

type Monitor struct {
	// contains filtered or unexported fields
}

Monitor 高性能监控器 - 3ns级别响应 Monitor 高性能监控器结构体

func DefaultMonitor added in v0.4.0

func DefaultMonitor() *Monitor

DefaultMonitor 获取默认监控器

func NewMonitor added in v0.4.0

func NewMonitor() *Monitor

NewMonitor 创建高性能监控器

func (*Monitor) Disable added in v0.4.0

func (m *Monitor) Disable()

Disable 禁用监控

func (*Monitor) Enable added in v0.4.0

func (m *Monitor) Enable()

Enable 启用监控

func (*Monitor) FastMemory added in v0.4.0

func (m *Monitor) FastMemory() (heap uint64)

FastMemory 快速内存检查 - 3.094ns/op

func (*Monitor) QuickCheck added in v0.4.0

func (m *Monitor) QuickCheck() (healthy bool, pressure string)

QuickCheck 快速健康检查

func (*Monitor) SetThreshold added in v0.4.0

func (m *Monitor) SetThreshold(mb uint64)

SetThreshold 设置阈值

func (*Monitor) Stats added in v0.4.0

func (m *Monitor) Stats() (ops, errors, current, peak, warnings uint64, errorRate float64)

Stats 获取统计

func (*Monitor) String added in v0.4.0

func (m *Monitor) String() string

String 字符串表示

func (*Monitor) Track added in v0.4.0

func (m *Monitor) Track() func(error)

Track 追踪操作 - 3.134ns/op

func (*Monitor) Update added in v0.4.0

func (m *Monitor) Update(heapBytes uint64) bool

Update 更新内存追踪 - 53ns/op

type MonitoringConfig added in v0.4.0

type MonitoringConfig struct {
	Enabled     bool                        `json:"enabled" yaml:"enabled"`
	Memory      MemoryMonitoringConfig      `json:"memory" yaml:"memory"`
	Performance PerformanceMonitoringConfig `json:"performance" yaml:"performance"`
	IO          IOMonitoringConfig          `json:"io" yaml:"io"`
}

MonitoringConfig 监控配置

type MultiLogWriter

type MultiLogWriter struct {
	BaseWriter
	// contains filtered or unexported fields
}

MultiLogWriter 多输出器

func (*MultiLogWriter) Close

func (w *MultiLogWriter) Close() error

Close 关闭所有输出器

func (*MultiLogWriter) Flush

func (w *MultiLogWriter) Flush() error

Flush 刷新所有输出器

func (*MultiLogWriter) GetStats

func (w *MultiLogWriter) GetStats() interface{}

GetStats 获取统计信息

func (*MultiLogWriter) IsHealthy

func (w *MultiLogWriter) IsHealthy() bool

IsHealthy 检查是否至少有一个输出器健康

func (*MultiLogWriter) Write

func (w *MultiLogWriter) Write(p []byte) (n int, err error)

Write 实现io.Writer接口

func (*MultiLogWriter) WriteLevel

func (w *MultiLogWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)

WriteLevel 按级别写入

type NetworkAdapterConfig added in v0.4.0

type NetworkAdapterConfig struct {
	Protocol        string            `json:"protocol" yaml:"protocol"` // tcp, udp, http, https
	Address         string            `json:"address" yaml:"address"`
	Port            int               `json:"port" yaml:"port"`
	Timeout         time.Duration     `json:"timeout" yaml:"timeout"`
	RetryAttempts   int               `json:"retry_attempts" yaml:"retry_attempts"`
	RetryInterval   time.Duration     `json:"retry_interval" yaml:"retry_interval"`
	TLS             TLSConfig         `json:"tls" yaml:"tls"`
	Authentication  AuthConfig        `json:"authentication" yaml:"authentication"`
	Headers         map[string]string `json:"headers" yaml:"headers"`
	CompressionType string            `json:"compression_type" yaml:"compression_type"` // gzip, lz4, none
}

NetworkAdapterConfig 网络适配器配置

type OperationLatency added in v0.4.0

type OperationLatency struct {
	Operation         string          `json:"operation"`
	Count             uint64          `json:"count"`
	TotalLatency      time.Duration   `json:"total_latency"`
	AvgLatency        time.Duration   `json:"avg_latency"`
	MinLatency        time.Duration   `json:"min_latency"`
	MaxLatency        time.Duration   `json:"max_latency"`
	P50Latency        time.Duration   `json:"p50_latency"`
	P90Latency        time.Duration   `json:"p90_latency"`
	P95Latency        time.Duration   `json:"p95_latency"`
	P99Latency        time.Duration   `json:"p99_latency"`
	Threshold         time.Duration   `json:"threshold"`
	ThresholdExceeded uint64          `json:"threshold_exceeded"`
	RecentLatencies   []time.Duration `json:"recent_latencies"`
}

OperationLatency 操作延迟

type OperationLogger added in v0.4.0

type OperationLogger struct {
	// contains filtered or unexported fields
}

OperationLogger 操作日志记录器

func NewOperationLogger added in v0.4.0

func NewOperationLogger(ctx context.Context, baseLogger ILogger, operation string) *OperationLogger

NewOperationLogger 创建操作日志记录器

func (*OperationLogger) Debug added in v0.4.0

func (ol *OperationLogger) Debug(msg string, kvs ...interface{})

Debug 记录 Debug 日志

func (*OperationLogger) End added in v0.4.0

func (ol *OperationLogger) End(keysAndValues ...interface{})

End 结束操作

func (*OperationLogger) EndWithError added in v0.4.0

func (ol *OperationLogger) EndWithError(err error, keysAndValues ...interface{})

EndWithError 结束操作(带错误)

func (*OperationLogger) Error added in v0.4.0

func (ol *OperationLogger) Error(msg string, kvs ...interface{})

Error 记录 Error 日志

func (*OperationLogger) GetChain added in v0.4.0

func (ol *OperationLogger) GetChain() *CorrelationChain

GetChain 获取相关性链

func (*OperationLogger) GetContext added in v0.4.0

func (ol *OperationLogger) GetContext() context.Context

GetContext 获取上下文

func (*OperationLogger) Info added in v0.4.0

func (ol *OperationLogger) Info(msg string, kvs ...interface{})

Info 记录 Info 日志

func (*OperationLogger) SetMetric added in v0.4.0

func (ol *OperationLogger) SetMetric(key string, value interface{}) *OperationLogger

SetMetric 设置指标

func (*OperationLogger) SetTag added in v0.4.0

func (ol *OperationLogger) SetTag(key, value string) *OperationLogger

SetTag 设置标签

func (*OperationLogger) Trace added in v0.4.0

func (ol *OperationLogger) Trace(msg string, kvs ...interface{})

Trace 记录 Trace 日志

func (*OperationLogger) Warn added in v0.4.0

func (ol *OperationLogger) Warn(msg string, kvs ...interface{})

Warn 记录 Warn 日志

type OperationStats added in v0.4.0

type OperationStats struct {
	Name          string        `json:"name"`
	Count         uint64        `json:"count"`
	TotalTime     time.Duration `json:"total_time"`
	AvgTime       time.Duration `json:"avg_time"`
	MinTime       time.Duration `json:"min_time"`
	MaxTime       time.Duration `json:"max_time"`
	TotalBytes    uint64        `json:"total_bytes"`
	AvgBytes      float64       `json:"avg_bytes"`
	ErrorCount    uint64        `json:"error_count"`
	ErrorRate     float64       `json:"error_rate"`
	LastExecuted  time.Time     `json:"last_executed"`
	FirstExecuted time.Time     `json:"first_executed"`
}

OperationStats 操作统计

type OperationThroughput added in v0.4.0

type OperationThroughput struct {
	Operation         string    `json:"operation"`
	Count             uint64    `json:"count"`
	StartTime         time.Time `json:"start_time"`
	LastTime          time.Time `json:"last_time"`
	CurrentThroughput float64   `json:"current_throughput"` // ops/sec
	AvgThroughput     float64   `json:"avg_throughput"`     // ops/sec
	MaxThroughput     float64   `json:"max_throughput"`     // ops/sec
	Threshold         float64   `json:"threshold"`          // ops/sec
	ThresholdExceeded uint64    `json:"threshold_exceeded"`
	RecentCounts      []uint64  `json:"recent_counts"`
}

OperationThroughput 操作吞吐量

type OptimizedConfig added in v0.4.0

type OptimizedConfig struct {
	CacheExpiry     time.Duration `json:"cache_expiry"`     // 缓存过期时间
	CheckInterval   time.Duration `json:"check_interval"`   // 检查间隔
	HistorySize     int           `json:"history_size"`     // 历史大小
	EnableCaching   bool          `json:"enable_caching"`   // 启用缓存
	EnableHistory   bool          `json:"enable_history"`   // 启用历史
	LightweightMode bool          `json:"lightweight_mode"` // 轻量级模式
}

OptimizedConfig 优化配置

type OptimizedMonitor added in v0.4.0

type OptimizedMonitor struct {
	// contains filtered or unexported fields
}

OptimizedMonitor 极致性能优化的监控器

func NewOptimizedMonitor added in v0.4.0

func NewOptimizedMonitor(config OptimizedConfig) *OptimizedMonitor

NewOptimizedMonitor 创建优化监控器

func (*OptimizedMonitor) FastMemoryInfo added in v0.4.0

func (m *OptimizedMonitor) FastMemoryInfo() (heap, stack, used uint64, numGC uint32)

FastMemoryInfo 快速内存信息获取 - 零分配版本

func (*OptimizedMonitor) GetStats added in v0.4.0

func (m *OptimizedMonitor) GetStats() OptimizedStats

GetStats 获取轻量级统计信息

func (*OptimizedMonitor) QuickCheck added in v0.4.0

func (m *OptimizedMonitor) QuickCheck() (healthy bool, pressure string)

QuickCheck 超快速健康检查 - 仅检查关键指标

func (*OptimizedMonitor) RecordCall added in v0.4.0

func (m *OptimizedMonitor) RecordCall(latencyNs uint64, isError bool)

RecordCall 记录调用 - 超轻量级

func (*OptimizedMonitor) Start added in v0.4.0

func (m *OptimizedMonitor) Start() error

Start 启动监控 - 超轻量级

func (*OptimizedMonitor) Stop added in v0.4.0

func (m *OptimizedMonitor) Stop() error

Stop 停止监控

type OptimizedStats added in v0.4.0

type OptimizedStats struct {
	TotalCalls   uint64 `json:"total_calls"`
	TotalErrors  uint64 `json:"total_errors"`
	TotalLatency uint64 `json:"total_latency_ns"`
	Enabled      bool   `json:"enabled"`
	CacheHits    int64  `json:"cache_hits"`
}

OptimizedStats 优化统计信息

func (OptimizedStats) GetAverageLatency added in v0.4.0

func (s OptimizedStats) GetAverageLatency() uint64

GetAverageLatency 获取平均延迟(纳秒)

func (OptimizedStats) GetErrorRate added in v0.4.0

func (s OptimizedStats) GetErrorRate() float64

GetErrorRate 获取错误率

type PerformanceData added in v0.4.0

type PerformanceData struct {
	Timestamp  time.Time        `json:"timestamp"`
	Latency    *LatencyStats    `json:"latency"`
	Throughput *ThroughputStats `json:"throughput"`
	Resource   *ResourceStats   `json:"resource"`
}

PerformanceData 性能数据

type PerformanceMonitor added in v0.4.0

type PerformanceMonitor interface {
	// 开始监控
	Start() error
	Stop() error

	// 获取性能数据
	GetPerformanceData() *PerformanceData
	GetLatencyStats() *LatencyStats
	GetThroughputStats() *ThroughputStats
	GetResourceStats() *ResourceStats

	// 记录性能数据
	RecordLatency(operation string, latency time.Duration)
	RecordThroughput(operation string, count uint64)
	RecordResourceUsage()

	// 性能警报
	SetLatencyThreshold(operation string, threshold time.Duration)
	SetThroughputThreshold(operation string, threshold float64)
	SetResourceThreshold(cpu, memory float64)

	// 回调函数
	OnLatencyThresholdExceeded(callback func(operation string, latency time.Duration))
	OnThroughputThresholdExceeded(callback func(operation string, throughput float64))
	OnResourceThresholdExceeded(callback func(usage *ResourceUsage))
}

PerformanceMonitor 性能监控器接口

type PerformanceMonitoringConfig added in v0.4.0

type PerformanceMonitoringConfig struct {
	Enabled         bool    `json:"enabled" yaml:"enabled"`
	TrackLatency    bool    `json:"track_latency" yaml:"track_latency"`
	TrackThroughput bool    `json:"track_throughput" yaml:"track_throughput"`
	SampleRate      float64 `json:"sample_rate" yaml:"sample_rate"`
}

PerformanceMonitoringConfig 性能监控配置

type PresetExtractorType added in v0.4.1

type PresetExtractorType string

PresetExtractorType 预设提取器类型

const (
	PresetExtractorDefault   PresetExtractorType = "default"   // 默认:TraceID + RequestID
	PresetExtractorGateway   PresetExtractorType = "gateway"   // 网关:TraceID + RequestID + User + Tenant
	PresetExtractorService   PresetExtractorType = "service"   // 服务:TraceID + RequestID + User + Tenant
	PresetExtractorWebSocket PresetExtractorType = "websocket" // WebSocket:TraceID + User + Session
	PresetExtractorGRPC      PresetExtractorType = "grpc"      // gRPC:从 metadata 提取
	PresetExtractorFull      PresetExtractorType = "full"      // 完整:所有字段
)

type PrometheusHookConfig added in v0.4.0

type PrometheusHookConfig struct {
	Namespace   string            `json:"namespace" yaml:"namespace"`
	Subsystem   string            `json:"subsystem" yaml:"subsystem"`
	MetricName  string            `json:"metric_name" yaml:"metric_name"`
	Help        string            `json:"help" yaml:"help"`
	Labels      map[string]string `json:"labels" yaml:"labels"`
	Registry    string            `json:"registry" yaml:"registry"`
	PushGateway string            `json:"push_gateway" yaml:"push_gateway"`
}

PrometheusHookConfig Prometheus钩子配置

type ResourceStats added in v0.4.0

type ResourceStats struct {
	CPU    *CPUStats    `json:"cpu"`
	Memory *MemoryStats `json:"memory"`
	GC     *GCStats     `json:"gc"`
}

ResourceStats 资源统计

type ResourceUsage added in v0.4.0

type ResourceUsage struct {
	CPU    float64   `json:"cpu"`
	Memory float64   `json:"memory"`
	Time   time.Time `json:"time"`
}

ResourceUsage 资源使用情况

type RotateLogWriter

type RotateLogWriter struct {
	BaseWriter
	FilePath string        `json:"file_path"`
	MaxSize  int64         `json:"max_size"` // 字节
	MaxFiles int           `json:"max_files"`
	MaxAge   time.Duration `json:"max_age"`
	Compress bool          `json:"compress"`
	// contains filtered or unexported fields
}

RotateLogWriter 轮转文件输出器

func (*RotateLogWriter) Close

func (w *RotateLogWriter) Close() error

Close 关闭输出器

func (*RotateLogWriter) Flush

func (w *RotateLogWriter) Flush() error

Flush 刷新缓冲区

func (*RotateLogWriter) GetStats

func (w *RotateLogWriter) GetStats() interface{}

GetStats 获取统计信息

func (*RotateLogWriter) IsHealthy

func (w *RotateLogWriter) IsHealthy() bool

IsHealthy 检查健康状态

func (*RotateLogWriter) Write

func (w *RotateLogWriter) Write(p []byte) (n int, err error)

Write 实现io.Writer接口

func (*RotateLogWriter) WriteLevel

func (w *RotateLogWriter) WriteLevel(level LogLevel, data []byte) (n int, err error)

WriteLevel 按级别写入

type SpecialLogType

type SpecialLogType struct {
	// contains filtered or unexported fields
}

SpecialLogType 特殊日志类型

type StandardLoggerAdapter

type StandardLoggerAdapter struct {
	// contains filtered or unexported fields
}

StandardLoggerAdapter 标准库适配器实现

func (*StandardLoggerAdapter) Clone

func (s *StandardLoggerAdapter) Clone() ILogger

Clone 克隆适配器

func (*StandardLoggerAdapter) Close

func (s *StandardLoggerAdapter) Close() error

Close 关闭适配器

func (*StandardLoggerAdapter) Debug

func (s *StandardLoggerAdapter) Debug(format string, args ...interface{})

Debug 调试日志

func (*StandardLoggerAdapter) DebugContext

func (s *StandardLoggerAdapter) DebugContext(ctx context.Context, format string, args ...interface{})

带上下文的日志方法

func (*StandardLoggerAdapter) DebugContextKV added in v0.4.3

func (s *StandardLoggerAdapter) DebugContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

带上下文的结构化日志方法

func (*StandardLoggerAdapter) DebugKV

func (s *StandardLoggerAdapter) DebugKV(msg string, keysAndValues ...interface{})

结构化日志方法(键值对)

func (*StandardLoggerAdapter) DebugLines added in v0.4.2

func (s *StandardLoggerAdapter) DebugLines(lines ...string)

func (*StandardLoggerAdapter) DebugMsg

func (s *StandardLoggerAdapter) DebugMsg(msg string)

纯文本日志方法

func (*StandardLoggerAdapter) Debugf added in v0.3.0

func (s *StandardLoggerAdapter) Debugf(format string, args ...interface{})

Printf风格方法(与上面相同,但命名更明确)

func (*StandardLoggerAdapter) Error

func (s *StandardLoggerAdapter) Error(format string, args ...interface{})

Error 错误日志

func (*StandardLoggerAdapter) ErrorContext

func (s *StandardLoggerAdapter) ErrorContext(ctx context.Context, format string, args ...interface{})

func (*StandardLoggerAdapter) ErrorContextKV added in v0.4.3

func (s *StandardLoggerAdapter) ErrorContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*StandardLoggerAdapter) ErrorKV

func (s *StandardLoggerAdapter) ErrorKV(msg string, keysAndValues ...interface{})

func (*StandardLoggerAdapter) ErrorLines added in v0.4.2

func (s *StandardLoggerAdapter) ErrorLines(lines ...string)

func (*StandardLoggerAdapter) ErrorMsg

func (s *StandardLoggerAdapter) ErrorMsg(msg string)

func (*StandardLoggerAdapter) Errorf added in v0.3.0

func (s *StandardLoggerAdapter) Errorf(format string, args ...interface{})

func (*StandardLoggerAdapter) Fatal

func (s *StandardLoggerAdapter) Fatal(format string, args ...interface{})

Fatal 致命错误日志

func (*StandardLoggerAdapter) FatalContext

func (s *StandardLoggerAdapter) FatalContext(ctx context.Context, format string, args ...interface{})

func (*StandardLoggerAdapter) FatalContextKV added in v0.4.3

func (s *StandardLoggerAdapter) FatalContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*StandardLoggerAdapter) FatalKV

func (s *StandardLoggerAdapter) FatalKV(msg string, keysAndValues ...interface{})

func (*StandardLoggerAdapter) FatalMsg

func (s *StandardLoggerAdapter) FatalMsg(msg string)

func (*StandardLoggerAdapter) Fatalf added in v0.3.0

func (s *StandardLoggerAdapter) Fatalf(format string, args ...interface{})

func (*StandardLoggerAdapter) Flush

func (s *StandardLoggerAdapter) Flush() error

Flush 刷新缓冲区

func (*StandardLoggerAdapter) GetAdapterName

func (s *StandardLoggerAdapter) GetAdapterName() string

GetAdapterName 获取适配器名称

func (*StandardLoggerAdapter) GetAdapterVersion

func (s *StandardLoggerAdapter) GetAdapterVersion() string

GetAdapterVersion 获取适配器版本

func (*StandardLoggerAdapter) GetLevel

func (s *StandardLoggerAdapter) GetLevel() LogLevel

GetLevel 获取日志级别

func (*StandardLoggerAdapter) Info

func (s *StandardLoggerAdapter) Info(format string, args ...interface{})

Info 信息日志

func (*StandardLoggerAdapter) InfoContext

func (s *StandardLoggerAdapter) InfoContext(ctx context.Context, format string, args ...interface{})

func (*StandardLoggerAdapter) InfoContextKV added in v0.4.3

func (s *StandardLoggerAdapter) InfoContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*StandardLoggerAdapter) InfoKV

func (s *StandardLoggerAdapter) InfoKV(msg string, keysAndValues ...interface{})

func (*StandardLoggerAdapter) InfoLines added in v0.4.2

func (s *StandardLoggerAdapter) InfoLines(lines ...string)

多行日志方法

func (*StandardLoggerAdapter) InfoMsg

func (s *StandardLoggerAdapter) InfoMsg(msg string)

func (*StandardLoggerAdapter) Infof added in v0.3.0

func (s *StandardLoggerAdapter) Infof(format string, args ...interface{})

func (*StandardLoggerAdapter) Initialize

func (s *StandardLoggerAdapter) Initialize() error

Initialize 初始化适配器

func (*StandardLoggerAdapter) IsHealthy

func (s *StandardLoggerAdapter) IsHealthy() bool

IsHealthy 检查适配器是否健康

func (*StandardLoggerAdapter) IsLevelEnabled

func (s *StandardLoggerAdapter) IsLevelEnabled(level LogLevel) bool

IsLevelEnabled 检查日志级别是否启用

func (*StandardLoggerAdapter) IsShowCaller

func (s *StandardLoggerAdapter) IsShowCaller() bool

IsShowCaller 是否显示调用者信息

func (*StandardLoggerAdapter) Log

func (s *StandardLoggerAdapter) Log(level LogLevel, msg string)

原始日志条目方法

func (*StandardLoggerAdapter) LogContext

func (s *StandardLoggerAdapter) LogContext(ctx context.Context, level LogLevel, msg string)

func (*StandardLoggerAdapter) LogKV

func (s *StandardLoggerAdapter) LogKV(level LogLevel, msg string, keysAndValues ...interface{})

func (*StandardLoggerAdapter) LogWithFields

func (s *StandardLoggerAdapter) LogWithFields(level LogLevel, msg string, fields map[string]interface{})

func (*StandardLoggerAdapter) Print

func (s *StandardLoggerAdapter) Print(args ...interface{})

兼容标准log包的方法

func (*StandardLoggerAdapter) Printf

func (s *StandardLoggerAdapter) Printf(format string, args ...interface{})

func (*StandardLoggerAdapter) Println

func (s *StandardLoggerAdapter) Println(args ...interface{})

func (*StandardLoggerAdapter) SetLevel

func (s *StandardLoggerAdapter) SetLevel(level LogLevel)

SetLevel 设置日志级别

func (*StandardLoggerAdapter) SetShowCaller

func (s *StandardLoggerAdapter) SetShowCaller(show bool)

SetShowCaller 设置是否显示调用者信息

func (*StandardLoggerAdapter) Warn

func (s *StandardLoggerAdapter) Warn(format string, args ...interface{})

Warn 警告日志

func (*StandardLoggerAdapter) WarnContext

func (s *StandardLoggerAdapter) WarnContext(ctx context.Context, format string, args ...interface{})

func (*StandardLoggerAdapter) WarnContextKV added in v0.4.3

func (s *StandardLoggerAdapter) WarnContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*StandardLoggerAdapter) WarnKV

func (s *StandardLoggerAdapter) WarnKV(msg string, keysAndValues ...interface{})

func (*StandardLoggerAdapter) WarnLines added in v0.4.2

func (s *StandardLoggerAdapter) WarnLines(lines ...string)

func (*StandardLoggerAdapter) WarnMsg

func (s *StandardLoggerAdapter) WarnMsg(msg string)

func (*StandardLoggerAdapter) Warnf added in v0.3.0

func (s *StandardLoggerAdapter) Warnf(format string, args ...interface{})

func (*StandardLoggerAdapter) WithContext

func (s *StandardLoggerAdapter) WithContext(ctx context.Context) ILogger

WithContext 的实现

func (*StandardLoggerAdapter) WithError

func (s *StandardLoggerAdapter) WithError(err error) ILogger

WithError 添加错误信息

func (*StandardLoggerAdapter) WithField

func (s *StandardLoggerAdapter) WithField(key string, value interface{}) ILogger

WithField 添加字段

func (*StandardLoggerAdapter) WithFields

func (s *StandardLoggerAdapter) WithFields(fields map[string]interface{}) ILogger

WithFields 添加多个字段

type Stats added in v0.4.0

type Stats struct {
	// 基础计数
	TotalOperations uint64  `json:"total_operations"`
	TotalErrors     uint64  `json:"total_errors"`
	TotalBytes      uint64  `json:"total_bytes"`
	ErrorRate       float64 `json:"error_rate"`

	// 时间统计
	StartTime         time.Time     `json:"start_time"`
	LastOperationTime time.Time     `json:"last_operation_time"`
	Uptime            time.Duration `json:"uptime"`

	// 性能统计
	OperationsPerSecond float64       `json:"operations_per_second"`
	BytesPerSecond      float64       `json:"bytes_per_second"`
	AvgOperationTime    time.Duration `json:"avg_operation_time"`

	// 详细统计
	Operations map[string]*OperationStats `json:"operations"`
	Metrics    map[string]*MetricStats    `json:"metrics"`
	Errors     *ErrorStats                `json:"errors"`
}

Stats 综合统计信息

type StatsCollector added in v0.4.0

type StatsCollector interface {
	// 记录操作
	Record(operation string, duration time.Duration, size uint64)
	RecordError(operation string, err error)
	RecordCount(metric string, value uint64)
	RecordGauge(metric string, value float64)
	RecordHistogram(metric string, value float64)

	// 获取统计
	GetStats() *Stats
	GetOperationStats(operation string) *OperationStats
	GetMetricStats(metric string) *MetricStats
	GetErrorStats() *ErrorStats

	// 重置和清理
	Reset()
	Cleanup(age time.Duration)
}

StatsCollector 统计收集器接口

type SuspiciousType added in v0.4.0

type SuspiciousType struct {
	TypeName       string  `json:"type_name"`
	GrowthRate     float64 `json:"growth_rate"`     // 增长率
	CurrentCount   uint64  `json:"current_count"`   // 当前数量
	CurrentSize    uint64  `json:"current_size"`    // 当前大小
	SuspicionLevel string  `json:"suspicion_level"` // low/medium/high
	Description    string  `json:"description"`
}

SuspiciousType 可疑类型

type TLSConfig added in v0.4.0

type TLSConfig struct {
	Enabled            bool   `json:"enabled" yaml:"enabled"`
	CertFile           string `json:"cert_file" yaml:"cert_file"`
	KeyFile            string `json:"key_file" yaml:"key_file"`
	CAFile             string `json:"ca_file" yaml:"ca_file"`
	InsecureSkipVerify bool   `json:"insecure_skip_verify" yaml:"insecure_skip_verify"`
}

TLSConfig TLS配置

type TextLogFormatter

type TextLogFormatter struct {
	*BaseFormatter
	Template string `json:"template"`
}

TextLogFormatter 文本格式化器

func (*TextLogFormatter) Format

func (f *TextLogFormatter) Format(entry *LogEntry) ([]byte, error)

Format 格式化日志条目

func (*TextLogFormatter) GetName

func (f *TextLogFormatter) GetName() string

GetName 获取格式化器名称

type ThroughputMetrics added in v0.4.0

type ThroughputMetrics struct {
	CurrentThroughput float64 `json:"current_throughput"` // total ops/sec
	AvgThroughput     float64 `json:"avg_throughput"`     // total ops/sec
	PeakThroughput    float64 `json:"peak_throughput"`    // total ops/sec
}

ThroughputMetrics 吞吐量指标

type ThroughputStats added in v0.4.0

type ThroughputStats struct {
	Operations map[string]*OperationThroughput `json:"operations"`
	Overall    *ThroughputMetrics              `json:"overall"`
}

ThroughputStats 吞吐量统计

type TimeFormat added in v0.4.0

type TimeFormat string

TimeFormat 时间格式类型

const (
	TimeFormatStandard TimeFormat = "2006-01-02 15:04:05"
	TimeFormatISO8601  TimeFormat = "2006-01-02T15:04:05Z"
	TimeFormatRFC3339  TimeFormat = "2006-01-02T15:04:05Z07:00"
	TimeFormatUnix     TimeFormat = "unix"
	TimeFormatDisabled TimeFormat = "disabled"
)

type Timing

type Timing struct {
	// contains filtered or unexported fields
}

Timing 计时器辅助结构

func StartTiming

func StartTiming(operation string) *Timing

StartTiming 开始计时

func (*Timing) AddDetail

func (t *Timing) AddDetail(key string, value interface{}) *Timing

AddDetail 添加详细信息

func (*Timing) End

func (t *Timing) End() time.Duration

End 结束计时并记录性能日志

func (*Timing) EndSimple

func (t *Timing) EndSimple() time.Duration

EndSimple 简单结束计时

type TypeStat added in v0.4.0

type TypeStat struct {
	TypeName   string  `json:"type_name"`
	Count      uint64  `json:"count"`
	TotalSize  uint64  `json:"total_size"`
	AvgSize    float64 `json:"avg_size"`
	Percentage float64 `json:"percentage"`
}

TypeStat 类型统计

type UltraFastConfig added in v0.4.0

type UltraFastConfig struct {
	Level      LogLevel   `json:"level" yaml:"level"`
	TimeFormat TimeFormat `json:"time_format" yaml:"time_format"`
	Colorful   bool       `json:"colorful" yaml:"colorful"`
	SyncMode   bool       `json:"sync_mode" yaml:"sync_mode"`
	Output     io.Writer  `json:"-" yaml:"-"`
}

UltraFastConfig 极致性能配置

func NewUltraFastConfig added in v0.4.0

func NewUltraFastConfig() *UltraFastConfig

NewUltraFastConfig 创建极致性能配置

func (*UltraFastConfig) ToConfig added in v0.4.0

func (c *UltraFastConfig) ToConfig() *LogConfig

ToConfig 转换为标准配置

type UltraFastLogger

type UltraFastLogger struct {
	// contains filtered or unexported fields
}

UltraFastLogger 极致性能的日志器

func NewUltraFast added in v0.4.0

func NewUltraFast() *UltraFastLogger

NewUltraFast 创建极致性能日志器(便利函数) 使用优化配置创建UltraFastLogger

func NewUltraFastLogger

func NewUltraFastLogger(config *LogConfig) *UltraFastLogger

NewUltraFastLogger 创建极致性能日志器

func NewUltraFastLoggerNoTime

func NewUltraFastLoggerNoTime(output io.Writer, level LogLevel) *UltraFastLogger

NewUltraFastLoggerNoTime 创建不包含时间戳的极致性能日志器

func (*UltraFastLogger) Clone

func (l *UltraFastLogger) Clone() ILogger

func (*UltraFastLogger) Debug

func (l *UltraFastLogger) Debug(format string, args ...interface{})

实现 ILogger 接口 - 带级别检查优化

func (*UltraFastLogger) DebugContext

func (l *UltraFastLogger) DebugContext(ctx context.Context, format string, args ...interface{})

上下文方法(自动提取 TraceID 和 RequestID)- 优化版本

func (*UltraFastLogger) DebugContextKV added in v0.4.3

func (l *UltraFastLogger) DebugContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*UltraFastLogger) DebugKV

func (l *UltraFastLogger) DebugKV(msg string, keysAndValues ...interface{})

键值对方法(极简版)

func (*UltraFastLogger) DebugLines added in v0.4.2

func (l *UltraFastLogger) DebugLines(lines ...string)

func (*UltraFastLogger) DebugMsg

func (l *UltraFastLogger) DebugMsg(msg string)

纯文本日志方法 - 带级别检查优化

func (*UltraFastLogger) Debugf added in v0.3.0

func (l *UltraFastLogger) Debugf(format string, args ...interface{})

Printf风格方法(与上面相同,但命名更明确) - 带级别检查优化

func (*UltraFastLogger) Error

func (l *UltraFastLogger) Error(format string, args ...interface{})

func (*UltraFastLogger) ErrorContext

func (l *UltraFastLogger) ErrorContext(ctx context.Context, format string, args ...interface{})

func (*UltraFastLogger) ErrorContextKV added in v0.4.3

func (l *UltraFastLogger) ErrorContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*UltraFastLogger) ErrorKV

func (l *UltraFastLogger) ErrorKV(msg string, keysAndValues ...interface{})

func (*UltraFastLogger) ErrorLines added in v0.4.2

func (l *UltraFastLogger) ErrorLines(lines ...string)

func (*UltraFastLogger) ErrorMsg

func (l *UltraFastLogger) ErrorMsg(msg string)

func (*UltraFastLogger) Errorf added in v0.3.0

func (l *UltraFastLogger) Errorf(format string, args ...interface{})

func (*UltraFastLogger) Fatal

func (l *UltraFastLogger) Fatal(format string, args ...interface{})

func (*UltraFastLogger) FatalContext

func (l *UltraFastLogger) FatalContext(ctx context.Context, format string, args ...interface{})

func (*UltraFastLogger) FatalContextKV added in v0.4.3

func (l *UltraFastLogger) FatalContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*UltraFastLogger) FatalKV

func (l *UltraFastLogger) FatalKV(msg string, keysAndValues ...interface{})

func (*UltraFastLogger) FatalMsg

func (l *UltraFastLogger) FatalMsg(msg string)

func (*UltraFastLogger) Fatalf added in v0.3.0

func (l *UltraFastLogger) Fatalf(format string, args ...interface{})

func (*UltraFastLogger) GetContextExtractor added in v0.4.1

func (l *UltraFastLogger) GetContextExtractor() ContextExtractor

GetContextExtractor 获取当前的上下文提取器

func (*UltraFastLogger) GetLevel

func (l *UltraFastLogger) GetLevel() LogLevel

func (*UltraFastLogger) Info

func (l *UltraFastLogger) Info(format string, args ...interface{})

func (*UltraFastLogger) InfoContext

func (l *UltraFastLogger) InfoContext(ctx context.Context, format string, args ...interface{})

func (*UltraFastLogger) InfoContextKV added in v0.4.3

func (l *UltraFastLogger) InfoContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*UltraFastLogger) InfoKV

func (l *UltraFastLogger) InfoKV(msg string, keysAndValues ...interface{})

func (*UltraFastLogger) InfoLines added in v0.4.2

func (l *UltraFastLogger) InfoLines(lines ...string)

多行日志方法

func (*UltraFastLogger) InfoMsg

func (l *UltraFastLogger) InfoMsg(msg string)

func (*UltraFastLogger) Infof added in v0.3.0

func (l *UltraFastLogger) Infof(format string, args ...interface{})

func (*UltraFastLogger) IsLevelEnabled

func (l *UltraFastLogger) IsLevelEnabled(level LogLevel) bool

func (*UltraFastLogger) IsShowCaller

func (l *UltraFastLogger) IsShowCaller() bool

func (*UltraFastLogger) Log

func (l *UltraFastLogger) Log(level LogLevel, msg string)

日志条目方法

func (*UltraFastLogger) LogContext

func (l *UltraFastLogger) LogContext(ctx context.Context, level LogLevel, msg string)

func (*UltraFastLogger) LogKV

func (l *UltraFastLogger) LogKV(level LogLevel, msg string, keysAndValues ...interface{})

func (*UltraFastLogger) LogWithFields

func (l *UltraFastLogger) LogWithFields(level LogLevel, msg string, fields map[string]interface{})

func (*UltraFastLogger) Print

func (l *UltraFastLogger) Print(v ...interface{})

简化的 Print 方法

func (*UltraFastLogger) Printf

func (l *UltraFastLogger) Printf(format string, v ...interface{})

func (*UltraFastLogger) Println

func (l *UltraFastLogger) Println(v ...interface{})

func (*UltraFastLogger) SetContextExtractor added in v0.4.1

func (l *UltraFastLogger) SetContextExtractor(extractor ContextExtractor)

SetContextExtractor 设置自定义上下文提取器 extractor: 自定义的上下文信息提取函数,如果为 nil 则使用默认提取器

func (*UltraFastLogger) SetLevel

func (l *UltraFastLogger) SetLevel(level LogLevel)

配置方法

func (*UltraFastLogger) SetShowCaller

func (l *UltraFastLogger) SetShowCaller(show bool)

func (*UltraFastLogger) Warn

func (l *UltraFastLogger) Warn(format string, args ...interface{})

func (*UltraFastLogger) WarnContext

func (l *UltraFastLogger) WarnContext(ctx context.Context, format string, args ...interface{})

func (*UltraFastLogger) WarnContextKV added in v0.4.3

func (l *UltraFastLogger) WarnContextKV(ctx context.Context, msg string, keysAndValues ...interface{})

func (*UltraFastLogger) WarnKV

func (l *UltraFastLogger) WarnKV(msg string, keysAndValues ...interface{})

func (*UltraFastLogger) WarnLines added in v0.4.2

func (l *UltraFastLogger) WarnLines(lines ...string)

func (*UltraFastLogger) WarnMsg

func (l *UltraFastLogger) WarnMsg(msg string)

func (*UltraFastLogger) Warnf added in v0.3.0

func (l *UltraFastLogger) Warnf(format string, args ...interface{})

func (*UltraFastLogger) WithContext

func (l *UltraFastLogger) WithContext(ctx context.Context) ILogger

func (*UltraFastLogger) WithError

func (l *UltraFastLogger) WithError(err error) ILogger

func (*UltraFastLogger) WithField

func (l *UltraFastLogger) WithField(key string, value interface{}) ILogger

字段方法返回简化的包装器

func (*UltraFastLogger) WithFields

func (l *UltraFastLogger) WithFields(fields map[string]interface{}) ILogger

type UltraLightMonitor added in v0.4.0

type UltraLightMonitor struct {
	// contains filtered or unexported fields
}

UltraLightMonitor 超轻量级监控器 - 仅原子操作

func NewUltraLightMonitor added in v0.4.0

func NewUltraLightMonitor() *UltraLightMonitor

NewUltraLightMonitor 创建超轻量级监控器

func (*UltraLightMonitor) CheckMemory added in v0.4.0

func (u *UltraLightMonitor) CheckMemory() (heap uint64, changed bool)

CheckMemory 检查内存 - 限频版本

func (*UltraLightMonitor) Disable added in v0.4.0

func (u *UltraLightMonitor) Disable()

Disable 禁用监控

func (*UltraLightMonitor) Enable added in v0.4.0

func (u *UltraLightMonitor) Enable()

Enable 启用监控

func (*UltraLightMonitor) Stats added in v0.4.0

func (u *UltraLightMonitor) Stats() (ops, errors uint64, errorRate float64)

Stats 获取统计信息

func (*UltraLightMonitor) String added in v0.4.0

func (u *UltraLightMonitor) String() string

String 字符串表示

func (*UltraLightMonitor) Track added in v0.4.0

func (u *UltraLightMonitor) Track() func(error)

Track 跟踪操作 - 零开销版本

type WebhookHook

type WebhookHook struct {
	*BaseHook
	URL        string            `json:"url"`
	Method     string            `json:"method"`
	Headers    map[string]string `json:"headers"`
	Timeout    time.Duration     `json:"timeout"`
	MaxRetries int               `json:"max_retries"`
	RetryDelay time.Duration     `json:"retry_delay"`
	// contains filtered or unexported fields
}

WebhookHook HTTP Webhook钩子

func (*WebhookHook) Fire

func (h *WebhookHook) Fire(entry *LogEntry) error

Fire 执行钩子

type WebhookHookConfig added in v0.4.0

type WebhookHookConfig struct {
	URL         string            `json:"url" yaml:"url"`
	Method      string            `json:"method" yaml:"method"`
	Headers     map[string]string `json:"headers" yaml:"headers"`
	Timeout     time.Duration     `json:"timeout" yaml:"timeout"`
	RetryCount  int               `json:"retry_count" yaml:"retry_count"`
	ContentType string            `json:"content_type" yaml:"content_type"`
	Template    string            `json:"template" yaml:"template"`
}

WebhookHookConfig Webhook钩子配置

type WriterStats

type WriterStats struct {
	BytesWritten int64         `json:"bytes_written"`
	LinesWritten int64         `json:"lines_written"`
	ErrorCount   int64         `json:"error_count"`
	LastWrite    time.Time     `json:"last_write"`
	StartTime    time.Time     `json:"start_time"`
	Uptime       time.Duration `json:"uptime"`
}

WriterStats 输出器统计信息

func NewWriterStats

func NewWriterStats() *WriterStats

NewWriterStats 创建输出器统计信息

func (*WriterStats) AddBytes

func (ws *WriterStats) AddBytes(bytes int64)

AddBytes 增加字节统计

func (*WriterStats) AddError

func (ws *WriterStats) AddError()

AddError 增加错误统计

type WriterType

type WriterType string

WriterType 输出器类型

const (
	ConsoleWriter WriterType = "console"
	FileWriter    WriterType = "file"
	RotateWriter  WriterType = "rotate"
	BufferWriter  WriterType = "buffer"
	MultiWriter   WriterType = "multi"
	NetworkWriter WriterType = "network"
)

type XMLLogFormatter

type XMLLogFormatter struct {
	*BaseFormatter
	RootElement string `json:"root_element"`
	LogElement  string `json:"log_element"`
}

XMLLogFormatter XML格式化器

func (*XMLLogFormatter) Format

func (f *XMLLogFormatter) Format(entry *LogEntry) ([]byte, error)

Format 格式化日志条目

func (*XMLLogFormatter) GetName

func (f *XMLLogFormatter) GetName() string

GetName 获取格式化器名称

Directories

Path Synopsis
examples
adapters command
basic command
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-08 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-22 13:43:27 * @FilePath: \go-logger\examples\basic\main.go * @Description: 基本使用示例 - 演示logger.New()和基础功能 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-08 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-22 13:43:27 * @FilePath: \go-logger\examples\basic\main.go * @Description: 基本使用示例 - 演示logger.New()和基础功能 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
benchmark command
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-08 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-08 00:00:00 * @FilePath: \go-logger\examples\benchmark\main.go * @Description: 性能基准测试示例 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-08 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-08 00:00:00 * @FilePath: \go-logger\examples\benchmark\main.go * @Description: 性能基准测试示例 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
compatibility command
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-09 19:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-09 19:00:00 * @FilePath: \go-logger\examples\compatibility\main.go * @Description: 多框架兼容性示例,展示如何使用 go-logger 模拟不同日志框架的API风格 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-09 19:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-09 19:00:00 * @FilePath: \go-logger\examples\compatibility\main.go * @Description: 多框架兼容性示例,展示如何使用 go-logger 模拟不同日志框架的API风格 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
configuration command
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-08 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-22 00:00:00 * @FilePath: \go-logger\examples\configuration\main.go * @Description: 配置系统示例 - 演示完整的配置选项和最佳实践 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-08 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-22 00:00:00 * @FilePath: \go-logger\examples\configuration\main.go * @Description: 配置系统示例 - 演示完整的配置选项和最佳实践 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
configurations command
context command
convenience command
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-22 14:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-22 14:00:00 * @FilePath: \go-logger\examples\convenience\main.go * @Description: 便利函数使用示例 - 演示NewUltraFast()、NewOptimized()和New() * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-22 14:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-22 14:00:00 * @FilePath: \go-logger\examples\convenience\main.go * @Description: 便利函数使用示例 - 演示NewUltraFast()、NewOptimized()和New() * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
custom_context_extractor command
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-24 11:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-24 11:30:00 * @FilePath: \go-logger\examples\custom_context_extractor\main.go * @Description: 自定义上下文提取器使用示例 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2024-11-24 11:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2024-11-24 11:30:00 * @FilePath: \go-logger\examples\custom_context_extractor\main.go * @Description: 自定义上下文提取器使用示例 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
enhanced command
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-09 18:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-09 18:00:00 * @FilePath: \go-logger\examples\enhanced\main.go * @Description: 增强接口功能示例,展示新增的上下文感知、键值对日志、多框架兼容等特性 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-09 18:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-09 18:00:00 * @FilePath: \go-logger\examples\enhanced\main.go * @Description: 增强接口功能示例,展示新增的上下文感知、键值对日志、多框架兼容等特性 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
factory command
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-08 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-08 00:00:00 * @FilePath: \go-logger\examples\factory\main.go * @Description: 工厂模式使用示例 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-08 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-08 00:00:00 * @FilePath: \go-logger\examples\factory\main.go * @Description: 工厂模式使用示例 * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
formatters command
monitoring command
real-world command
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-22 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-22 12:15:22 * @FilePath: \go-logger\examples\real-world\main.go * @Description: 实际应用场景示例 - 展示在真实项目中如何使用logger.New() * * Copyright (c) 2024 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-22 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-22 12:15:22 * @FilePath: \go-logger\examples\real-world\main.go * @Description: 实际应用场景示例 - 展示在真实项目中如何使用logger.New() * * Copyright (c) 2024 by kamalyes, All Rights Reserved.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL