log

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Jan 8, 2026 License: Apache-2.0 Imports: 14 Imported by: 3

README

Log Package

一个功能强大的日志包,支持多种日志格式和输出方式。

特性

  • 支持多种日志格式(JSON、Console)
  • 支持多种输出方式(文件、控制台、网络)
  • 支持日志级别控制
  • 支持结构化日志
  • 支持日志轮转:按大小轮转、按时间轮转(天、小时、月等)
  • 支持多种日志库(Zap、Logrus、Klog)
  • 支持彩色日志输出:不同级别的日志显示不同颜色
  • 日志级别带方括号:更清晰的日志级别标识
  • 支持日志分级输出:不同级别日志输出到不同文件(Duplicate 模式推荐)
  • 支持类型化日志:HTTP、SQL、gRPC、Redis 等类型标记,便于分析
  • 支持链路追踪:自动追踪请求调用链

快速开始

基本使用
package main

import (
    "github.com/FangcunMount/iam-contracts/pkg/log"
)

func main() {
    // 初始化日志
    log.Init(&log.Options{
        Level:      "info",
        Format:     "console",
        OutputPaths: []string{"stdout"},
    })
    defer log.Flush()

    // 使用日志
    log.Info("Hello, World!")
    log.Error("Something went wrong")
}
配置选项
log.Init(&log.Options{
    Level:      "debug",           // 日志级别
    Format:     "console",         // 日志格式 (console/json)
    EnableColor: true,             // 启用彩色输出(仅 console 格式)
    OutputPaths: []string{         // 输出路径
        "stdout",
        "/var/log/app.log",
    },
    ErrorOutputPaths: []string{    // 错误输出路径
        "stderr",
        "/var/log/app-error.log",
    },
    MaxSize:    100,               // 单个日志文件最大大小(MB)
    MaxAge:     30,                // 保留旧日志文件的最大天数
    MaxBackups: 10,                // 保留旧日志文件的最大数量
    Compress:   true,              // 是否压缩旧日志文件
})
彩色日志输出

启用彩色输出可以让不同级别的日志更加醒目:

log.Init(&log.Options{
    Level:       "debug",
    Format:      "console",
    EnableColor: true,  // 启用彩色输出
    OutputPaths: []string{"stdout"},
})

// 不同级别的日志将显示不同的颜色
log.Debug("This is a debug message")   // 青色 [DEBUG]
log.Info("This is an info message")    // 绿色 [INFO]
log.Warn("This is a warning message")  // 黄色 [WARN]
log.Error("This is an error message")  // 红色 [ERROR]

注意

  • 彩色输出仅在 console 格式下生效
  • 输出到文件时建议关闭彩色输出(EnableColor: false
  • 所有日志级别都会带有方括号 [LEVEL],无论是否启用颜色

颜色方案

  • [DEBUG] - 青色(Cyan)
  • [INFO] - 绿色(Green)
  • [WARN] - 黄色(Yellow)
  • [ERROR] - 红色(Red)
  • [FATAL] - 红色(Red)
  • [PANIC] - 红色(Red)

日志级别

  • debug: 调试信息
  • info: 一般信息
  • warn: 警告信息
  • error: 错误信息
  • fatal: 致命错误(会调用os.Exit(1))
  • panic: 恐慌错误(会调用panic)

结构化日志

log.Info("User login",
    "user_id", 123,
    "ip", "192.168.1.1",
    "user_agent", "Mozilla/5.0...",
)

日志轮转

当日志文件达到指定大小时,会自动进行轮转:

log.Init(&log.Options{
    OutputPaths: []string{"/var/log/app.log"},
    MaxSize:    100,    // 100MB
    MaxAge:     30,     // 30天
    MaxBackups: 10,     // 保留10个旧文件
    Compress:   true,   // 压缩旧文件
})
按时间轮转

支持按时间自动轮转日志文件,可以按天、按小时、按月等方式分割日志。

按天轮转
opts := log.NewOptions()
opts.EnableTimeRotation = true
opts.TimeRotationFormat = "2006-01-02"  // 按天轮转
opts.MaxAge = 7                          // 保留7天
opts.OutputPaths = []string{"/var/log/app.log"}
log.Init(opts)
// 生成的文件名:app.2025-11-01.log, app.2025-11-02.log, ...
按小时轮转
opts := log.NewOptions()
opts.EnableTimeRotation = true
opts.TimeRotationFormat = "2006-01-02-15"  // 按小时轮转
opts.MaxAge = 24                            // 保留24小时
opts.OutputPaths = []string{"/var/log/app.log"}
log.Init(opts)
// 生成的文件名:app.2025-11-01-10.log, app.2025-11-01-11.log, ...

其他支持的时间格式

  • 2006-01-02: 按天轮转
  • 2006-01-02-15: 按小时轮转
  • 2006-01: 按月轮转
  • 2006-W01: 按周轮转(需要自定义)

优势

  • 日志文件按时间自然分割,便于查找和分析
  • 适合长时间运行的服务
  • 可以根据业务需求设置不同的轮转粒度
  • 自动清理过期日志,节省磁盘空间

示例

# 运行按天轮转示例
go run pkg/log/example/dailyrotation/main.go

# 运行按小时轮转示例
go run pkg/log/example/hourlyrotation/main.go

日志分级输出

支持将不同级别的日志输出到不同的文件,便于日志分析和问题排查。

基本用法
opts := log.NewOptions()
opts.EnableLevelOutput = true
opts.LevelOutputMode = "duplicate" // 推荐使用 duplicate 模式

// 配置输出路径
opts.LevelOutputPaths = map[string][]string{
    "all":   []string{"/var/log/app.log"},   // 记录所有日志
    "error": []string{"/var/log/error.log"}, // 额外记录错误
}

log.Init(opts)
输出模式
1. Duplicate 模式(推荐,默认)

支持重复输出,适合生产环境:

opts.LevelOutputMode = "duplicate"
opts.LevelOutputPaths = map[string][]string{
    "all":   []string{"/var/log/app.log"},   // 记录所有级别日志
    "error": []string{"/var/log/error.log"}, // 额外记录 ERROR
    "warn":  []string{"/var/log/warn.log"},  // 额外记录 WARN(可选)
}

输出结果

  • app.log: 包含 DEBUG, INFO, WARN, ERROR(完整日志)
  • error.log: 只包含 ERROR(便于快速定位故障)
  • warn.log: 只包含 WARN(便于发现潜在问题)

适用场景

  • 生产环境推荐:完整日志 + 错误日志分离
  • ✅ 需要快速定位错误,同时保留完整上下文
  • ✅ 配合监控系统,对 error.log 设置告警
2. Above 模式

输出该级别及以上的日志:

opts.LevelOutputMode = "above"
opts.LevelOutputPaths = map[string][]string{
    "info":  []string{"/var/log/info.log"},  // 包含: INFO, WARN, ERROR
    "error": []string{"/var/log/error.log"}, // 包含: ERROR
}

输出结果

  • info.log: INFO + WARN + ERROR
  • error.log: 仅 ERROR

适用场景

  • 需要在一个文件中查看所有重要日志
  • 错误日志单独存储

⚠️ 注意:此模式下日志会重复(info.log 和 error.log 都包含 ERROR)

3. Exact 模式

只输出精确匹配的日志级别:

opts.LevelOutputMode = "exact"
opts.LevelOutputPaths = map[string][]string{
    "debug": []string{"/var/log/debug.log"},  // 仅 DEBUG
    "info":  []string{"/var/log/info.log"},   // 仅 INFO
    "warn":  []string{"/var/log/warn.log"},   // 仅 WARN
    "error": []string{"/var/log/error.log"},  // 仅 ERROR
}

输出结果

  • 每个文件只包含对应级别的日志
  • 没有重复,严格分离

适用场景

  • 需要精确统计各级别日志数量
  • 不同级别日志需要不同的处理策略
生产环境推荐配置
opts := log.NewOptions()
opts.Level = "info"                  // INFO 及以上
opts.Format = "json"                 // JSON 格式便于分析
opts.EnableLevelOutput = true
opts.LevelOutputMode = "duplicate"   // 使用 duplicate 模式
opts.EnableTimeRotation = true       // 启用按天轮转
opts.TimeRotationFormat = "2006-01-02"
opts.MaxAge = 30                     // 保留 30 天
opts.Compress = true                 // 压缩旧日志

opts.LevelOutputPaths = map[string][]string{
    "all":   []string{"/var/log/app.log"},   // 完整日志
    "error": []string{"/var/log/error.log"}, // 错误日志(设置告警)
}

log.Init(opts)

优势

  • app.log 包含完整日志,便于问题追溯
  • error.log 只含错误,便于快速定位
  • ✅ 按天轮转,自动管理磁盘空间
  • ✅ JSON 格式,便于 ELK/日志分析工具处理
示例

查看各种模式的完整示例:

# Duplicate 模式(推荐)
go run pkg/log/example/duplicatemode/main.go

# 生产环境配置
go run pkg/log/example/production/main.go

# Above 模式
go run pkg/log/example/leveloutput/main.go

# Exact 模式
go run pkg/log/example/exactlevel/main.go

运行 exact 模式示例

go run pkg/log/example/exactlevel/main.go


## 多种日志库支持

### Zap

```go
import "github.com/FangcunMount/iam-contracts/pkg/log"

log.Init(&log.Options{
    Level:      "info",
    Format:     "json",
    OutputPaths: []string{"stdout"},
})
Logrus
import "github.com/FangcunMount/iam-contracts/pkg/log/logrus"

logger := logrus.New()
logger.SetFormatter(&logrus.JSONFormatter{})
logger.Info("Hello, World!")
Klog
import "github.com/FangcunMount/iam-contracts/pkg/log/klog"

klog.InitFlags(nil)
klog.Info("Hello, World!")
klog.Flush()

开发工具

开发环境日志
log.Init(&log.Options{
    Level:      "debug",
    Format:     "console",
    OutputPaths: []string{"stdout"},
    Development: true,  // 开发模式
})
测试环境日志
log.Init(&log.Options{
    Level:      "info",
    Format:     "json",
    OutputPaths: []string{"/var/log/test.log"},
    Development: false,
})

链路追踪集成

基本使用
import (
    "context"
    "github.com/FangcunMount/component-base/pkg/log"
    "github.com/FangcunMount/component-base/pkg/util/idutil"
)

func main() {
    log.Init(log.NewOptions())
    defer log.Flush()

    // 创建追踪上下文
    ctx := context.Background()
    traceID := idutil.NewTraceID()    // 生成 32 字符 Trace ID
    spanID := idutil.NewSpanID()      // 生成 16 字符 Span ID
    requestID := idutil.NewRequestID() // 生成请求 ID
    
    ctx = log.WithTraceContext(ctx, traceID, spanID, requestID)
    
    // 使用带追踪信息的日志
    log.InfoContext(ctx, "处理订单", log.String("order_id", "ORD-123"))
    log.DebugContext(ctx, "验证库存")
    log.ErrorContext(ctx, "库存不足")
}
HTTP 中间件集成
import (
    "net/http"
    "github.com/FangcunMount/component-base/pkg/log"
    "github.com/FangcunMount/component-base/pkg/log/middleware"
)

func main() {
    log.Init(log.NewOptions())
    defer log.Flush()
    
    // 创建 HTTP 处理器
    handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        ctx := r.Context()
        
        // 日志会自动包含 trace_id, span_id, request_id
        log.InfoContext(ctx, "处理请求", 
            log.String("path", r.URL.Path),
            log.String("method", r.Method),
        )
        
        w.WriteHeader(http.StatusOK)
    })
    
    // 使用追踪中间件
    tracedHandler := middleware.TracingMiddleware(handler)
    
    http.ListenAndServe(":8080", tracedHandler)
}
微服务调用链追踪
// 服务 A 调用服务 B
func callServiceB(ctx context.Context) {
    // 创建子 span
    spanID := idutil.NewSpanID()
    childCtx := log.WithSpanID(ctx, spanID)
    
    log.InfoContext(childCtx, "调用服务 B", log.String("service", "service-b"))
    
    // 调用服务 B...
    // 将 trace_id 和 span_id 通过 HTTP Header 传递
}
追踪上下文 API
// 注入完整追踪信息
ctx = log.WithTraceContext(ctx, traceID, spanID, requestID)

// 只更新 Span ID(创建子 span)
ctx = log.WithSpanID(ctx, newSpanID)

// 获取追踪信息
traceID := log.TraceID(ctx)
spanID := log.SpanID(ctx)
requestID := log.RequestID(ctx)

// 带追踪信息的日志方法
log.InfoContext(ctx, "message", fields...)
log.DebugContext(ctx, "message", fields...)
log.WarnContext(ctx, "message", fields...)
log.ErrorContext(ctx, "message", fields...)
ID 生成工具
import "github.com/FangcunMount/component-base/pkg/util/idutil"

// 生成 Trace ID(32 字符十六进制,符合 OpenTelemetry 规范)
traceID := idutil.NewTraceID()  // 例如:51c89d3c4c18d317915cae78f4221908

// 生成 Span ID(16 字符十六进制)
spanID := idutil.NewSpanID()    // 例如:2cc53d25e033223e

// 生成 Request ID(带时间戳)
requestID := idutil.NewRequestID()  // 例如:req-1761965855567-63dg7rsf
HTTP 中间件特性

追踪中间件自动处理:

  1. 提取追踪信息:从 HTTP 请求头提取现有的 trace_id
  2. 生成追踪 ID:如果请求没有 trace_id,自动生成新的
  3. 注入到上下文:将追踪信息注入 context.Context
  4. 响应头返回:在响应中添加 X-Trace-Id 和 X-Request-Id 头
  5. 自动记录:记录请求开始和结束,包含耗时

支持的 HTTP Header:

  • X-Trace-Id:分布式追踪 ID
  • X-Span-Id:当前 span ID
  • X-Request-Id:请求 ID
OpenTelemetry 集成(可选)

如果需要与 OpenTelemetry 集成,可以参考 pkg/log/otel/otel.go 中的示例代码。

示例程序

查看完整示例:

  • pkg/log/example/tracing/main.go - 基础追踪示例
  • pkg/log/example/microservices/main.go - 微服务调用链示例

运行示例:

# 基础追踪示例
go run pkg/log/example/tracing/main.go

# 微服务示例
go run pkg/log/example/microservices/main.go

类型化日志

支持为不同类型的操作添加自动类型标记,便于日志分类和分析。

支持的类型
  • HTTP - HTTP/REST API 请求日志
  • SQL - 数据库查询日志
  • GRPC - gRPC 服务调用日志
  • Redis - Redis 缓存操作日志
  • MQ - 消息队列操作日志
  • Cache - 通用缓存操作日志
  • RPC - 通用 RPC 调用日志
基本使用
// HTTP 请求日志(自动添加 type=HTTP)
log.HTTP("GET /api/users",
    log.String("method", "GET"),
    log.String("path", "/api/users"),
    log.Int("status", 200),
    log.Float64("duration_ms", 45.6),
)

// SQL 查询日志(自动添加 type=SQL)
log.SQL("查询用户信息",
    log.String("query", "SELECT * FROM users WHERE id = ?"),
    log.Int("rows", 1),
    log.Float64("duration_ms", 12.3),
)

// gRPC 调用日志(自动添加 type=GRPC)
log.GRPC("UserService.GetUser",
    log.String("service", "UserService"),
    log.String("method", "GetUser"),
    log.String("code", "OK"),
)

// Redis 操作日志(自动添加 type=Redis)
log.Redis("GET user:10086",
    log.String("command", "GET"),
    log.String("key", "user:10086"),
    log.Bool("hit", true),
)
不同级别

每种类型都提供 4 个级别:

log.HTTP()       // INFO 级别
log.HTTPDebug()  // DEBUG 级别
log.HTTPWarn()   // WARN 级别
log.HTTPError()  // ERROR 级别
实际应用
func HandleOrder(w http.ResponseWriter, r *http.Request) {
    // 记录 HTTP 请求
    log.HTTP("接收订单请求",
        log.String("method", r.Method),
        log.String("path", r.URL.Path),
    )
    
    // 查询数据库
    log.SQL("查询用户信息",
        log.String("query", "SELECT * FROM users WHERE id = ?"),
        log.Float64("duration_ms", 5.2),
    )
    
    // 检查缓存
    log.Redis("检查库存缓存",
        log.String("key", "inventory:PROD-12345"),
        log.Bool("hit", true),
    )
    
    // 调用服务
    log.GRPC("调用支付服务",
        log.String("service", "PaymentService"),
        log.String("method", "Charge"),
    )
    
    // 发送消息
    log.MQ("发送订单事件",
        log.String("topic", "order-created"),
    )
}
日志分析

类型化日志便于过滤和分析:

# 只查看 HTTP 日志
cat app.log | grep '"type":"HTTP"'

# 只查看 SQL 日志
cat app.log | grep '"type":"SQL"'

# 统计各类型日志数量
cat app.log | jq -r '.type' | sort | uniq -c

# 计算 HTTP 平均响应时间
cat app.log | grep '"type":"HTTP"' | jq '.duration_ms' | awk '{sum+=$1; count++} END {print sum/count}'
详细文档

查看完整的类型化日志文档:TYPED_LOGS.md

运行示例:

go run pkg/log/example/typed-logs/main.go

最佳实践

  1. 选择合适的日志级别:不要在生产环境使用debug级别
  2. 使用结构化日志:便于日志分析和搜索
  3. 配置日志轮转:避免日志文件过大
  4. 分离错误日志:将错误日志输出到单独的文件(使用 Duplicate 模式)
  5. 使用有意义的日志消息:便于问题排查
  6. 使用链路追踪:在微服务架构中使用追踪 ID 关联日志
  7. 传递追踪上下文:跨服务调用时通过 HTTP Header 传递追踪信息
  8. 创建子 Span:在关键操作时创建新的 Span ID,便于定位问题
  9. 使用类型化日志:为不同操作使用对应的日志类型(HTTP、SQL、gRPC 等)
  10. 记录关键字段:duration、status、error 等便于监控和分析

许可证

MIT License

Documentation

Overview

Package log is a log package used by TKE team.

Index

Constants

View Source
const (
	KeyRequestID   string = "requestID"
	KeyUsername    string = "username"
	KeyWatcherName string = "watcher"
)

Defines common log fields.

Variables

View Source
var (
	// DebugLevel logs are typically voluminous, and are usually disabled in
	// production.
	DebugLevel = zapcore.DebugLevel
	// InfoLevel is the default logging priority.
	InfoLevel = zapcore.InfoLevel
	// WarnLevel logs are more important than Info, but don't need individual
	// human review.
	WarnLevel = zapcore.WarnLevel
	// ErrorLevel logs are high-priority. If an application is running smoothly,
	// it shouldn't generate any error-level logs.
	ErrorLevel = zapcore.ErrorLevel
	// PanicLevel logs a message, then panics.
	PanicLevel = zapcore.PanicLevel
	// FatalLevel logs a message, then calls os.Exit(1).
	FatalLevel = zapcore.FatalLevel
)
View Source
var (
	Any         = zap.Any
	Array       = zap.Array
	Object      = zap.Object
	Binary      = zap.Binary
	Bool        = zap.Bool
	Bools       = zap.Bools
	ByteString  = zap.ByteString
	ByteStrings = zap.ByteStrings
	Complex64   = zap.Complex64
	Complex64s  = zap.Complex64s
	Complex128  = zap.Complex128
	Complex128s = zap.Complex128s
	Duration    = zap.Duration
	Durations   = zap.Durations
	Err         = zap.Error
	Errors      = zap.Errors
	Float32     = zap.Float32
	Float32s    = zap.Float32s
	Float64     = zap.Float64
	Float64s    = zap.Float64s
	Int         = zap.Int
	Ints        = zap.Ints
	Int8        = zap.Int8
	Int8s       = zap.Int8s
	Int16       = zap.Int16
	Int16s      = zap.Int16s
	Int32       = zap.Int32
	Int32s      = zap.Int32s
	Int64       = zap.Int64
	Int64s      = zap.Int64s
	Namespace   = zap.Namespace
	Reflect     = zap.Reflect
	Stack       = zap.Stack
	String      = zap.String
	Stringer    = zap.Stringer
	Strings     = zap.Strings
	Time        = zap.Time
	Times       = zap.Times
	Uint        = zap.Uint
	Uints       = zap.Uints
	Uint8       = zap.Uint8
	Uint8s      = zap.Uint8s
	Uint16      = zap.Uint16
	Uint16s     = zap.Uint16s
	Uint32      = zap.Uint32
	Uint32s     = zap.Uint32s
	Uint64      = zap.Uint64
	Uint64s     = zap.Uint64s
	Uintptr     = zap.Uintptr
	Uintptrs    = zap.Uintptrs
)

Alias for zap type functions.

Functions

func Cache added in v0.3.0

func Cache(msg string, fields ...Field)

Cache 记录缓存操作日志 自动添加 type=Cache 字段

func CacheDebug added in v0.3.0

func CacheDebug(msg string, fields ...Field)

CacheDebug 记录缓存操作的调试日志

func CacheError added in v0.3.0

func CacheError(msg string, fields ...Field)

CacheError 记录缓存操作的错误日志

func CacheWarn added in v0.3.0

func CacheWarn(msg string, fields ...Field)

CacheWarn 记录缓存操作的警告日志

func CheckIntLevel

func CheckIntLevel(level int32) bool

CheckIntLevel used for other log wrapper such as klog which return if logging a message at the specified level is enabled.

func Debug

func Debug(msg string, fields ...Field)

Debug method output debug level log.

func DebugContext added in v0.2.7

func DebugContext(ctx context.Context, msg string, fields ...Field)

DebugContext 记录带追踪信息的 debug 日志

func Debugf

func Debugf(format string, v ...interface{})

Debugf method output debug level log.

func DebugfContext added in v0.2.7

func DebugfContext(ctx context.Context, format string, v ...interface{})

DebugfContext 记录带追踪信息的格式化 debug 日志

func Debugw

func Debugw(msg string, keysAndValues ...interface{})

Debugw method output debug level log.

func Error

func Error(msg string, fields ...Field)

Error method output error level log.

func ErrorContext added in v0.2.7

func ErrorContext(ctx context.Context, msg string, fields ...Field)

ErrorContext 记录带追踪信息的 error 日志

func Errorf

func Errorf(format string, v ...interface{})

Errorf method output error level log.

func ErrorfContext added in v0.2.7

func ErrorfContext(ctx context.Context, format string, v ...interface{})

ErrorfContext 记录带追踪信息的格式化 error 日志

func Errorw

func Errorw(msg string, keysAndValues ...interface{})

Errorw method output error level log.

func ExtractRequestID added in v0.2.7

func ExtractRequestID(ctx context.Context) string

ExtractRequestID 从 context 中提取 request ID

func ExtractSpanID added in v0.2.7

func ExtractSpanID(ctx context.Context) string

ExtractSpanID 从 context 中提取 span ID

func ExtractTraceID added in v0.2.7

func ExtractTraceID(ctx context.Context) string

ExtractTraceID 从 context 中提取 trace ID 支持 OpenTelemetry 和自定义 trace ID

func Fatal

func Fatal(msg string, fields ...Field)

Fatal method output fatal level log.

func Fatalf

func Fatalf(format string, v ...interface{})

Fatalf method output fatal level log.

func Fatalw

func Fatalw(msg string, keysAndValues ...interface{})

Fatalw method output Fatalw level log.

func Flush

func Flush()

Flush calls the underlying Core's Sync method, flushing any buffered log entries. Applications should take care to call Sync before exiting.

func GRPC added in v0.3.0

func GRPC(msg string, fields ...Field)

GRPC 记录 gRPC 调用日志 自动添加 type=GRPC 字段

func GRPCDebug added in v0.3.0

func GRPCDebug(msg string, fields ...Field)

GRPCDebug 记录 gRPC 调用的调试日志

func GRPCError added in v0.3.0

func GRPCError(msg string, fields ...Field)

GRPCError 记录 gRPC 调用的错误日志

func GRPCWarn added in v0.3.0

func GRPCWarn(msg string, fields ...Field)

GRPCWarn 记录 gRPC 调用的警告日志

func HTTP added in v0.3.0

func HTTP(msg string, fields ...Field)

HTTP 记录 HTTP 请求日志 自动添加 type=HTTP 字段

func HTTPDebug added in v0.3.0

func HTTPDebug(msg string, fields ...Field)

HTTPDebug 记录 HTTP 请求的调试日志

func HTTPError added in v0.3.0

func HTTPError(msg string, fields ...Field)

HTTPError 记录 HTTP 请求的错误日志

func HTTPWarn added in v0.3.0

func HTTPWarn(msg string, fields ...Field)

HTTPWarn 记录 HTTP 请求的警告日志

func Info

func Info(msg string, fields ...Field)

Info method output info level log.

func InfoContext added in v0.2.7

func InfoContext(ctx context.Context, msg string, fields ...Field)

InfoContext 记录带追踪信息的 info 日志

func Infof

func Infof(format string, v ...interface{})

Infof method output info level log.

func InfofContext added in v0.2.7

func InfofContext(ctx context.Context, format string, v ...interface{})

InfofContext 记录带追踪信息的格式化 info 日志

func Infow

func Infow(msg string, keysAndValues ...interface{})

Infow method output info level log.

func Init

func Init(opts *Options)

Init initializes logger with specified options.

func L

func L(ctx context.Context) *zapLogger

L method output with specified context value.

func MQ added in v0.3.0

func MQ(msg string, fields ...Field)

MQ 记录消息队列操作日志 自动添加 type=MQ 字段

func MQDebug added in v0.3.0

func MQDebug(msg string, fields ...Field)

MQDebug 记录消息队列操作的调试日志

func MQError added in v0.3.0

func MQError(msg string, fields ...Field)

MQError 记录消息队列操作的错误日志

func MQWarn added in v0.3.0

func MQWarn(msg string, fields ...Field)

MQWarn 记录消息队列操作的警告日志

func Mongo added in v0.4.0

func Mongo(msg string, fields ...Field)

Mongo 记录 MongoDB 操作日志 自动添加 type=MongoDB 字段

func MongoDebug added in v0.4.0

func MongoDebug(msg string, fields ...Field)

MongoDebug 记录 MongoDB 操作的调试日志

func MongoError added in v0.4.0

func MongoError(msg string, fields ...Field)

MongoError 记录 MongoDB 操作的错误日志

func MongoWarn added in v0.4.0

func MongoWarn(msg string, fields ...Field)

MongoWarn 记录 MongoDB 操作的警告日志

func New

func New(opts *Options) *zapLogger

New create logger by opts which can custmoized by command arguments.

func NewWithRotation

func NewWithRotation(opts *Options) *zap.Logger

NewWithRotation 创建支持日志轮转的 logger

func Panic

func Panic(msg string, fields ...Field)

Panic method output panic level log and shutdown application.

func Panicf

func Panicf(format string, v ...interface{})

Panicf method output panic level log and shutdown application.

func Panicw

func Panicw(msg string, keysAndValues ...interface{})

Panicw method output panic level log.

func RPC added in v0.3.0

func RPC(msg string, fields ...Field)

RPC 记录 RPC 调用日志(通用) 自动添加 type=RPC 字段

func RPCDebug added in v0.3.0

func RPCDebug(msg string, fields ...Field)

RPCDebug 记录 RPC 调用的调试日志

func RPCError added in v0.3.0

func RPCError(msg string, fields ...Field)

RPCError 记录 RPC 调用的错误日志

func RPCWarn added in v0.3.0

func RPCWarn(msg string, fields ...Field)

RPCWarn 记录 RPC 调用的警告日志

func Redis added in v0.3.0

func Redis(msg string, fields ...Field)

Redis 记录 Redis 操作日志 自动添加 type=Redis 字段

func RedisDebug added in v0.3.0

func RedisDebug(msg string, fields ...Field)

RedisDebug 记录 Redis 操作的调试日志

func RedisError added in v0.3.0

func RedisError(msg string, fields ...Field)

RedisError 记录 Redis 操作的错误日志

func RedisWarn added in v0.3.0

func RedisWarn(msg string, fields ...Field)

RedisWarn 记录 Redis 操作的警告日志

func RequestID added in v0.2.7

func RequestID(ctx context.Context) zap.Field

RequestID 返回 request ID 字段

func SQL added in v0.3.0

func SQL(msg string, fields ...Field)

SQL 记录 SQL 查询日志 自动添加 type=SQL 字段

func SQLDebug added in v0.3.0

func SQLDebug(msg string, fields ...Field)

SQLDebug 记录 SQL 查询的调试日志

func SQLError added in v0.3.0

func SQLError(msg string, fields ...Field)

SQLError 记录 SQL 查询的错误日志

func SQLWarn added in v0.3.0

func SQLWarn(msg string, fields ...Field)

SQLWarn 记录 SQL 查询的警告日志

func SpanID added in v0.2.7

func SpanID(ctx context.Context) zap.Field

SpanID 返回 span ID 字段

func StdErrLogger

func StdErrLogger() *log.Logger

StdErrLogger returns logger of standard library which writes to supplied zap logger at error level.

func StdInfoLogger

func StdInfoLogger() *log.Logger

StdInfoLogger returns logger of standard library which writes to supplied zap logger at info level.

func SugaredLogger

func SugaredLogger() *zap.SugaredLogger

SugaredLogger returns global sugared logger.

func TraceFields added in v0.2.7

func TraceFields(ctx context.Context) []zap.Field

TraceFields 返回所有追踪相关字段

func TraceID added in v0.2.7

func TraceID(ctx context.Context) zap.Field

TraceField 返回 trace ID 字段

func Warn

func Warn(msg string, fields ...Field)

Warn method output warning level log.

func WarnContext added in v0.2.7

func WarnContext(ctx context.Context, msg string, fields ...Field)

WarnContext 记录带追踪信息的 warn 日志

func Warnf

func Warnf(format string, v ...interface{})

Warnf method output warning level log.

func WarnfContext added in v0.2.7

func WarnfContext(ctx context.Context, format string, v ...interface{})

WarnfContext 记录带追踪信息的格式化 warn 日志

func Warnw

func Warnw(msg string, keysAndValues ...interface{})

Warnw method output warning level log.

func WithContext

func WithContext(ctx context.Context) context.Context

WithContext returns a copy of context in which the log value is set.

func WithRequestID added in v0.2.7

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

WithRequestID 将 request ID 添加到 context

func WithSpanID added in v0.2.7

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

WithSpanID 将 span ID 添加到 context

func WithTraceContext added in v0.2.7

func WithTraceContext(ctx context.Context, traceID, spanID, requestID string) context.Context

WithTraceContext 将完整的追踪上下文添加到 context

func WithTraceID added in v0.2.7

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

WithTraceID 将 trace ID 添加到 context

func ZapLogger

func ZapLogger() *zap.Logger

ZapLogger used for other log wrapper such as klog.

Types

type Field

type Field = zapcore.Field

Field is an alias for the field structure in the underlying log frame.

type InfoLogger

type InfoLogger interface {
	// Info logs a non-error message with the given key/value pairs as context.
	//
	// The msg argument should be used to add some constant description to
	// the log line.  The key/value pairs can then be used to add additional
	// variable information.  The key/value pairs should alternate string
	// keys and arbitrary values.
	Info(msg string, fields ...Field)
	Infof(format string, v ...interface{})
	Infow(msg string, keysAndValues ...interface{})

	// Enabled tests whether this InfoLogger is enabled.  For example,
	// commandline flags might be used to set the logging verbosity and disable
	// some info logs.
	Enabled() bool
}

InfoLogger represents the ability to log non-error messages, at a particular verbosity.

func V

func V(level Level) InfoLogger

V return a leveled InfoLogger.

type Level

type Level = zapcore.Level

Level is an alias for the level structure in the underlying log frame.

type Logger

type Logger interface {
	// All Loggers implement InfoLogger.  Calling InfoLogger methods directly on
	// a Logger value is equivalent to calling them on a V(0) InfoLogger.  For
	// example, logger.Info() produces the same result as logger.V(0).Info.
	InfoLogger
	Debug(msg string, fields ...Field)
	Debugf(format string, v ...interface{})
	Debugw(msg string, keysAndValues ...interface{})
	Warn(msg string, fields ...Field)
	Warnf(format string, v ...interface{})
	Warnw(msg string, keysAndValues ...interface{})
	Error(msg string, fields ...Field)
	Errorf(format string, v ...interface{})
	Errorw(msg string, keysAndValues ...interface{})
	Panic(msg string, fields ...Field)
	Panicf(format string, v ...interface{})
	Panicw(msg string, keysAndValues ...interface{})
	Fatal(msg string, fields ...Field)
	Fatalf(format string, v ...interface{})
	Fatalw(msg string, keysAndValues ...interface{})

	// V returns an InfoLogger value for a specific verbosity level.  A higher
	// verbosity level means a log message is less important.  It's illegal to
	// pass a log level less than zero.
	V(level Level) InfoLogger
	Write(p []byte) (n int, err error)

	// WithValues adds some key-value pairs of context to a logger.
	// See Info for documentation on how key/value pairs work.
	WithValues(keysAndValues ...interface{}) Logger

	// WithName adds a new element to the logger's name.
	// Successive calls with WithName continue to append
	// suffixes to the logger's name.  It's strongly recommended
	// that name segments contain only letters, digits, and hyphens
	// (see the package documentation for more information).
	WithName(name string) Logger

	// WithContext returns a copy of context in which the log value is set.
	WithContext(ctx context.Context) context.Context

	// Flush calls the underlying Core's Sync method, flushing any buffered
	// log entries. Applications should take care to call Sync before exiting.
	Flush()
}

Logger represents the ability to log messages, both errors and not.

func FromContext

func FromContext(ctx context.Context) Logger

FromContext returns the value of the log key on the ctx.

func NewLogger

func NewLogger(l *zap.Logger) Logger

NewLogger creates a new logr.Logger using the given Zap Logger to log.

func WithName

func WithName(s string) Logger

WithName adds a new path segment to the logger's name. Segments are joined by periods. By default, Loggers are unnamed.

func WithValues

func WithValues(keysAndValues ...interface{}) Logger

WithValues creates a child logger and adds adds Zap fields to it.

type Options

type Options struct {
	OutputPaths       []string `json:"output-paths"       mapstructure:"output-paths"`
	ErrorOutputPaths  []string `json:"error-output-paths" mapstructure:"error-output-paths"`
	Level             string   `json:"level"              mapstructure:"level"`
	Format            string   `json:"format"             mapstructure:"format"`
	DisableCaller     bool     `json:"disable-caller"     mapstructure:"disable-caller"`
	DisableStacktrace bool     `json:"disable-stacktrace" mapstructure:"disable-stacktrace"`
	EnableColor       bool     `json:"enable-color"       mapstructure:"enable-color"`
	Development       bool     `json:"development"        mapstructure:"development"`
	Name              string   `json:"name"               mapstructure:"name"`

	// 日志轮转配置
	MaxSize    int  `json:"max-size"    mapstructure:"max-size"`    // 单个日志文件最大大小(MB)
	MaxAge     int  `json:"max-age"     mapstructure:"max-age"`     // 保留旧日志文件的最大天数
	MaxBackups int  `json:"max-backups" mapstructure:"max-backups"` // 保留旧日志文件的最大个数
	Compress   bool `json:"compress"    mapstructure:"compress"`    // 是否压缩旧日志文件

	// 按时间轮转配置
	EnableTimeRotation bool   `json:"enable-time-rotation" mapstructure:"enable-time-rotation"` // 是否启用按时间轮转
	TimeRotationFormat string `json:"time-rotation-format" mapstructure:"time-rotation-format"` // 时间轮转格式,如 "2006-01-02" 表示按天

	// 日志分级输出配置
	// 为不同日志级别配置独立的输出路径
	// 例如: {"all": []string{"/var/log/app.log"}, "error": []string{"/var/log/error.log"}}
	LevelOutputPaths map[string][]string `json:"level-output-paths" mapstructure:"level-output-paths"`
	// 是否启用分级输出(如果为 true,则使用 LevelOutputPaths;否则使用 OutputPaths)
	EnableLevelOutput bool `json:"enable-level-output" mapstructure:"enable-level-output"`
	// 分级输出模式:
	// "exact"     - 只输出精确匹配的日志级别(例如:info 文件只记录 INFO 级别)
	// "above"     - 输出该级别及以上的日志(例如:info 文件记录 INFO、WARN、ERROR)
	// "duplicate" - 支持重复输出,"all" 记录所有日志,其他级别额外记录(推荐)
	//               例如:{"all": ["app.log"], "error": ["error.log"]}
	//               app.log 记录所有日志,error.log 只额外记录 error
	LevelOutputMode string `json:"level-output-mode" mapstructure:"level-output-mode"`
}

Options contains configuration items related to log.

func NewOptions

func NewOptions() *Options

NewOptions creates an Options object with default parameters.

func (*Options) AddFlags

func (o *Options) AddFlags(fs *pflag.FlagSet)

AddFlags adds flags for log to the specified FlagSet object.

func (*Options) Build

func (o *Options) Build() error

Build constructs a global zap logger from the Config and Options.

func (*Options) String

func (o *Options) String() string

func (*Options) Validate

func (o *Options) Validate() []error

Validate validate the options fields.

type TimeRotationWriter added in v0.2.7

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

TimeRotationWriter 按时间轮转的日志写入器

func NewTimeRotationWriter added in v0.2.7

func NewTimeRotationWriter(filename, timeFormat string, maxAge int, compress bool) *TimeRotationWriter

NewTimeRotationWriter 创建一个按时间轮转的写入器

func (*TimeRotationWriter) Close added in v0.2.7

func (w *TimeRotationWriter) Close() error

Close 关闭当前文件

func (*TimeRotationWriter) Sync added in v0.2.7

func (w *TimeRotationWriter) Sync() error

Sync 实现 zapcore.WriteSyncer 接口

func (*TimeRotationWriter) Write added in v0.2.7

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

Write 实现 io.Writer 接口

type TraceContextKey added in v0.2.7

type TraceContextKey string

TraceContextKey 用于在 context 中存储自定义 trace ID

const (
	// TraceIDKey trace ID 的 context key
	TraceIDKey TraceContextKey = "trace_id"
	// SpanIDKey span ID 的 context key
	SpanIDKey TraceContextKey = "span_id"
	// RequestIDKey request ID 的 context key
	RequestIDKey TraceContextKey = "request_id"
)

Directories

Path Synopsis
Package distribution implements a logger which compatible to logrus/std log/prometheus.
Package distribution implements a logger which compatible to logrus/std log/prometheus.
advanced command
Package main 展示日志模块的高级功能组合使用
Package main 展示日志模块的高级功能组合使用
colorful command
Package main 展示带颜色和方括号的日志输出
Package main 展示带颜色和方括号的日志输出
compare command
Package main 对比展示带颜色和不带颜色的日志输出
Package main 对比展示带颜色和不带颜色的日志输出
comparison command
对比三种日志分级输出模式
对比三种日志分级输出模式
context command
dailyrotation command
Package main 展示按天轮转日志功能
Package main 展示按天轮转日志功能
duplicatemode command
演示 duplicate 模式:app.log 记录所有日志,error.log 额外记录错误
演示 duplicate 模式:app.log 记录所有日志,error.log 额外记录错误
exactlevel command
Package main 展示精确级别输出模式
Package main 展示精确级别输出模式
hourlyrotation command
Package main 展示按小时轮转日志功能
Package main 展示按小时轮转日志功能
leveloutput command
Package main 展示日志分级输出功能
Package main 展示日志分级输出功能
microservices command
Package main 展示微服务间的链路追踪
Package main 展示微服务间的链路追踪
nocolor command
Package main 展示不带颜色但有方括号的日志输出
Package main 展示不带颜色但有方括号的日志输出
production command
演示实际生产环境的日志配置:app.log 记录所有,error.log 额外记录错误,按天轮转
演示实际生产环境的日志配置:app.log 记录所有,error.log 额外记录错误,按天轮转
simple command
tracing command
Package main 展示链路追踪集成功能
Package main 展示链路追踪集成功能
typed-logs command
演示类型化日志的使用
演示类型化日志的使用
vlevel command
Package klog init klog logger.
Package klog init klog logger.
Package logrus adds a hook to the logrus logger hooks.
Package logrus adds a hook to the logrus logger hooks.
Package otel 提供 OpenTelemetry 集成
Package otel 提供 OpenTelemetry 集成

Jump to

Keyboard shortcuts

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