Documentation
¶
Overview ¶
Package logging 简单封装了在日常使用 zap 打日志时的常用方法。
提供快速使用 zap 打印日志的全部方法,所有日志打印方法开箱即用
提供多种快速创建 logger 的方法
支持在使用 Error 及其以上级别打印日志时自动将该事件上报到 Sentry
支持从 context.Context/gin.Context 中创建、获取带有 Trace ID 的 logger
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 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 NewLogger(options Options) (*zap.Logger, error)
- func NewSentryClient(options sentry.ClientOptions) (*sentry.Client, error)
- func NewSentryCore(cfg SentryCoreConfig, sentryClient *sentry.Client) zapcore.Core
- 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 RegisterLumberjackSink(sink *LumberjackSink) error
- func ReplaceLogger(newLogger *zap.Logger) func()
- func SafeClientIP(gc *gin.Context) string
- func SentryAttach(l *zap.Logger, sentryClient *sentry.Client) *zap.Logger
- func SentryCaptureException(err error) error
- func SentryCaptureMessage(msg string) error
- func SentryClient() *sentry.Client
- func ServerIP() string
- func SetLevel(lvl string)
- 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 GinLogDetails
- 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 LumberjackSink
- type Options
- type SentryCoreConfig
Constants ¶
const (
// AtomicLevelAddrEnvKey 初始化时尝试获取该环境变量用于设置动态修改日志级别的 http 服务运行地址
AtomicLevelAddrEnvKey = "ATOMIC_LEVEL_ADDR"
)
const (
// LogFilename 默认日志文件名
LogFilename = "/tmp/logging.log"
)
Variables ¶
var ( // GormLoggerName gorm logger 名称 GormLoggerName = "gorm" // GormLoggerCallerSkip caller skip GormLoggerCallerSkip = 3 )
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, } )
var ( // EncoderConfig 默认的日志字段名配置 EncoderConfig = zapcore.EncoderConfig{ TimeKey: "time", LevelKey: "level", NameKey: "logger", CallerKey: "caller", MessageKey: "msg", StacktraceKey: "stacktrace", LineEnding: zapcore.DefaultLineEnding, EncodeLevel: zapcore.CapitalLevelEncoder, EncodeTime: TimeEncoder, EncodeDuration: zapcore.SecondsDurationEncoder, EncodeCaller: CallerEncoder, } )
Functions ¶
func AttachCore ¶
AttachCore add a core to zap logger
func CallerEncoder ¶
func CallerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder)
CallerEncoder serializes a caller in package/file:funcname:line format
func CloneLogger ¶
CloneLogger return the global logger copy which add a new name
func CtxTraceID ¶
CtxTraceID get trace id from context Modify TraceIDPrefix change change the prefix
func Debugf ¶
Debugf 尝试从 Context 中获取带 trace id 的 sugared logger 来模板字符串记录 debug 级别的日志 logging.Debugf(nil, "str:%s", "abd")
func Debugs ¶
Debugs 尝试从 Context 中获取带 trace id 的 sugared logger 来记录 debug 级别的日志 logging.Debugs(nil, "abc", 123)
func Debugw ¶
Debugw 尝试从 Context 中获取带 trace id 的 sugared logger 来 kv 记录 debug 级别的日志 logging.Debugw(nil, "msg", "k1", "v1", "k2", "v2")
func ExtraField ¶
ExtraField 顺序传入 kv 对,返回以 extra 为 key ,传入的 kv 对组成的 map 为值的 zap Reflect Field 在需要固定日志外层 json 字段有需要添加新字段时可以使用
func GetGinTraceIDFromHeader ¶
GetGinTraceIDFromHeader 从 gin 的 request header 中获取 key 为 TraceIDKeyname 的值作为 traceid
func GetGinTraceIDFromPostForm ¶
GetGinTraceIDFromPostForm 从 gin 的 postform 中获取 key 为 TraceIDKeyname 的值作为 traceid
func GetGinTraceIDFromQueryString ¶
GetGinTraceIDFromQueryString 从 gin 的 querystring 中获取 key 为 TraceIDKeyname 的值作为 traceid
func GinLoggerWithConfig ¶
func GinLoggerWithConfig(conf GinLoggerConfig) gin.HandlerFunc
GinLoggerWithConfig 根据配置信息生成 gin 的 Logger 中间件 中间件会记录访问信息,根据状态码确定日志级别, 500 以上为 Error , 400-500 默认为 Warn , 400 以下默认为 Info api 请求进来的 context 的函数无需在其中打印 err ,使用 c.Error(err)会在请求完成时自动打印 error context 中有 error 则日志忽略返回码始终使用 error 级别
func NewCtxLogger ¶
func NewCtxLogger(c context.Context, logger *zap.Logger, traceID string) (context.Context, *zap.Logger)
NewCtxLogger return a context with logger and trace id and a logger with trace id
func NewSentryClient ¶
func NewSentryClient(options sentry.ClientOptions) (*sentry.Client, error)
NewSentryClient return sentry client by sentrydsn
func NewSentryCore ¶
func NewSentryCore(cfg SentryCoreConfig, sentryClient *sentry.Client) zapcore.Core
NewSentryCore new a sentry core
func RegisterLumberjackSink ¶
func RegisterLumberjackSink(sink *LumberjackSink) error
RegisterLumberjackSink 注册 lumberjack sink 在 OutputPaths 中指定输出为 sink.Scheme://log_filename 即可使用 path url 中不指定日志文件名则使用默认的名称 一个 scheme 只能对应一个文件名,相同的 scheme 注册无效,会全部写入同一个文件
func ReplaceLogger ¶
ReplaceLogger 替换默认的全局 logger 为传入的新 logger 返回函数,调用它可以恢复全局 logger 为上一次的 logger
func SafeClientIP ¶
SafeClientIP 安全地获取客户端 IP,避免 nil engine 导致的 panic
func SentryAttach ¶
SentryAttach attach sentrycore
func SentryCaptureException ¶
SentryCaptureException 上报 error 信息到 sentry
func SentryCaptureMessage ¶
SentryCaptureMessage 上报 message 信息到 sentry
func TimeEncoder ¶
func TimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)
TimeEncoder 自定义日志时间格式, 不带时区信息, YYYY-mm-dd H:M:S.xxxxxx
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 GinLogDetails ¶
type GinLogDetails struct {
// 接收到请求的时间
ReqTime time.Time `json:"req_time"`
// 请求方法
Method string `json:"method"`
// 请求 Path
Path string `json:"path"`
// 请求 RawQuery
Query string `json:"query"`
// http 协议版本
Proto string `json:"proto"`
// 请求内容长度
ContentLength int `json:"content_length"`
// 请求的 host host:port
Host string `json:"host"`
// 请求 remote addr host:port
RemoteAddr string `json:"remote_addr"`
// uri
RequestURI string `json:"request_uri"`
// referer
Referer string `json:"referer"`
// user agent
UserAgent string `json:"user_agent"`
// 真实客户端 ip
ClientIP string `json:"client_ip"`
// content type
ContentType string `json:"content_type"`
// handler name
HandlerName string `json:"handler_name"`
// http 状态码
StatusCode int `json:"status_code"`
// 响应 body 字节数
BodySize int `json:"body_size"`
// 请求处理耗时 (秒)
Latency float64 `json:"latency_seconds"`
// Context 中的 Keys
ContextKeys map[string]interface{} `json:"context_keys,omitempty"`
// http request header
RequestHeader http.Header `json:"request_header,omitempty"`
// http Request Form
RequestForm url.Values `json:"request_form,omitempty"`
// 请求 body
RequestBody interface{} `json:"request_body,omitempty"`
// 响应 Body
ResponseBody interface{} `json:"response_body,omitempty"`
}
GinLogDetails gin 日志中间件记录的信息
type GinLoggerConfig ¶
type GinLoggerConfig struct {
// Optional. Default value is logging.defaultGinLogFormatter
Formatter func(context.Context, GinLogDetails) 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(context.Context) string
// InitFieldsFunc 获取 logger 初始字段方法 key 为字段名 value 为字段值
InitFieldsFunc func(context.Context) map[string]interface{}
// 是否使用详细模式打印日志,记录更多字段信息
// Optional.
EnableDetails bool
// 是否打印 context keys
// Optional.
EnableContextKeys bool
// 是否打印请求头信息
// Optional.
EnableRequestHeader bool
// 是否打印请求form信息
// Optional.
EnableRequestForm bool
// 是否打印请求体信息
// Optional.
EnableRequestBody bool
// 是否打印响应体信息
// Optional.
EnableResponseBody bool
// 慢请求时间阈值 请求处理时间超过该值则使用 Error 级别打印日志
SlowThreshold time.Duration
}
GinLoggerConfig GinLogger 支持的配置项字段定义
type GormLogger ¶
type GormLogger struct {
// contains filtered or unexported fields
}
GormLogger 使用 zap 来打印 gorm 的日志 初始化时在内部的 logger 中添加 trace id 可以追踪 sql 执行记录
func NewGormLogger ¶
func NewGormLogger(logLevel zapcore.Level, traceWithLevel zapcore.Level, slowThreshold time.Duration) GormLogger
NewGormLogger 返回带 zap logger 的 GormLogger
func (GormLogger) CtxLogger ¶
func (g GormLogger) CtxLogger(ctx context.Context) *zap.Logger
CtxLogger 创建打印日志的 ctxlogger
func (GormLogger) Error ¶
func (g GormLogger) Error(ctx context.Context, msg string, data ...interface{})
Error 实现 gorm logger 接口方法
func (GormLogger) Info ¶
func (g GormLogger) Info(ctx context.Context, msg string, data ...interface{})
Info 实现 gorm logger 接口方法
func (GormLogger) LogMode ¶
func (g GormLogger) LogMode(gormLogLevel gormlogger.LogLevel) gormlogger.Interface
LogMode 实现 gorm logger 接口方法
type LumberjackSink ¶
type LumberjackSink struct {
*lumberjack.Logger
Scheme string
}
LumberjackSink 将日志输出到 lumberjack 进行 rotate
func NewLumberjackSink ¶
func NewLumberjackSink(scheme, filename string, maxAge, maxBackups, maxSize int, compress, localtime bool) *LumberjackSink
NewLumberjackSink 创建 LumberjackSink 对象
func (LumberjackSink) Sync ¶
func (LumberjackSink) Sync() error
Sync lumberjack Logger 默认已实现 Sink 的其他方法,这里实现 Sync 后就成为一个 Sink 对象
type Options ¶
type Options struct {
Name string // logger 名称
Level string // 日志级别 debug, info, warn, error dpanic, panic, fatal
Format string // 日志格式
OutputPaths []string // 日志输出位置
InitialFields map[string]interface{} // 日志初始字段
DisableCaller bool // 是否关闭打印 caller
DisableStacktrace bool // 是否关闭打印 stackstrace
SentryClient *sentry.Client // sentry 客户端
EncoderConfig *zapcore.EncoderConfig // 配置日志字段 key 的名称
LumberjackSink *LumberjackSink // lumberjack sink 支持日志文件 rotate
AtomicLevelServer AtomicLevelServerOption // AtomicLevel server 相关配置
}
Options new logger options