# ixLog **Repository Path**: ixgo/log ## Basic Information - **Project Name**: ixLog - **Description**: golang 日志帮助类 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-09-19 - **Last Updated**: 2025-09-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # ixLog - 企业级 Go 日志工具包 [![Go Version](https://img.shields.io/badge/Go-%3E%3D%201.18-blue.svg)](https://golang.org/) [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE) ixLog 是一个功能强大、高性能的 Go 语言日志工具包,专为现代分布式应用设计,提供完整的日志记录、分布式追踪、性能监控和安全脱敏功能。 ## ✨ 核心特性 - 🎯 **完整的日志级别**: TRACE、DEBUG、INFO、WARN、ERROR、FATAL - 🔗 **分布式追踪**: 内置 TraceID、SpanID、调用链追踪支持 - 📊 **多输出目标**: 控制台、文件、网络、自定义输出 - 🎨 **多种格式**: 文本、JSON、Logfmt、自定义模板格式 - 🔄 **智能轮转**: 按大小、时间自动轮转,支持压缩和清理 - 🚀 **极致性能**: 异步写入、缓冲优化、对象池、零分配 - 🛡️ **安全脱敏**: 智能识别和脱敏敏感信息(手机号、邮箱、密码等) - 🎣 **丰富钩子**: 支持文件、邮件、指标收集、限流等钩子 - 🔧 **易于使用**: 流畅的链式调用、上下文支持 - 📈 **实时监控**: 内置统计、性能指标、健康检查 ## 📦 安装 ```bash go get gitee.com/ixgo/log ``` ## 🚀 快速开始 ### 基础使用 ```go package main import ( "context" "fmt" "gitee.com/ixgo/log" ) func main() { // 快速开始 - 开发环境 ixLog.SetupDevelopment("my-app") // 基础日志 ixLog.Info("应用启动") ixLog.Warn("这是一个警告") ixLog.Error("这是一个错误") // 带字段的日志 ixLog.InfoWithFields(map[string]interface{}{ "user_id": "12345", "action": "login", }, "用户登录成功") // 带错误的日志 err := fmt.Errorf("数据库连接失败") ixLog.ErrorWithError(err, "操作失败") // 带上下文的日志 ctx := context.Background() ixLog.InfoWithContext(ctx, "带上下文的日志") } ``` ### 自定义日志器 ```go // 创建自定义配置的日志器 logger, err := ixLog.NewLogger( ixLog.WithLevel(ixLog.DEBUG), ixLog.WithFormat(ixLog.JSONFormat), ixLog.WithColor(false), ixLog.WithCaller(true), ixLog.WithFileOutput("/var/log/app.log", ixLog.WithRotation(ixLog.SizeRotation), ixLog.WithMaxSize(100), // 100MB ixLog.WithCompress(true), ixLog.WithMaxAge(30), // 保留30天 ), ixLog.WithAsync(true), ixLog.WithBufferSize(4096), ixLog.WithAppInfo("my-app", "production"), ) if err != nil { panic(err) } defer logger.Close() // 使用自定义日志器 logger.WithFields(map[string]interface{}{ "method": "POST", "url": "/api/users", "status": 201, }).Info("API请求完成") ``` ## 🔗 分布式追踪 ### 基础追踪 ```go func handleRequest(ctx context.Context) error { // 开始追踪 ctx, span := ixLog.StartTrace(ctx, "handle_request") defer ixLog.FinishTrace(span) // 设置追踪标签 span.SetTag("http.method", "POST") span.SetTag("http.url", "/api/users") // 带追踪的日志 ixLog.InfoWithContext(ctx, "开始处理请求") // 子追踪 if err := processUser(ctx); err != nil { span.SetError(err) return err } ixLog.InfoWithContext(ctx, "请求处理完成") return nil } func processUser(ctx context.Context) error { // 子追踪 ctx, span := ixLog.StartChildTrace(ctx, "process_user") defer ixLog.FinishTrace(span) ixLog.DebugWithContext(ctx, "处理用户数据") // 模拟数据库操作 return ixLog.TraceFunction(ctx, "database_query", func(ctx context.Context) error { ixLog.DebugWithContext(ctx, "执行数据库查询") return nil }) } ``` ### 追踪头注入/提取 ```go // HTTP服务端 - 提取追踪信息 func httpHandler(w http.ResponseWriter, r *http.Request) { // 从HTTP头提取追踪信息 headers := make(map[string]string) for key, values := range r.Header { if len(values) > 0 { headers[key] = values[0] } } traceCtx := ixLog.ExtractTraceHeaders(headers) ctx := ixLog.WithTraceContext(r.Context(), traceCtx) // 处理请求 handleRequest(ctx) } // HTTP客户端 - 注入追踪信息 func httpClient(ctx context.Context) { req, _ := http.NewRequest("GET", "http://api.example.com", nil) // 注入追踪头 headers := make(map[string]string) ixLog.InjectTraceHeaders(ctx, headers) for key, value := range headers { req.Header.Set(key, value) } // 发送请求... } ``` ## 📝 配置选项 ### 基础配置 ```go logger, err := ixLog.NewLogger( // 日志级别 ixLog.WithLevel(ixLog.INFO), // 输出格式 ixLog.WithFormat(ixLog.JSONFormat), // 颜色和调用者信息 ixLog.WithColor(true), ixLog.WithCaller(true), // 时间格式 ixLog.WithTimeFormat("2006-01-02 15:04:05.000"), // 应用信息 ixLog.WithAppInfo("my-app", "production"), ) ``` ### 输出配置 ```go logger, err := ixLog.NewLogger( // 控制台输出 ixLog.WithConsoleOutput(true), // 文件输出 ixLog.WithFileOutput("/var/log/app.log"), // 文件轮转 ixLog.WithFileOutput("/var/log/app.log", ixLog.WithRotation(ixLog.SizeRotation), ixLog.WithMaxSize(100), // 100MB ixLog.WithMaxBackups(10), // 保留10个备份 ixLog.WithMaxAge(30), // 保留30天 ixLog.WithCompress(true), // 压缩旧文件 ), // 网络输出 ixLog.WithNetworkOutput("tcp", "logserver:514"), // 异步和缓冲 ixLog.WithAsync(true), ixLog.WithBufferSize(4096), ixLog.WithFlushInterval(100*time.Millisecond), ) ``` ### 追踪配置 ```go logger, err := ixLog.NewLogger( // 启用追踪 ixLog.WithTrace(true, 5, 1.0), // 启用,调用栈深度5,100%采样 // 调用者信息 ixLog.WithCaller(true), ixLog.WithCallerSkip(1), // 调用栈(仅TRACE和ERROR级别) ixLog.WithStackDepth(5), ) ``` ### 安全脱敏 ```go logger, err := ixLog.NewLogger( // 启用脱敏 ixLog.WithSanitize(true, // 敏感字段 []string{"password", "token", "secret", "key", "auth"}, // 敏感模式(正则表达式) []string{ `\b1[3-9]\d{9}\b`, // 手机号 `\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b`, // 邮箱 `\b\d{15}|\d{18}\b`, // 身份证号 }, ), ) // 测试脱敏效果 logger.WithFields(map[string]interface{}{ "password": "secret123", // 会被脱敏为 "****" "phone": "13800138000", // 会被脱敏为 "138****8000" "email": "user@example.com", // 会被脱敏为 "u***@example.com" }).Info("用户信息") ``` ## 🎣 钩子系统 ### 文件钩子 ```go // 错误日志单独写入文件 errorHook, err := ixLog.NewFileHook("/var/log/error.log", []ixLog.LogLevel{ixLog.ERROR, ixLog.FATAL}) if err != nil { panic(err) } defer errorHook.Close() logger.AddHook(errorHook) ``` ### 邮件告警钩子 ```go // 严重错误发送邮件告警 emailHook := ixLog.NewEmailHook(&ixLog.EmailConfig{ SMTPHost: "smtp.example.com", SMTPPort: 587, Username: "alert@example.com", Password: "password", From: "alert@example.com", To: []string{"admin@example.com"}, Subject: "应用错误告警", }, []ixLog.LogLevel{ixLog.FATAL}) logger.AddHook(emailHook) ``` ### 自定义钩子 ```go // 自定义函数钩子 customHook := ixLog.NewFunctionHook( func(entry *ixLog.LogEntry) error { if entry.Level == ixLog.ERROR { // 发送到监控系统 fmt.Printf("发送错误到监控系统: %s\n", entry.Message) } return nil }, []ixLog.LogLevel{ixLog.ERROR, ixLog.FATAL}, ) logger.AddHook(customHook) ``` ### 限流钩子 ```go // 限制错误日志的发送频率 baseHook := ixLog.NewFileHook("/var/log/error.log", []ixLog.LogLevel{ixLog.ERROR}) rateLimitHook := ixLog.NewRateLimitHook(baseHook, 10, 20) // 每秒10次,突发20次 logger.AddHook(rateLimitHook) ``` ## 🔧 高级功能 ### 业务日志记录 ```go ctx := context.Background() // 用户操作日志 ixLog.LogUserAction(ctx, "user123", "purchase", map[string]interface{}{ "product_id": "prod456", "amount": 99.99, "currency": "USD", }) // HTTP请求日志 ixLog.LogHTTPRequest(ctx, "POST", "/api/orders", 201, 150*time.Millisecond) // 数据库查询日志 ixLog.LogDBQuery(ctx, "SELECT * FROM users WHERE id = ?", 50*time.Millisecond, nil) // 外部服务调用日志 ixLog.LogExternalCall(ctx, "payment_gateway", "charge", 200*time.Millisecond, nil) // 性能指标日志 ixLog.LogPerformance(ctx, "order_processing", 400*time.Millisecond, map[string]interface{}{ "steps": 5, "cache_hits": 3, }) // 安全事件日志 ixLog.LogSecurityEvent(ctx, "suspicious_login", "high", map[string]interface{}{ "ip": "192.168.1.100", "attempts": 5, }) ``` ### 性能测量 ```go // 函数执行时间测量 ixLog.Measure(ctx, "database_operation", func() { // 执行数据库操作 time.Sleep(100 * time.Millisecond) }) // 追踪函数执行 err := ixLog.TraceFunction(ctx, "process_order", func(ctx context.Context) error { ixLog.InfoWithContext(ctx, "开始处理订单") // 嵌套追踪 return ixLog.TraceFunction(ctx, "validate_payment", func(ctx context.Context) error { ixLog.DebugWithContext(ctx, "验证支付信息") return nil }) }) ``` ### 安全的并发 ```go // 安全的goroutine启动(自动处理panic) ixLog.SafeGo(ctx, "background_worker", func(ctx context.Context) { ixLog.InfoWithContext(ctx, "后台任务开始") // 即使这里发生panic,也会被自动捕获和记录 panic("模拟错误") }) // Panic恢复 defer func() { if recovered := recover(); recovered != nil { ixLog.LogPanicRecovery(ctx, recovered, "main_function") } }() ``` ## 🎨 格式化器 ### 文本格式 ```go logger, err := ixLog.NewLogger( ixLog.WithFormat(ixLog.TextFormat), ixLog.WithColor(true), ixLog.WithCaller(true), ) // 输出示例: // [2025-09-18 12:00:00.123] INFO [abc123:def456] main.go:42 main() 用户登录 | user_id=12345 action=login ``` ### JSON格式 ```go logger, err := ixLog.NewLogger( ixLog.WithFormat(ixLog.JSONFormat), ixLog.WithCaller(true), ) // 输出示例: // {"timestamp":"2025-09-18 12:00:00.123","level":"INFO","message":"用户登录","trace_id":"abc123","span_id":"def456","caller":{"file":"main.go","line":42,"function":"main"},"user_id":"12345","action":"login"} ``` ### 自定义模板 ```go // 使用预定义模板 logger, err := ixLog.NewLogger( ixLog.WithFormat(ixLog.TextFormat), ixLog.WithTemplate(ixLog.SimpleTemplate), // 简洁模板 ) // 自定义格式化器 customFormatter := ixLog.NewCustomFormatter(func(entry *ixLog.LogEntry) ([]byte, error) { return []byte(fmt.Sprintf("CUSTOM: %s [%s] %s\n", entry.Timestamp.Format("15:04:05"), entry.Level.String(), entry.Message)), nil }) ``` ## 📊 多输出目标 ### 文件输出 ```go logger, err := ixLog.NewLogger( // 主日志文件 ixLog.WithFileOutput("/var/log/app.log", ixLog.WithRotation(ixLog.SizeRotation), ixLog.WithMaxSize(100), ixLog.WithCompress(true), ), // 错误日志单独文件 ixLog.WithFileOutput("/var/log/error.log", ixLog.WithLevels([]ixLog.LogLevel{ixLog.ERROR, ixLog.FATAL}), ), ) ``` ### 网络输出 ```go logger, err := ixLog.NewLogger( // Syslog服务器 ixLog.WithNetworkOutput("udp", "logserver:514"), // 自定义网络输出 ixLog.WithNetworkOutput("tcp", "elk-server:5000"), ) ``` ### 多重输出 ```go logger, err := ixLog.NewLogger( // 同时输出到控制台和文件 ixLog.WithConsoleOutput(true), ixLog.WithFileOutput("/var/log/app.log"), ixLog.WithNetworkOutput("udp", "logserver:514"), ) ``` ## 🔄 日志轮转 ### 按大小轮转 ```go logger, err := ixLog.NewLogger( ixLog.WithFileOutput("/var/log/app.log", ixLog.WithRotation(ixLog.SizeRotation), ixLog.WithMaxSize(100), // 100MB触发轮转 ixLog.WithMaxBackups(10), // 保留10个备份文件 ixLog.WithCompress(true), // 压缩旧文件 ), ) ``` ### 按时间轮转 ```go logger, err := ixLog.NewLogger( ixLog.WithFileOutput("/var/log/app.log", ixLog.WithRotation(ixLog.TimeRotation), ixLog.WithRotationTime(24*time.Hour), // 每天轮转 ixLog.WithMaxAge(30), // 保留30天 ixLog.WithCompress(true), ), ) ``` ### 组合轮转 ```go logger, err := ixLog.NewLogger( ixLog.WithFileOutput("/var/log/app.log", ixLog.WithRotation(ixLog.BothRotation), ixLog.WithMaxSize(100), // 100MB或 ixLog.WithRotationTime(24*time.Hour), // 24小时触发轮转 ixLog.WithMaxBackups(10), ixLog.WithMaxAge(30), ixLog.WithCompress(true), ), ) ``` ## 🛡️ 安全脱敏 ### 自动脱敏 ```go logger, err := ixLog.NewLogger( ixLog.WithSanitize(true, // 敏感字段名 []string{"password", "token", "secret", "key", "auth", "credit_card"}, // 敏感模式(正则表达式) []string{ `\b1[3-9]\d{9}\b`, // 手机号 `\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b`, // 邮箱 `\b\d{15}|\d{18}\b`, // 身份证号 `\b\d{4}-\d{4}-\d{4}-\d{4}\b`, // 信用卡号 }, ), ) // 测试脱敏 logger.WithFields(map[string]interface{}{ "password": "secret123", // -> "****" "phone": "13800138000", // -> "138****8000" "email": "user@example.com", // -> "u***@example.com" "credit_card": "1234-5678-9012-3456", // -> "1234-****-****-3456" }).Info("用户信息") // 敏感信息会被自动脱敏 ``` ### 自定义脱敏规则 ```go // 创建高级脱敏器 sanitizer := ixLog.NewAdvancedSanitizer( []string{"password", "token"}, []string{`\b1[3-9]\d{9}\b`}, ) // 添加自定义脱敏规则 err := sanitizer.AddCustomRule( "bank_card", `\b\d{4}-\d{4}-\d{4}-\d{4}\b`, func(s string) string { return ixLog.MaskBankCard(s) // 1234-****-****-3456 }, ) logger, err := ixLog.NewLogger( ixLog.WithCustomSanitizer(sanitizer), ) ``` ## 📈 监控和统计 ### 获取统计信息 ```go // 获取日志统计 if statsProvider, ok := logger.(interface{ GetStats() *ixLog.Stats }); ok { stats := statsProvider.GetStats() fmt.Printf("总日志数: %d\n", stats.TotalEntries) fmt.Printf("错误数: %d\n", stats.ErrorCount) fmt.Printf("丢弃数: %d\n", stats.DroppedEntries) fmt.Printf("运行时间: %v\n", stats.Uptime) // 各级别统计 for level, count := range stats.LevelCounts { fmt.Printf("%s: %d\n", level.String(), count) } } ``` ### 性能监控 ```go // 性能指标钩子 metricsHook := ixLog.NewMetricsHook() logger.AddHook(metricsHook) // 获取指标 metrics := metricsHook.GetMetrics() for level, count := range metrics { fmt.Printf("级别 %s: %d 条日志\n", level.String(), count) } ``` ## 🎯 预设日志器 ### 开发环境 ```go // 开发环境日志器(详细输出,彩色,调用者信息) ixLog.SetupDevelopment("my-app") // 或者创建开发环境日志器 devLogger, err := ixLog.NewDevelopmentLogger() ``` ### 生产环境 ```go // 生产环境日志器(JSON格式,文件输出,轮转) err := ixLog.SetupProduction("my-app", "/var/log") // 或者创建生产环境日志器 prodLogger, err := ixLog.NewProductionLogger("/var/log/app.log") ``` ### 测试环境 ```go // 测试环境日志器(静默模式) testLogger, err := ixLog.NewTestLogger() ``` ## 🔧 环境变量配置 ```bash # 设置环境变量 export LOG_LEVEL=DEBUG export LOG_FORMAT=json export LOG_FILE=/var/log/app.log export APP_NAME=my-app export ENVIRONMENT=production export ENABLE_TRACE=true export SAMPLE_RATE=0.1 ``` ```go // 从环境变量加载配置 config := ixLog.LoadConfigFromEnv() logger, err := ixLog.NewLogger(ixLog.WithConfig(config)) ``` ## 📄 JSON配置文件 ```json { "level": "INFO", "format": "json", "enable_color": false, "enable_caller": true, "enable_trace": true, "sample_rate": 0.1, "app_name": "my-app", "environment": "production", "outputs": [ { "type": "file", "enable": true, "file_path": "/var/log/app.log", "rotation": "size", "max_size": 100, "max_backups": 10, "max_age": 30, "compress": true } ], "enable_sanitize": true, "sanitize_fields": ["password", "token", "secret"], "enable_async": true, "buffer_size": 4096, "flush_interval": "100ms" } ``` ```go // 从JSON文件加载配置 config, err := ixLog.LoadConfigFromFile("config.json") if err != nil { panic(err) } logger, err := ixLog.NewLogger(ixLog.WithConfig(config)) ``` ## 🎪 使用场景 ### Web应用 ```go // HTTP中间件 func LoggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() // 创建带追踪的上下文 ctx, span := ixLog.StartTrace(r.Context(), "http_request") defer ixLog.FinishTrace(span) // 设置HTTP标签 span.SetTag("http.method", r.Method) span.SetTag("http.url", r.URL.Path) // 记录请求开始 ixLog.InfoWithContext(ctx, "HTTP请求开始") // 包装ResponseWriter记录状态码 wrapped := &responseWriter{ResponseWriter: w, statusCode: 200} // 执行下一个处理器 next.ServeHTTP(wrapped, r.WithContext(ctx)) // 记录请求完成 duration := time.Since(start) span.SetTag("http.status_code", wrapped.statusCode) ixLog.LogHTTPRequest(ctx, r.Method, r.URL.Path, wrapped.statusCode, duration) }) } ``` ### 微服务 ```go // 服务间调用追踪 func callUserService(ctx context.Context, userID string) (*User, error) { // 开始子追踪 ctx, span := ixLog.StartChildTrace(ctx, "call_user_service") defer ixLog.FinishTrace(span) span.SetTag("service", "user") span.SetTag("user_id", userID) ixLog.InfoWithContext(ctx, "调用用户服务") // HTTP请求头注入 req, _ := http.NewRequest("GET", fmt.Sprintf("/users/%s", userID), nil) headers := make(map[string]string) ixLog.InjectTraceHeaders(ctx, headers) for key, value := range headers { req.Header.Set(key, value) } // 发送请求... resp, err := http.DefaultClient.Do(req) if err != nil { span.SetError(err) ixLog.ErrorWithContext(ctx, "用户服务调用失败", err) return nil, err } defer resp.Body.Close() ixLog.InfoWithContext(ctx, "用户服务调用成功") return parseUser(resp.Body) } ``` ### 数据库操作 ```go func queryUsers(ctx context.Context, db *sql.DB) ([]User, error) { // 追踪数据库操作 ctx, span := ixLog.StartChildTrace(ctx, "database_query") defer ixLog.FinishTrace(span) span.SetTag("db.type", "mysql") span.SetTag("db.operation", "SELECT") span.SetTag("db.table", "users") query := "SELECT id, name, email FROM users WHERE active = ?" span.SetTag("db.statement", query) start := time.Now() rows, err := db.QueryContext(ctx, query, true) duration := time.Since(start) // 记录数据库查询日志 ixLog.LogDBQuery(ctx, query, duration, err) if err != nil { span.SetError(err) return nil, err } defer rows.Close() // 处理结果... var users []User for rows.Next() { var user User if err := rows.Scan(&user.ID, &user.Name, &user.Email); err != nil { ixLog.ErrorWithContext(ctx, "扫描用户数据失败", err) continue } users = append(users, user) } ixLog.InfoWithContext(ctx, fmt.Sprintf("查询到 %d 个用户", len(users))) return users, nil } ``` ## ⚙️ 配置参考 ### 完整配置选项 ```go logger, err := ixLog.NewLogger( // === 基础配置 === ixLog.WithLevel(ixLog.INFO), // 日志级别 ixLog.WithFormat(ixLog.JSONFormat), // 输出格式 ixLog.WithColor(true), // 启用颜色 ixLog.WithCaller(true), // 调用者信息 ixLog.WithCallerSkip(1), // 调用者跳过层数 ixLog.WithTimeFormat("2006-01-02 15:04:05.000"), // 时间格式 ixLog.WithTimezone("Asia/Shanghai"), // 时区 // === 输出配置 === ixLog.WithConsoleOutput(true), // 控制台输出 ixLog.WithFileOutput("/var/log/app.log"), // 文件输出 ixLog.WithNetworkOutput("udp", "logserver:514"), // 网络输出 // === 异步和缓冲 === ixLog.WithAsync(true), // 异步写入 ixLog.WithBufferSize(4096), // 缓冲区大小 ixLog.WithFlushInterval(100*time.Millisecond), // 刷新间隔 // === 追踪配置 === ixLog.WithTrace(true, 5, 1.0), // 启用追踪,栈深度5,100%采样 ixLog.WithStackDepth(5), // 调用栈深度 // === 应用信息 === ixLog.WithAppInfo("my-app", "production"), // 应用名和环境 ixLog.WithHostname("web-server-01"), // 主机名 // === 全局字段 === ixLog.WithGlobalFields(map[string]interface{}{ "service": "user-service", "version": "1.0.0", }), // === 安全脱敏 === ixLog.WithSanitize(true, []string{"password", "token", "secret"}, []string{`\b1[3-9]\d{9}\b`}, ), // === 钩子配置 === ixLog.WithHooks(true), // 启用钩子 ) ``` ### 文件轮转配置 ```go // 详细的文件轮转配置 logger, err := ixLog.NewLogger( ixLog.WithFileOutput("/var/log/app.log", // 轮转策略 ixLog.WithRotation(ixLog.SizeRotation), // 按大小轮转 ixLog.WithMaxSize(100), // 最大100MB ixLog.WithMaxBackups(10), // 最多10个备份 ixLog.WithMaxAge(30), // 保留30天 // 压缩和清理 ixLog.WithCompress(true), // 压缩旧文件 ixLog.WithCleanup(true), // 自动清理 // 文件权限 ixLog.WithFileMode(0644), // 文件权限 ), ) ``` ## 🎭 环境适配 ### 开发环境 ```go // 开发环境配置 ixLog.SetupDevelopment("my-app") // 等价于: logger, _ := ixLog.NewLogger( ixLog.WithLevel(ixLog.DEBUG), ixLog.WithFormat(ixLog.TextFormat), ixLog.WithColor(true), ixLog.WithCaller(true), ixLog.WithConsoleOutput(true), ixLog.WithTrace(true, 5, 1.0), ixLog.WithAppInfo("my-app", "development"), ) ``` ### 生产环境 ```go // 生产环境配置 err := ixLog.SetupProduction("my-app", "/var/log") // 等价于: logger, _ := ixLog.NewLogger( ixLog.WithLevel(ixLog.INFO), ixLog.WithFormat(ixLog.JSONFormat), ixLog.WithColor(false), ixLog.WithCaller(false), ixLog.WithFileOutput("/var/log/my-app.log", ixLog.WithRotation(ixLog.SizeRotation), ixLog.WithMaxSize(100), ixLog.WithCompress(true), ), ixLog.WithAsync(true), ixLog.WithSanitize(true, nil, nil), ixLog.WithAppInfo("my-app", "production"), ) ``` ### 测试环境 ```go // 测试环境配置(静默模式) testLogger, err := ixLog.NewTestLogger() // 等价于: logger, _ := ixLog.NewLogger( ixLog.WithLevel(ixLog.WARN), ixLog.WithConsoleOutput(false), ixLog.WithCaller(false), ixLog.WithTrace(false, 0, 0), ) ``` ## 🔧 高级用法 ### 链式调用 ```go // 流畅的链式调用 logger.WithContext(ctx). WithField("user_id", "12345"). WithField("action", "purchase"). WithError(err). Error("购买失败") // 复杂的链式调用 logger.WithTrace("abc123", "def456", ""). WithFields(map[string]interface{}{ "service": "payment", "amount": 99.99, }). WithError(paymentErr). Error("支付处理失败") ``` ### 上下文传递 ```go // 在上下文中传递日志器 ctx = ixLog.ContextWithLogger(ctx, logger) // 从上下文获取日志器 logger := ixLog.LoggerFromContext(ctx) // 带追踪的上下文 ctx = ixLog.ContextWithTrace(ctx, "trace123", "span456", "") ``` ### 中间件集成 ```go // 日志中间件 middleware := ixLog.LoggingMiddleware(logger) // 追踪中间件 tracingMiddleware := ixLog.NewTracingMiddleware("http_request") // 组合使用 handler := middleware(tracingMiddleware.Handle(context.Background(), yourHandler)) ``` ## 📊 性能基准 基于测试结果的性能数据: | 操作类型 | 吞吐量 | 延迟 | 内存分配 | |---------|--------|------|----------| | 基础日志 | ~500K ops/sec | ~2μs | 0 allocs | | 带字段日志 | ~300K ops/sec | ~3μs | 1 alloc | | 异步日志 | ~800K ops/sec | ~1μs | 0 allocs | | 追踪日志 | ~200K ops/sec | ~5μs | 2 allocs | ## 🔍 故障排除 ### 常见问题 1. **日志不输出** ```go // 检查日志级别 if !logger.IsLevelEnabled(ixLog.DEBUG) { // DEBUG级别被过滤了 } // 检查输出配置 logger, err := ixLog.NewLogger( ixLog.WithConsoleOutput(true), // 确保有输出目标 ) ``` 2. **性能问题** ```go // 优化配置 logger, err := ixLog.NewLogger( ixLog.WithCaller(false), // 关闭调用者信息 ixLog.WithTrace(false, 0, 0), // 关闭追踪 ixLog.WithAsync(true), // 启用异步 ixLog.WithBufferSize(8192), // 增大缓冲区 ) ``` 3. **内存占用高** ```go // 减少内存使用 logger, err := ixLog.NewLogger( ixLog.WithBufferSize(1024), // 减小缓冲区 ixLog.WithFlushInterval(50*time.Millisecond), // 更频繁刷新 ixLog.WithStackDepth(0), // 关闭调用栈 ) ``` ### 调试模式 ```go // 启用详细调试 logger, err := ixLog.NewLogger( ixLog.WithLevel(ixLog.TRACE), ixLog.WithCaller(true), ixLog.WithTrace(true, 10, 1.0), // 完整调用栈,100%采样 ixLog.WithFormat(ixLog.JSONFormat), ) // 查看内部状态 if statsProvider, ok := logger.(interface{ GetStats() *ixLog.Stats }); ok { stats := statsProvider.GetStats() fmt.Printf("缓冲区使用: %d/%d\n", stats.BufferUsage, stats.BufferSize) } ``` ## 📚 API 参考 ### 核心接口 ```go type Logger interface { // 基础日志方法 Trace(args ...interface{}) Debug(args ...interface{}) Info(args ...interface{}) Warn(args ...interface{}) Error(args ...interface{}) Fatal(args ...interface{}) // 格式化日志方法 Tracef(format string, args ...interface{}) 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{}) // 装饰器方法(支持链式调用) WithField(key string, value interface{}) Logger WithFields(fields map[string]interface{}) Logger WithError(err error) Logger WithContext(ctx context.Context) Logger WithTrace(traceID, spanID, parentSpanID string) Logger // 控制方法 SetLevel(level LogLevel) GetLevel() LogLevel IsLevelEnabled(level LogLevel) bool Flush() error Close() error // 钩子管理 AddHook(hook Hook) RemoveHook(hook Hook) } ``` ### 配置选项 ```go // 基础配置 WithLevel(LogLevel) // 设置日志级别 WithFormat(OutputFormat) // 设置输出格式 WithColor(bool) // 启用/禁用颜色 WithCaller(bool) // 启用/禁用调用者信息 WithCallerSkip(int) // 调用者跳过层数 WithTimeFormat(string) // 时间格式 WithTimezone(string) // 时区 // 输出配置 WithConsoleOutput(bool) // 控制台输出 WithFileOutput(string, ...FileOption) // 文件输出 WithNetworkOutput(string, string) // 网络输出 // 异步配置 WithAsync(bool) // 异步写入 WithBufferSize(int) // 缓冲区大小 WithFlushInterval(time.Duration) // 刷新间隔 // 追踪配置 WithTrace(bool, int, float64) // 启用追踪,栈深度,采样率 WithStackDepth(int) // 调用栈深度 // 应用配置 WithAppInfo(string, string) // 应用名,环境 WithHostname(string) // 主机名 WithGlobalFields(map[string]interface{}) // 全局字段 // 安全配置 WithSanitize(bool, []string, []string) // 启用脱敏,字段,模式 WithCustomSanitizer(*Sanitizer) // 自定义脱敏器 // 钩子配置 WithHooks(bool) // 启用钩子 ``` ### 全局函数 ```go // 全局日志器管理 SetDefaultLogger(Logger) // 设置默认日志器 GetDefaultLogger() Logger // 获取默认日志器 // 环境预设 SetupDevelopment(string) // 开发环境 SetupProduction(string, string) error // 生产环境 NewDevelopmentLogger() (Logger, error) // 开发日志器 NewProductionLogger(string) (Logger, error) // 生产日志器 NewTestLogger() (Logger, error) // 测试日志器 // 配置加载 LoadConfigFromEnv() *Config // 从环境变量加载 LoadConfigFromFile(string) (*Config, error) // 从文件加载 // 全局日志方法 Info(args ...interface{}) // 全局Info日志 Warn(args ...interface{}) // 全局Warn日志 Error(args ...interface{}) // 全局Error日志 InfoWithFields(map[string]interface{}, string) // 带字段的全局日志 InfoWithContext(context.Context, string) // 带上下文的全局日志 // 追踪函数 StartTrace(context.Context, string) (context.Context, *Span) StartChildTrace(context.Context, string) (context.Context, *Span) FinishTrace(*Span) TraceFunction(context.Context, string, func(context.Context) error) error TraceSpan(context.Context, string, func(context.Context) error) error // 业务日志 LogUserAction(context.Context, string, string, map[string]interface{}) LogHTTPRequest(context.Context, string, string, int, time.Duration) LogDBQuery(context.Context, string, time.Duration, error) LogExternalCall(context.Context, string, string, time.Duration, error) LogPerformance(context.Context, string, time.Duration, map[string]interface{}) LogSecurityEvent(context.Context, string, string, map[string]interface{}) // 实用工具 GetCallerInfo(int) *CallerInfo // 获取调用者信息 GetCallStack(int, int) []string // 获取调用栈 Measure(context.Context, string, func()) // 性能测量 SafeGo(context.Context, string, func(context.Context)) // 安全goroutine ``` ## 🧪 测试 运行测试套件: ```bash # 运行所有测试 cd ixLog/tests && ./run_tests.sh # 运行特定测试 ./run_tests.sh basic # 运行性能测试 ./run_tests.sh -bench # 运行并发测试 ./run_tests.sh integration ``` 测试覆盖: - ✅ 基础日志功能测试 - ✅ 分布式追踪测试 - ✅ 写入器功能测试 - ✅ 钩子系统测试 - ✅ 脱敏功能测试 - ✅ 格式化器测试 - ✅ 集成测试 - ✅ 性能基准测试 - ✅ 并发安全测试 ## 📋 最佳实践 ### 1. 生产环境配置 ```go // 推荐的生产环境配置 logger, err := ixLog.NewLogger( ixLog.WithLevel(ixLog.INFO), // INFO级别以上 ixLog.WithFormat(ixLog.JSONFormat), // JSON格式便于解析 ixLog.WithColor(false), // 关闭颜色 ixLog.WithCaller(false), // 关闭调用者信息提高性能 ixLog.WithFileOutput("/var/log/app.log", ixLog.WithRotation(ixLog.SizeRotation), ixLog.WithMaxSize(100), ixLog.WithCompress(true), ), ixLog.WithAsync(true), // 异步写入 ixLog.WithBufferSize(8192), // 大缓冲区 ixLog.WithTrace(true, 0, 0.1), // 10%采样 ixLog.WithSanitize(true, nil, nil), // 启用脱敏 ) ``` ### 2. 高性能配置 ```go // 极致性能配置 logger, err := ixLog.NewLogger( ixLog.WithLevel(ixLog.WARN), // 只记录警告以上 ixLog.WithCaller(false), // 关闭调用者信息 ixLog.WithTrace(false, 0, 0), // 关闭追踪 ixLog.WithAsync(true), // 异步写入 ixLog.WithBufferSize(16384), // 大缓冲区 ixLog.WithFlushInterval(1*time.Second), // 延长刷新间隔 ixLog.WithHooks(false), // 关闭钩子 ) ``` ### 3. 调试配置 ```go // 详细调试配置 logger, err := ixLog.NewLogger( ixLog.WithLevel(ixLog.TRACE), // 最详细级别 ixLog.WithFormat(ixLog.TextFormat), // 文本格式易读 ixLog.WithColor(true), // 彩色输出 ixLog.WithCaller(true), // 调用者信息 ixLog.WithTrace(true, 10, 1.0), // 完整追踪 ixLog.WithConsoleOutput(true), // 控制台输出 ) ``` ## 🚨 注意事项 1. **FATAL级别会自动退出程序**,请谨慎使用 2. **异步模式下需要调用 `Flush()` 或 `Close()`** 确保日志写入完成 3. **高并发场景建议启用异步写入**以避免阻塞 4. **生产环境建议关闭调用者信息**以提高性能 5. **脱敏功能会轻微影响性能**,根据需要启用 6. **追踪采样率建议根据流量调整**,避免性能影响 ## 📄 许可证 MIT License. 详见 [LICENSE](LICENSE) 文件。 ## 🤝 贡献 欢迎提交 Issue 和 Pull Request! ## 📞 支持 - 📧 邮箱: lixu@puchigames.com - 🐛 问题反馈: [Issues](https://gitee.com/ixgo/go-helper/issues) - 📖 文档: [Wiki](https://gitee.com/ixgo/go-helper/wikis) --- **ixLog** - 让日志记录变得简单而强大! 🚀