logger

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2022 License: MIT Imports: 30 Imported by: 4

README

logger

logger

logger wraps uber/zap and trace with opentelemetry

flowchart LR
logger -- openTelemetrySDK --> trace
trace -- http --> tempo

logger -- zap --> log 
log-->loki

tempo-->grafana
loki-->grafana

Feature
  • 支持日志及切分
  • 支持追踪(基于 opentelemetry
  • 支持 Debug,Info,Warn,Error,Fatal 日志等级
  • 支持异常自动恢复 defer logger.End(ctx)
Install
go get -u -v github.com/itmisx/logger
Usage
  • 配置项

    type Config struct {
        // 调试模式,默认仅记录错误
        Debug              bool    `yaml:"debug" mapstructure:"debug"`   
        // 日志文件记录开关   
        EnableLog          bool    `yaml:"enable_log" mapstructure:"enable_log"`   
        // 日志追踪开关
        EnableTrace        bool    `yaml:"enable_trace" mapstructure:"enable_trace"` 
        // 日志文件路径
        File               string  `yaml:"file" mapstructure:"file"` 
        // 单个日志文件的大小限制,单位MB  
        MaxSize            int     `yaml:"max_size" mapstructure:"max_size"`  
        // 日志文件数据的限制   
        MaxBackups         int     `yaml:"max_backups" mapstructure:"max_backups"` 
        // 日志文件的保存天数  
        MaxAge             int     `yaml:"max_age" mapstructure:"max_age"`   
        // 日志文件压缩开关   
        Compress           bool    `yaml:"compress" mapstructure:"compress"`
        // 日志切分的时间,参考linux定时任务0 0 0  * * *,精确到秒  
        Rotate             string  `yaml:"rotate" mapstructure:"rotate"`   
        // 追踪内容导出类型,默认为jaeger
        TracerProviderType string  `yaml:"tracer_provider_type" mapstructure:"tracer_provider_type"`
        // 追踪采样的频率, 0.0-1
        TraceSampleRatio   float64 `yaml:"trace_sample_ratio" mapstructure:"trace_sample_ratio"`
        // jaeger的URI地址
        JaegerServer       string  `yaml:"jaeger_server" mapstructure:"jaeger_server"`
        // jaeger用户名
        JaegerUsername     string  `yaml:"jaeger_username" mapstructure:"jaeger_username"`
        // jaeger密码
        JaegerPassword     string  `yaml:"jaeger_password" mapstructure:"jaeger_password"`
    }
    
  • 初始化

    // 初始化,配置参考logger.Config
    // service.name为服务的名字
    // service.version为版本
    // logger.Init(config,attrs...logger.Field),更多的logger.Type参考logger下filed.go
    logger.Init(conf,logger.String("service.name","service1"),logger.String("service.version","version"))
    
  • 基础使用

    // 在一个函数中启动一个span
    // 并注册一个延迟结束(!!切记,缺少可能会导致内存泄露)
    func foo(){
        // logger.Start(ctx,spanName,attrs...logger.Field)
        // 可以为一个span指定spanName以及额外的属性信息
        // attr支持logger.String("key","value") 形式,更多的logger.Type参考logger下filed.go
        ctx:=logger.Start(context,spanName,logger.String("key","value"))
        defer logger.End(ctx)
        // 正常记录日志
        // logger.Info(ctx,msg,attrs...logger.Field)
        // 记录msg信息及额外的信息
        // attr支持logger.String("key","value") 形式
        // 支持Debug,Info,Warn,Error,Fatal
        logger.Info(ctx,msg,logger.String("key","value"))
    }
    
  • 追踪传递,就是传递 traceID 和 spanID

    gin 框架实例

    // 请求方
    //
    // 请求方调用request时,注入context trace信息
    // post为封装的一个请求函数
    func post(ctx context.Context){
        …… // request的请求
        // 注入context追踪信息
        // request类型为*http.Request
        logger.HttpInject(ctx,request)
        …… // 发送请求
    }
    
    
    // 接收方
    // gin举例,初始化gin时,注册中间件
    // sevice为当前后台服务的名称
    router.Use(GinMiddleware("service"))
    // 使用
    func foo(c *gin.Context){
        ctx:=logger.Start(c.Request.Context(),spanName,logger.String("key","value"))
        defer logger.End(ctx)
        // 正常记录日志
        logger.Info(ctx,msg,logger.String("key","value"))
    }
    

    手动传递

    // 对于不能通过函数或请求传递的,则需要手动传递
    // 通过 指定traceID和spanID生成一个context
    //
    // 然后,logger.Start(ctx,"spanName"),其生成的span就为childspan
    //
    // 其中traceID和spanID可以利用logger.GenTraceID()和logger.GenSpanID()生成
    // 也可以通过上个start返回的spanCtx中获得,logger.TraceID(spanCtx),logger.SpanID(spanCtx)
    ctx, err := NewRootContext(traceID, spanID)
    
functions
  • Init(conf Config,applicationAttributes ...logger.Field) //初始化,配置及应用信息
  • Start(ctx context.Context,spanName string,spanStartOption ...logger.Field) context.Context //启动日志追踪,spanName 为追踪跨度的名称,spanStartOption 为跨度额外信息
  • Info(ctx context.Context,msg string,attributes ...logger.Field) // 普通日志
  • Warn(ctx context.Context,msg string,attributes ...logger.Field) // 警告日志
  • Error(ctx context.Context,msg string,attributes ...logger.Field) // 错误日志
  • End(ctx context.Context) //结束日志追踪
  • TraceID(ctx context.Context)string //获取 traceID
  • SpanID(ctx context.Context)string //获取 spanID
  • GenTraceID()string // 生成 traceID
  • GenSpanID()string // 生成 spanID

logger.Field 类型支持

  • bool
  • boolSlice
  • int
  • intSlice
  • int64
  • int64Slice
  • float64
  • float64Slice
  • string
  • stringSlice
  • stringer, interface{String()string{}}
基于loki+tempo+grafana的效果(日志查询+追踪)

image

License

Use of logger is governed by the Mit License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Debug

func Debug(ctx context.Context, msg string, attributes ...Field)

Debug record debug

func End

func End(ctx context.Context)

End end trace

func Error

func Error(ctx context.Context, msg string, attributes ...Field)

Error record error

func Fatal

func Fatal(ctx context.Context, msg string, attributes ...Field)

Fatal record fatal

func FieldsToKeyValues

func FieldsToKeyValues(fields ...Field) []attribute.KeyValue

FieldsToKeyValue

func FieldsToZapFields

func FieldsToZapFields(ctx context.Context, fields ...Field) []zapcore.Field

FieldsToZapFields

func GenSpanID

func GenSpanID() string

GenSpanID gererate spanID

func GenTraceID

func GenTraceID() string

GenTraceID generate traceID current timestamp with 8 rand bytes

func GinMiddleware

func GinMiddleware(service string) gin.HandlerFunc

GinMiddleware extract spanContext

func HttpInject

func HttpInject(ctx context.Context, request *http.Request) error

HTTPInject inject spanContext

func Info

func Info(ctx context.Context, msg string, attributes ...Field)

Info record info

func Init

func Init(conf Config, applicationAttributes ...Field)

LoggerInit logger初始化

applicationAttributes 应用属性,如应用的名称,版本等 can use service.name,service.namesapce,service.instance.id,service.version, telemetry.sdk.name,telemetry.sdk.language,telemetry.sdk.version,telemetry.auto.version or other key that you need

example: Init(conf,String("sevice.name",service1))

func NewRootContext

func NewRootContext(traceID string, spanID string) (context.Context, error)

NewRootContext new root context with given traceID and spanID

func SetSpanAttr added in v0.0.2

func SetSpanAttr(ctx context.Context, attributes ...Field)

SetSpanAttr 为当前的span动态设置属性

func SpanID

func SpanID(ctx context.Context) string

TraceID return traceID

func Start

func Start(ctx context.Context, spanName string, spanStartOption ...Field) context.Context

Start 启动一个span追踪 ctx 上级span spanName span名字 spanStartOption span附带属性

func TraceID

func TraceID(ctx context.Context) string

TraceID return traceID

func Warn

func Warn(ctx context.Context, msg string, attributes ...Field)

Warn record warn

Types

type Config

type Config struct {
	// 是否开启debug模式,未开启debug模式,仅记录错误
	Debug bool `yaml:"debug" mapstructure:"debug"`
	// 追踪使能
	EnableTrace bool `yaml:"enable_trace" mapstructure:"enable_trace"`
	// 日志输出的方式
	// none为不输出日志,file 为文件方式输出,console为控制台。默认为console
	Output string `yaml:"output" mapstructure:"output"`
	// 日志文件路径
	File string `yaml:"file" mapstructure:"file"` // 日志文件路径
	// 日志文件大小限制,默认最大100MB,超过将触发文件切割
	MaxSize int `yaml:"max_size" mapstructure:"max_size"`
	// 日志文件的分割文件的数量,超过的将会被删除
	MaxBackups int `yaml:"max_backups" mapstructure:"max_backups"`
	// 日志文件的保留时间,超过的将会被删除
	MaxAge int `yaml:"max_age" mapstructure:"max_age"`
	// 是否启用日志文件的压缩功能
	Compress bool `yaml:"compress" mapstructure:"compress"`
	// 是否启用日志的切割功能
	Rotate string `yaml:"rotate" mapstructure:"rotate"`
	// 日志追踪的类型,file or jaeger
	TracerProviderType string `yaml:"tracer_provider_type" mapstructure:"tracer_provider_type"`
	// 日志追踪采样的比率, 0.0-1
	// 0,never trace
	// 1,always trace
	TraceSampleRatio float64 `yaml:"trace_sample_ratio" mapstructure:"trace_sample_ratio"`
	// 最大span数量限制,当达到最大限制时,停止trace
	// default 200
	MaxSpan int `yaml:"max_span" mapstructure:"max_span"`
	// Jaeger server
	JaegerServer   string `yaml:"jaeger_server" mapstructure:"jaeger_server"`
	JaegerUsername string `yaml:"jaeger_username" mapstructure:"jaeger_username"`
	JaegerPassword string `yaml:"jaeger_password" mapstructure:"jaeger_password"`
}

Config 配置项

type Field

type Field struct {
	Key        string
	Type       FieldType
	Bool       bool
	Bools      []bool
	Integer    int
	Integers   []int
	String     string
	Float64    float64
	Integer64  int64
	Integer64s []int64
	Strings    []string
	Float64s   []float64
	Any        interface{}
}

func Any added in v0.0.3

func Any(key string, val interface{}) Field

Any

func Bool

func Bool(key string, val bool) Field

Bool

func BoolSlice

func BoolSlice(key string, val []bool) Field

BoolSlice

func Err added in v0.0.3

func Err(err error) Field

Err

func Float64

func Float64(key string, val float64) Field

Float64

func Float64Slice

func Float64Slice(key string, val []float64) Field

Float64Slice

func Int

func Int(key string, val int) Field

Int

func Int64

func Int64(key string, val int64) Field

Int64

func Int64Slice

func Int64Slice(key string, val []int64) Field

Int64Slice

func IntSlice

func IntSlice(key string, val []int) Field

IntSlice

func String

func String(key string, val string) Field

String

func StringSlice

func StringSlice(key string, val []string) Field

StringSlice

func Stringer

func Stringer(key string, val fmt.Stringer) Field

Stringer

type FieldType

type FieldType int

type LoggerSpanContext

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

save context span

type Trace

type Trace struct{}

func (Trace) NewFileProvider

func (tx Trace) NewFileProvider(conf Config, attributes ...Field) (*trace.TracerProvider, error)

NewFileProvider

func (Trace) NewJaegerProvider

func (tx Trace) NewJaegerProvider(conf Config,
	attributes ...Field,
) (*trace.TracerProvider, error)

NewJaegerProvider

Directories

Path Synopsis
propagation

Jump to

Keyboard shortcuts

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