Documentation ¶
Overview ¶
Package logit 简单封装了在日常使用 zap 打日志时的常用方法。
提供快速使用 zap 打印日志的全部方法,所有日志打印方法开箱即用
提供多种快速创建 baseLogger 的方法
支持从 context.Context/gin.Context 中创建、获取带有 Trace ID 的 baseLogger
Index ¶
- Constants
- Variables
- func AttachCore(l *zap.Logger, c zapcore.Core) *zap.Logger
- func CallerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder)
- func CloneLogger(name string, fields ...zap.Field) *zap.Logger
- func CtxLogger(c context.Context, fields ...zap.Field) *zap.Logger
- func CtxTraceID(c context.Context) string
- func Debug(c context.Context, msg string, fields ...zap.Field)
- func Debugf(c context.Context, template string, args ...interface{})
- func Debugs(c context.Context, args ...interface{})
- func Debugw(c context.Context, msg string, keysAndValues ...interface{})
- func Error(c context.Context, msg string, fields ...zap.Field)
- func Errorf(c context.Context, template string, args ...interface{})
- func Errors(c context.Context, args ...interface{})
- func Errorw(c context.Context, msg string, keysAndValues ...interface{})
- func ExtraField(keysAndValues ...interface{}) zap.Field
- func Fatal(c context.Context, msg string, fields ...zap.Field)
- func Fatalf(c context.Context, template string, args ...interface{})
- func Fatals(c context.Context, args ...interface{})
- func Fatalw(c context.Context, msg string, keysAndValues ...interface{})
- func For(c context.Context, fields ...interface{}) *zap.SugaredLogger
- func FuncName(pc uintptr) string
- func GetGinRequestBody(c *gin.Context) []byte
- func GetGinTraceIDFromHeader(c *gin.Context) string
- func GetGinTraceIDFromPostForm(c *gin.Context) string
- func GetGinTraceIDFromQueryString(c *gin.Context) string
- func GinLogger() gin.HandlerFunc
- func GinLoggerWithConfig(conf GinLoggerConfig) gin.HandlerFunc
- func Info(c context.Context, msg string, fields ...zap.Field)
- func Infof(c context.Context, template string, args ...interface{})
- func Infos(c context.Context, args ...interface{})
- func Infow(c context.Context, msg string, keysAndValues ...interface{})
- func NewCtxLogger(c context.Context, logger *zap.Logger, traceID string) (context.Context, *zap.Logger)
- func NewGinLogger(conf GinLoggerConfig) gin.HandlerFunc
- func NewLogger(options Options) (*zap.Logger, error)
- func Panic(c context.Context, msg string, fields ...zap.Field)
- func Panicf(c context.Context, template string, args ...interface{})
- func Panics(c context.Context, args ...interface{})
- func Panicw(c context.Context, msg string, keysAndValues ...interface{})
- func RegisterSink(scheme string, sink zap.Sink) error
- func ReplaceLogger(newLogger *zap.Logger) func()
- func ServerIP() string
- func SetContextLogger(c context.Context, logger *zap.Logger) context.Context
- func SetLevel(lvl string) error
- func Sync(c context.Context) error
- func TextLevel() string
- func TimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)
- func Warn(c context.Context, msg string, fields ...zap.Field)
- func Warnf(c context.Context, template string, args ...interface{})
- func Warns(c context.Context, args ...interface{})
- func Warnw(c context.Context, msg string, keysAndValues ...interface{})
- type AtomicLevelServerOption
- type CtxKey
- type GinLogExtends
- type GinLoggerConfig
- type GormLogger
- func (g GormLogger) CtxLogger(ctx context.Context) *zap.Logger
- func (g GormLogger) Error(ctx context.Context, msg string, data ...interface{})
- func (g GormLogger) Info(ctx context.Context, msg string, data ...interface{})
- func (g GormLogger) LogMode(gormLogLevel gormlogger.LogLevel) gormlogger.Interface
- func (g GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)
- func (g GormLogger) Warn(ctx context.Context, msg string, data ...interface{})
- type GormLoggerOptions
- type LumberjackSink
- type Options
- type RedisLogger
- func (l RedisLogger) AfterProcess(ctx context.Context, cmd redis.Cmder) error
- func (l RedisLogger) AfterProcessPipeline(ctx context.Context, cmds []redis.Cmder) error
- func (l RedisLogger) BeforeProcess(ctx context.Context, cmd redis.Cmder) (context.Context, error)
- func (l RedisLogger) BeforeProcessPipeline(ctx context.Context, cmds []redis.Cmder) (context.Context, error)
- func (l RedisLogger) CtxLogger(ctx context.Context) *zap.Logger
- type RedisLoggerOptions
Constants ¶
const ( // GormLoggerName gorm baseLogger 名称 GormLoggerName = "gorm" // GormLoggerCallerSkip caller skip GormLoggerCallerSkip = 3 )
Variables ¶
var ( // AtomicLevelMap string level mapping zap AtomicLevel AtomicLevelMap = map[string]zap.AtomicLevel{ "debug": zap.NewAtomicLevelAt(zap.DebugLevel), "info": zap.NewAtomicLevelAt(zap.InfoLevel), "warn": zap.NewAtomicLevelAt(zap.WarnLevel), "error": zap.NewAtomicLevelAt(zap.ErrorLevel), "dpanic": zap.NewAtomicLevelAt(zap.DPanicLevel), "panic": zap.NewAtomicLevelAt(zap.PanicLevel), "fatal": zap.NewAtomicLevelAt(zap.FatalLevel), } // ZapcoreLevelMap string level mapping zapcore.Level ZapcoreLevelMap = map[string]zapcore.Level{ "debug": zap.DebugLevel, "info": zap.InfoLevel, "warn": zap.WarnLevel, "error": zap.ErrorLevel, "dpanic": zap.DPanicLevel, "panic": zap.PanicLevel, "fatal": zap.FatalLevel, } )
Functions ¶
func AttachCore ¶
AttachCore add a core to zap baseLogger
func CallerEncoder ¶
func CallerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder)
CallerEncoder
@Description: serializes a caller in package/file:funcname:line format @param caller @param enc
func CloneLogger ¶
CloneLogger return the global baseLogger copy which add a new name
func CtxLogger ¶
CtxLogger
@Description: get the ctxLogger in context @param c @param fields @return *zap.Logger
func CtxTraceID ¶
CtxTraceID get trace id from context Modify TraceIDPrefix change the prefix
func Debugf ¶
Debugf 尝试从 Context 中获取带 trace id 的 sugared baseLogger 来模板字符串记录 debug 级别的日志 logit.Debugf(nil, "str:%s", "abd")
func Debugs ¶
Debugs 尝试从 Context 中获取带 trace id 的 sugared baseLogger 来记录 debug 级别的日志 logit.Debugs(nil, "abc", 123)
func Debugw ¶
Debugw 尝试从 Context 中获取带 trace id 的 sugared baseLogger 来 kv 记录 debug 级别的日志 logit.Debugw(nil, "msg", "k1", "v1", "k2", "v2")
func ExtraField ¶
ExtraField 顺序传入 kv 对,返回以 extra 为 key ,传入的 kv 对组成的 map 为值的 zap Reflect Field 在需要固定日志外层 json 字段有需要添加新字段时可以使用
func FuncName ¶
FuncName
@Description: FuncName 返回调用本函数的函数名称 @param pc runtime.Caller 返回的第一个值 @return string
func GetGinTraceIDFromHeader ¶
GetGinTraceIDFromHeader
@Description: 从 gin 的 request header 中获取 key 为 TraceIDKeyName 的值作为 traceid @param c @return string
func GetGinTraceIDFromPostForm ¶
GetGinTraceIDFromPostForm
@Description: 从 gin 的 post form 中获取 key 为 TraceIDKeyName 的值作为 traceid @param c @return string
func GetGinTraceIDFromQueryString ¶
GetGinTraceIDFromQueryString
@Description: 从 gin 的 querystring 中获取 key 为 TraceIDKeyName 的值作为 traceid @param c @return string
func GinLogger ¶
func GinLogger() gin.HandlerFunc
GinLogger
@Description: 以默认配置生成 gin 的 Logger 中间件 @return gin.HandlerFunc
func GinLoggerWithConfig ¶
func GinLoggerWithConfig(conf GinLoggerConfig) gin.HandlerFunc
GinLoggerWithConfig
@Description: 根据配置信息生成 gin 的 Logger 中间件
中间件会记录访问信息,根据状态码确定日志级别, 500 以上为 Error , 400-500 默认为 Warn , 400 以下默认为 Info api 请求进来的 context 的函数无需在其中打印 err ,使用 c.Error(err)会在请求完成时自动打印 error context 中有 error 则日志忽略返回码始终使用 error 级别
@param conf @return gin.HandlerFunc
func NewCtxLogger ¶
func NewCtxLogger(c context.Context, logger *zap.Logger, traceID string) (context.Context, *zap.Logger)
NewCtxLogger
@Description: return a context with baseLogger and trace id and a baseLogger with trace id @param c @param logger @param traceID @return context.Context @return *zap.Logger
func NewGinLogger ¶ added in v0.4.0
func NewGinLogger(conf GinLoggerConfig) gin.HandlerFunc
NewGinLogger
@Description: alias for GinLoggerWithConfig @param conf @return gin.HandlerFunc
func RegisterSink ¶ added in v0.3.0
RegisterSink 注册 lumberjack sink 在 OutputPaths 中指定输出为 sink.Scheme://log_filename 即可使用 path url 中不指定日志文件名则使用默认的名称 一个 scheme 只能对应一个文件名,相同的 scheme 注册无效,会全部写入同一个文件
func ReplaceLogger ¶
ReplaceLogger 替换默认的全局 baseLogger 为传入的新 baseLogger 返回函数,调用它可以恢复全局 baseLogger 为上一次的 baseLogger
func SetContextLogger ¶ added in v0.6.1
func TimeEncoder ¶
func TimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)
TimeEncoder
@Description: 自定义日志时间格式, 不带时区信息, YYYY-mm-dd H:M:S.xxxxxx @param t @param enc
Types ¶
type AtomicLevelServerOption ¶
type AtomicLevelServerOption struct { Addr string // http 动态修改日志级别服务运行地址 Path string // 设置 url path ,可选 Username string // 请求时设置 basic auth 认证的用户名,可选 Password string // 请求时设置 basic auth 认证的密码,可选,与 username 同时存在才开启 basic auth }
AtomicLevelServerOption AtomicLevel server 相关配置
type GinLogExtends ¶
type GinLogExtends struct { // 请求处理耗时 (秒) Latency float64 `json:"latency_seconds"` HandleName string `json:"handle_name"` }
GinLogExtends gin 日志中间件记录的扩展
type GinLoggerConfig ¶
type GinLoggerConfig struct { Name string // Optional. Default value is logit.defaultGinLogFormatter Formatter func(*gin.Context, GinLogExtends) string // SkipPaths is a url path array which logs are not written. // Optional. SkipPaths []string // SkipPathRegexps skip path by regexp SkipPathRegexps []string // TraceIDFunc 获取或生成 trace id 的函数 // Optional. TraceIDFunc func(*gin.Context) string // 是否使用详细模式打印日志,记录更多字段信息 // Optional. EnableDetails bool // 以下选项开启后对性能有影响,适用于接口调试,慎用。 // 是否打印 context keys // Optional. EnableContextKeys bool // 是否打印请求头信息 // Optional. EnableRequestHeader bool // 是否打印请求form信息 // Optional. EnableRequestForm bool // 是否打印请求体信息 // Optional. EnableRequestBody bool // 是否打印响应体信息 // Optional. EnableResponseBody bool // 慢请求时间阈值 请求处理时间超过该值则使用 Warn 级别打印日志 SlowThreshold time.Duration // 日志输出路径,默认 []string{"console"} // Optional. OutputPaths []string // 日志初始字段 // Optional. InitialFields map[string]interface{} // 是否关闭打印 caller,默认 false // Optional. DisableCaller bool // 是否关闭打印 stack strace,默认 false // Optional. DisableStacktrace bool // 配置日志字段 key 的名称 // Optional. EncoderConfig *zapcore.EncoderConfig }
GinLoggerConfig GinLogger 支持的配置项字段定义
type GormLogger ¶
type GormLogger struct {
// contains filtered or unexported fields
}
GormLogger 使用 zap 来打印 gorm 的日志 初始化时在内部的 baseLogger 中添加 trace id 可以追踪 sql 执行记录
func NewGormLogger ¶
func NewGormLogger(opt GormLoggerOptions) (GormLogger, error)
NewGormLogger
@Description: 创建实现了 gorm logger interface 的 logger @param opt @return GormLogger @return error
func (GormLogger) CtxLogger ¶
func (g GormLogger) CtxLogger(ctx context.Context) *zap.Logger
CtxLogger 创建打印日志的 ctx logger
func (GormLogger) Error ¶
func (g GormLogger) Error(ctx context.Context, msg string, data ...interface{})
Error 实现 gorm baseLogger 接口方法
func (GormLogger) Info ¶
func (g GormLogger) Info(ctx context.Context, msg string, data ...interface{})
Info 实现 gorm baseLogger 接口方法
func (GormLogger) LogMode ¶
func (g GormLogger) LogMode(gormLogLevel gormlogger.LogLevel) gormlogger.Interface
LogMode 实现 gorm baseLogger 接口方法
type GormLoggerOptions ¶
type GormLoggerOptions struct { Name string // 日志级别 LogLevel zapcore.Level // CallerSkip,默认值 3 CallerSkip int // 慢请求时间阈值 请求处理时间超过该值则使用 Warn 级别打印日志 SlowThreshold time.Duration // 日志输出路径,默认 []string{"console"} // Optional. OutputPaths []string // 日志初始字段 // Optional. InitialFields map[string]interface{} // 是否关闭打印 caller,默认 false // Optional. DisableCaller bool // 是否关闭打印 stack strace,默认 false // Optional. DisableStacktrace bool // 配置日志字段 key 的名称 // Optional. EncoderConfig *zapcore.EncoderConfig // RecordNotFoundErr 错误等级 RecordNotFoundErrLevel string }
type LumberjackSink ¶
type LumberjackSink struct {
*lumberjack.Logger
}
LumberjackSink 将日志输出到 lumberjack 进行 rotate
func NewLumberjackSink ¶
func NewLumberjackSink(filename string, maxAge, maxBackups, maxSize int, compress, localtime bool) *LumberjackSink
NewLumberjackSink
@Description: 创建 LumberjackSink 对象 @param scheme sink scheme @param filename 文件名称 @param maxAge 最大生命周期 @param maxBackups 最多保留文件个数 @param maxSize 单个文件最大 size @param compress 是否压缩 @param localtime 是否采用本地时间 @return *LumberjackSink
func (LumberjackSink) Sync ¶
func (LumberjackSink) Sync() error
Sync lumberjack Logger 默认已实现 Sink 的其他方法,这里实现 Sync 后就成为一个 Sink 对象
type Options ¶
type Options struct { Name string // baseLogger 名称 Level string // 日志级别 debug, info, warn, error dpanic, panic, fatal Format string // 日志格式 console, json OutputPaths []string // 日志输出位置 InitialFields map[string]interface{} // 日志初始字段 DisableCaller bool // 是否关闭打印 caller DisableStacktrace bool // 是否关闭打印 stackstrace EncoderConfig *zapcore.EncoderConfig // 配置日志字段 key 的名称 }
Options new baseLogger options
type RedisLogger ¶
type RedisLogger struct {
// contains filtered or unexported fields
}
func NewRedisLogger ¶
func NewRedisLogger(opt RedisLoggerOptions) (RedisLogger, error)
func (RedisLogger) AfterProcess ¶
func (l RedisLogger) AfterProcess(ctx context.Context, cmd redis.Cmder) error
AfterProcess
@Description: 实现 go-redis HOOK AfterProcess 方法 @receiver l @param ctx @param cmd @return error
func (RedisLogger) AfterProcessPipeline ¶
func (l RedisLogger) AfterProcessPipeline(ctx context.Context, cmds []redis.Cmder) error
AfterProcessPipeline
@Description: 实现 go-redis HOOK AfterProcessPipeline 方法 @receiver l @param ctx @param cmds @return error
func (RedisLogger) BeforeProcess ¶
BeforeProcess
@Description: 实现 go-redis HOOK BeforeProcess 方法 @receiver l @param ctx @param cmd @return context.Context @return error
func (RedisLogger) BeforeProcessPipeline ¶
func (l RedisLogger) BeforeProcessPipeline(ctx context.Context, cmds []redis.Cmder) (context.Context, error)
BeforeProcessPipeline
@Description: @receiver l @param ctx @param cmds @return context.Context @return error
type RedisLoggerOptions ¶
type RedisLoggerOptions struct { Name string // CallerSkip,默认值 4 CallerSkip int // 慢请求时间阈值 请求处理时间超过该值则使用 Warn 级别打印日志 SlowThreshold time.Duration // 日志输出路径,默认 []string{"console"} // Optional. OutputPaths []string // 日志初始字段 // Optional. InitialFields map[string]interface{} // 是否关闭打印 caller,默认 false // Optional. DisableCaller bool // 是否关闭打印 stack strace,默认 false // Optional. DisableStacktrace bool // 配置日志字段 key 的名称 // Optional. EncoderConfig *zapcore.EncoderConfig // nil err level NilErrLevel string }