logging

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2021 License: MIT Imports: 28 Imported by: 1

README

logging

logging 简单封装了在日常使用 zap 打日志时的常用方法。

  • 提供快速使用 zap 打印日志的方法,除 zap 的 DPanic 、 DPanicf 方法外所有日志打印方法开箱即用
  • 提供多种快速创建 logger 的方法
  • 集成 Sentry,设置 DSN 后可直接使用 Sentry ,支持在使用 Error 及其以上级别打印日志时自动将该事件上报到 Sentry
  • 支持从 Context 中创建、获取带有 Trace ID 的 logger
  • 提供 gin 的日志中间件,支持使用 logging 的 logger 打印访问日志,支持 Trace ID,可以记录更加详细的请求和响应信息,支持通过配置自定义。
  • 支持服务内部函数方式和外部 HTTP 方式动态调整日志级别,无需修改配置、重启服务
  • 支持自定义 logger Encoder 配置
  • 支持将日志保存到文件并自动 rotate
  • 支持 Gorm 日志打印 Trace ID

logging 只提供 zap 使用时的常用方法汇总,不是对 zap 进行二次开发,拒绝过度封装。

安装

go get -u github.com/uhonliu/go-logging

开箱即用

logging 提供的开箱即用方法都是使用自身默认 logger 克隆出的 CtxLogger 实际执行的。 在 logging 被 import 时,会生成内部使用的默认 logger 。 默认 logger 使用 JSON 格式打印日志内容到 stderr 。 默认不带 Sentry 上报功能,可以通过设置环境变量或者替换 logger 方法支持。 默认 logger 可通过代码内部动态修改日志级别, 默认不支持 HTTP 方式动态修改日志级别,需要指定端口创建新的 logger 来支持。 默认带有初始字段 pid 打印进程 ID 。

开箱即用的方法第一个参数为 context.Context, 可以传入 gin.Context ,会尝试从其中获取 Trace ID 进行日志打印,无需 Trace ID 可以直接传 nil

示例 example/logging.go

全局开箱即用的方法默认不支持 sentry 自动上报 Error 级别的事件,有两种方式可以使其支持:

  1. 通过设置系统环境变量 SENTRY_DSNSENTRY_DEBUG 来实现自动上报。

  2. 也可以通过替换默认 logger 来实现让全局方法支持 Error 以上级别自动上报。

示例 example/replace.go

快速获取、创建你的 Logger

logging 提供多种方式快速获取一个 logger 来打印日志

示例 example/logger.go

带 Trace ID 的 CtxLogger

每一次函数或者 gin 的 http 接口调用,在最顶层入口处都将一个带有唯一 trace id 的 logger 放入 context.Context 或 gin.Context , 后续函数在内部打印日志时从 Context 中获取带有本次调用 trace id 的 logger 来打印日志几个进行调用链路跟踪。

示例 1 普通函数中打印打印带 Trace ID 的日志 example/context.go

示例 2 gin 中打印带 Trace ID 的日志 example/gin.go:

动态修改 logger 日志级别

logging 可以在代码中对 AtomicLevel 调用 SetLevel 动态修改日志级别,也可以通过请求 HTTP 接口修改。 创建 logger 时可自定义端口运行 HTTP 服务来接收请求修改日志级别。实际使用中日志级别通常写在配置文件中, 可以通过监听配置文件的修改来动态调用 SetLevel 方法。

示例 example/atomiclevel.go

自定义 logger Encoder 配置

示例 example/encoder.go

日志保存到文件并自动 rotate

使用 lumberjack 将日志保存到文件并 rotate ,采用 zap 的 RegisterSink 方法和 Config.OutputPaths 字段添加自定义的日志输出的方式来使用 lumberjack 。

示例 example/lumberjack.go

支持 Gorm 日志打印 Trace ID

使用 gorm v2 支持 context logger 打印 trace id

示例 example/gorm.go

gin middleware: GinLogger

GinLogger uses zap to log detailed access logs in JSON or text format with trace id, supports flexible and rich configuration, and supports automatic reporting of log events above error level to sentry

示例: example/ginlogger.go

Documentation

Overview

Package logging 简单封装了在日常使用 zap 打日志时的常用方法。

提供快速使用 zap 打印日志的全部方法,所有日志打印方法开箱即用

提供多种快速创建 logger 的方法

支持在使用 Error 及其以上级别打印日志时自动将该事件上报到 Sentry

支持从 context.Context/gin.Context 中创建、获取带有 Trace ID 的 logger

Index

Constants

View Source
const (
	// SentryDSNEnvKey 引入包时默认创建 logger 将尝试从该环境变量名中获取 sentry dsn
	SentryDSNEnvKey = "SENTRY_DSN"
	// SentryDebugEnvKey 尝试从该环境变量中获取 sentry 是否开启 debug 模式
	SentryDebugEnvKey = "SENTRY_DEBUG"
	// AtomicLevelAddrEnvKey 初始化时尝试获取该环境变量用于设置动态修改日志级别的 http 服务运行地址
	AtomicLevelAddrEnvKey = "ATOMIC_LEVEL_ADDR"
)
View Source
const (
	// LogFilename 默认日志文件名
	LogFilename = "/tmp/logging.log"
)

Variables

View Source
var (
	// GormLoggerName gorm logger 名称
	GormLoggerName = "gorm"
	// GormLoggerCallerSkip caller skip
	GormLoggerCallerSkip = 3
)
View Source
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,
	}
)
View Source
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

func AttachCore(l *zap.Logger, c zapcore.Core) *zap.Logger

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

func CloneLogger(name string, fields ...zap.Field) *zap.Logger

CloneLogger return the global logger copy which add a new name

func CtxLogger

func CtxLogger(c context.Context, fields ...zap.Field) *zap.Logger

CtxLogger get the ctxLogger in context

func CtxTraceID

func CtxTraceID(c context.Context) string

CtxTraceID get trace id from context Modify TraceIDPrefix change change the prefix

func Debug

func Debug(c context.Context, msg string, fields ...zap.Field)

Debug 尝试从 Context 中获取带 trace id 的 logger 记录 debug 级别的日志

func Debugf

func Debugf(c context.Context, template string, args ...interface{})

Debugf 尝试从 Context 中获取带 trace id 的 sugared logger 来模板字符串记录 debug 级别的日志 logging.Debugf(nil, "str:%s", "abd")

func Debugs

func Debugs(c context.Context, args ...interface{})

Debugs 尝试从 Context 中获取带 trace id 的 sugared logger 来记录 debug 级别的日志 logging.Debugs(nil, "abc", 123)

func Debugw

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

Debugw 尝试从 Context 中获取带 trace id 的 sugared logger 来 kv 记录 debug 级别的日志 logging.Debugw(nil, "msg", "k1", "v1", "k2", "v2")

func Error

func Error(c context.Context, msg string, fields ...zap.Field)

Error 尝试从 Context 中获取带 trace id 的 logger 记录 error 级别的日志

func Errorf

func Errorf(c context.Context, template string, args ...interface{})

Errorf 尝试从 Context 中获取带 trace id 的 sugared logger 来模板字符串记录 error 级别的日志

func Errors

func Errors(c context.Context, args ...interface{})

Errors 尝试从 Context 中获取带 trace id 的 sugared logger 来记录 Error 级别的日志

func Errorw

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

Errorw 尝试从 Context 中获取带 trace id 的 sugared logger 来 kv 记录 error 级别的日志

func ExtraField

func ExtraField(keysAndValues ...interface{}) zap.Field

ExtraField 顺序传入 kv 对,返回以 extra 为 key ,传入的 kv 对组成的 map 为值的 zap Reflect Field 在需要固定日志外层 json 字段有需要添加新字段时可以使用

func Fatal

func Fatal(c context.Context, msg string, fields ...zap.Field)

Fatal 尝试从 Context 中获取带 trace id 的 logger 记录 fatal 级别的日志

func Fatalf

func Fatalf(c context.Context, template string, args ...interface{})

Fatalf 尝试从 Context 中获取带 trace id 的 sugared logger 来模板字符串记录 fatal 级别的日志

func Fatals

func Fatals(c context.Context, args ...interface{})

Fatals 尝试从 Context 中获取带 trace id 的 sugared logger 来记录 Fatal 级别的日志

func Fatalw

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

Fatalw 尝试从 Context 中获取带 trace id 的 sugared logger 来 kv 记录 fatal 级别的日志

func FuncName

func FuncName(pc uintptr) string

FuncName 返回调用本函数的函数名称 pc runtime.Caller 返回的第一个值

func GetGinRequestBody

func GetGinRequestBody(c *gin.Context) []byte

GetGinRequestBody 获取请求 body

func GetGinTraceIDFromHeader

func GetGinTraceIDFromHeader(c *gin.Context) string

GetGinTraceIDFromHeader 从 gin 的 request header 中获取 key 为 TraceIDKeyname 的值作为 traceid

func GetGinTraceIDFromPostForm

func GetGinTraceIDFromPostForm(c *gin.Context) string

GetGinTraceIDFromPostForm 从 gin 的 postform 中获取 key 为 TraceIDKeyname 的值作为 traceid

func GetGinTraceIDFromQueryString

func GetGinTraceIDFromQueryString(c *gin.Context) string

GetGinTraceIDFromQueryString 从 gin 的 querystring 中获取 key 为 TraceIDKeyname 的值作为 traceid

func GinLogger

func GinLogger() gin.HandlerFunc

GinLogger 以默认配置生成 gin 的 Logger 中间件

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 Info

func Info(c context.Context, msg string, fields ...zap.Field)

Info 尝试从 Context 中获取带 trace id 的 logger 记录 info 级别的日志

func Infof

func Infof(c context.Context, template string, args ...interface{})

Infof 尝试从 Context 中获取带 trace id 的 sugared logger 来模板字符串记录 info 级别的日志

func Infos

func Infos(c context.Context, args ...interface{})

Infos 尝试从 Context 中获取带 trace id 的 sugared logger 来记录 info 级别的日志

func Infow

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

Infow 尝试从 Context 中获取带 trace id 的 sugared logger 来 kv 记录 info 级别的日志

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 NewLogger

func NewLogger(options Options) (*zap.Logger, error)

NewLogger return a zap Logger instance

func NewSentryClient

func NewSentryClient(dsn string, debug bool) (*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 Panic

func Panic(c context.Context, msg string, fields ...zap.Field)

Panic 尝试从 Context 中获取带 trace id 的 logger 记录 panic 级别的日志

func Panicf

func Panicf(c context.Context, template string, args ...interface{})

Panicf 尝试从 Context 中获取带 trace id 的 sugared logger 来模板字符串记录 panic 级别的日志

func Panics

func Panics(c context.Context, args ...interface{})

Panics 尝试从 Context 中获取带 trace id 的 sugared logger 来记录 Panic 级别的日志

func Panicw

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

Panicw 尝试从 Context 中获取带 trace id 的 sugared logger 来 kv 记录 panic 级别的日志

func RegisterLumberjackSink

func RegisterLumberjackSink(sink *LumberjackSink) error

RegisterLumberjackSink 注册 lumberjack sink 在 OutputPaths 中指定输出为 sink.Scheme://log_filename 即可使用 path url 中不指定日志文件名则使用默认的名称 一个 scheme 只能对应一个文件名,相同的 scheme 注册无效,会全部写入同一个文件

func ReplaceLogger

func ReplaceLogger(newLogger *zap.Logger) func()

ReplaceLogger 替换默认的全局 logger 为传入的新 logger 返回函数,调用它可以恢复全局 logger 为上一次的 logger

func SentryAttach

func SentryAttach(l *zap.Logger, sentryClient *sentry.Client) *zap.Logger

SentryAttach attach sentrycore

func SentryCaptureException

func SentryCaptureException(err error) error

SentryCaptureException 上报 error 信息到 sentry

func SentryCaptureMessage

func SentryCaptureMessage(msg string) error

SentryCaptureMessage 上报 message 信息到 sentry

func SentryClient

func SentryClient() *sentry.Client

SentryClient 返回默认 sentry client

func ServerIP

func ServerIP() string

ServerIP 获取当前 IP

func SetLevel

func SetLevel(lvl string)

SetLevel 使用字符串级别设置默认 logger 的 atomic level

func TextLevel

func TextLevel() string

TextLevel 返回默认 logger 的 字符串 level

func TimeEncoder

func TimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)

TimeEncoder 自定义日志时间格式, 不带时区信息, YYYY-mm-dd H:M:S.xxxxxx

func Warn

func Warn(c context.Context, msg string, fields ...zap.Field)

Warn 尝试从 Context 中获取带 trace id 的 logger 记录 warn 级别的日志

func Warnf

func Warnf(c context.Context, template string, args ...interface{})

Warnf 尝试从 Context 中获取带 trace id 的 sugared logger 来模板字符串记录 warn 级别的日志

func Warns

func Warns(c context.Context, args ...interface{})

Warns 尝试从 Context 中获取带 trace id 的 sugared logger 来记录 warn 级别的日志

func Warnw

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

Warnw 尝试从 Context 中获取带 trace id 的 sugared logger 来 kv 记录 warn 级别的日志

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 Ctxkey

type Ctxkey string

Ctxkey context key 类型

var (
	// CtxLoggerName define the ctx logger name
	CtxLoggerName Ctxkey = "ctx_logger"
	// TraceIDKeyname define the trace id keyname
	TraceIDKeyname Ctxkey = "trace_id"
	// TraceIDPrefix set the prefix when gen a trace id
	TraceIDPrefix = "logging_"
)

type GinLogDetails

type GinLogDetails struct {
	// 请求处理完成时间
	Timestamp time.Time `json:"timestamp"`
	// 请求方法
	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"`
	// 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 接口方法

func (GormLogger) Trace

func (g GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)

Trace 实现 gorm logger 接口方法

func (GormLogger) Warn

func (g GormLogger) Warn(ctx context.Context, msg string, data ...interface{})

Warn 实现 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

type SentryCoreConfig

type SentryCoreConfig struct {
	Tags              map[string]string
	DisableStacktrace bool
	Level             zapcore.Level
	FlushTimeout      time.Duration
	Hub               *sentry.Hub
}

SentryCoreConfig is a minimal set of parameters for Sentry Core.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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