logger

package module
v0.0.0-...-7bfebd0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2025 License: MIT Imports: 20 Imported by: 5

README

需要注意 lumberjack 不管是v2还是v3 都有多goroutine写入导致goroutine泄露的问题

logger

基于Zap,可选日志文件归档方式

Feature

  • 根据info/warn级别切割日志文件
  • 根据文件大小归档
  • 根据时间归档
  • 时间切割单元可选
  • 日志发送到sentry

Usage

  • install logger with go get

go get github.com/23233/ggg/logger

  1. 新建logger
import (
 "github.com/23233/ggg/logger"
)

...

c := logger.New()
c.SetDivision("time")	    // 设置归档方式,"time"时间归档 "size" 文件大小归档,文件大小等可以在配置文件配置
c.SetTimeUnit(logger.Minute) // 时间归档 可以设置切割单位
c.SetEncoding("json")	    // 输出格式 "json" 或者 "console"

c.SetInfoFile("./logs/server.log")		// 设置info级别日志
c.SetErrorFile("./logs/server_err.log")	// 设置warn级别日志

c.InitLogger()
  1. 从配置文件中加载(Toml,Yaml,Json)
// toml file
c := logger.NewFromToml("configs/config.toml")

// yaml file
c := logger.NewFromYaml("configs/config.yaml")


// json file
c := logger.NewFromJson("configs/config.json")

c.InitLogger()
  1. caller 显示调用文件行号
c.SetCaller(true)
c.SetCallerSkip(1) // 从我算起 我是1 如果你自己再封装一次 再+1
  1. 输出
import (
 "github.com/23233/ggg/logger"
)

...
c := logger.New()
c.InitLogger()

logger.Info("info level test")
logger.Error("error level test")
logger.Warn("warn level test")
logger.Debug("debug level test")
logger.Fatal("fatal level test")

// format
logger.Infof("info level test: %s", "111")
logger.Errorf("error level test: %s", "111")
logger.Warnf("warn level test: %s", "111")
logger.Debugf("debug level test: %s", "111")
{"level":"info","time":"2019-09-11T18:32:59.680+0800","msg":"info level test"}
{"level":"error","time":"2019-09-11T18:32:59.680+0800","msg":"error level test"}
{"level":"warn","time":"2019-09-11T18:32:59.681+0800","msg":"warn level test"}
{"level":"debug","time":"2019-09-11T18:32:59.681+0800","msg":"debug level test"}
{"level":"fatal","time":"2019-09-11T18:32:59.681+0800","msg":"fatal level test"}
  1. with args
import (
 "github.com/23233/ggg/logger"
)

...
c := logger.New()
c.InitLogger()

logger.Info("this is a log", logger.With("Trace", "12345677"))
logger.Info("this is a log", logger.WithError(errors.New("this is a new error")))
{"level":"info","time":"2019-09-11T18:38:51.022+0800","msg":"this is a log","Trace":"12345677"}
{"level":"info","time":"2019-09-11T18:38:51.026+0800","msg":"this is a log","error":"this is a new error"}

Performance

BenchmarkLogger/logde_logger_without_fields-4            3000000               563 ns/op
BenchmarkLogger/logde_logger_with_fields-4               2000000               637 ns/op
BenchmarkLogger/logde_logger_without_fields_write_into_file-4             200000             13021 ns/op
BenchmarkLogger/logde_logger_with_fields_write_into_file-4                100000             12606 ns/op
  1. sentry
c := logger.New()
c.SetDivision("time")     // 设置归档方式,"time"时间归档 "size" 文件大小归档,文件大小等可以在配置文件配置
c.SetTimeUnit(logger.Day) // 时间归档 可以设置切割单位
c.SetEncoding("json")     // 输出格式 "json" 或者 "console"
//c.Stacktrace = true

c.SetInfoFile("./logs/server.log")      // 设置info级别日志
c.SetErrorFile("./logs/server_err.log") // 设置warn级别日志

c.SentryConfig = logger.SentryLoggerConfig{
    DSN:              "sentry dsn",
    Debug:            true,
    AttachStacktrace: true,
    Environment:      "dev",
    Tags: map[string]string{
        "source": "demo",
    },
}

c.InitLogger()

Documentation

Index

Constants

View Source
const (
	TimeDivision        = "time"
	SizeDivision        = "size"
	TimeAndSizeDivision = "time_and_size"
)
View Source
const (
	Minute = "minute"
	Hour   = "hour"
	Day    = "day"
	Month  = "month"
	Year   = "year"
)

Variables

This section is empty.

Functions

func ChangeJsCaller

func ChangeJsCaller(call int)

func ChangeJtCaller

func ChangeJtCaller(call int)

func NewCircularFifoQueue

func NewCircularFifoQueue(maxSize uint) *circularFifoQueue

NewCircularFifoQueue creates a new circularFifoQueue.

func NewSentryCore

func NewSentryCore(cfg sentryCoreConfig, sentryClient *sentry.Client) *core

NewSentryCore 生成Core对象

func NewStats

func NewStats() *stats

func NewTimeSizeRotator

func NewTimeSizeRotator(filename string, maxSize, maxBackups, maxAge int, compress bool, unit TimeUnit) io.Writer

NewTimeSizeRotator 是 TimeSizeRotator 的构造函数

Types

type Log

type Log struct {
	L  *zap.Logger
	Op *LogOptions
}
var (
	DefaultPath = "./logs/"
	J           *Log // json day
	JH          *Log // json hour
	Js          *Log // json size
	JM          *Log // json day size mix
)

func InitJsonSizeLog

func InitJsonSizeLog(prefix string, fields ...zap.Field) *Log

func InitJsonTimeLog

func InitJsonTimeLog(prefix string, t TimeUnit, fields ...zap.Field) *Log

func InitJsonTimeSizeLog

func InitJsonTimeSizeLog(prefix string, t TimeUnit, maxSize int, fields ...zap.Field) *Log

func (*Log) Close

func (c *Log) Close() *Log

func (*Log) Debug

func (c *Log) Debug(msg string, args ...zap.Field)

func (*Log) Debugf

func (c *Log) Debugf(format string, args ...interface{})

func (*Log) ErrEf

func (c *Log) ErrEf(err error, format string, args ...interface{})

func (*Log) Error

func (c *Log) Error(msg string, args ...zap.Field)

func (*Log) ErrorE

func (c *Log) ErrorE(err error, format string, args ...interface{})

func (*Log) ErrorFw

func (c *Log) ErrorFw(field []zap.Field, format string, args ...interface{})

func (*Log) Errorf

func (c *Log) Errorf(format string, args ...interface{})

func (*Log) Fatal

func (c *Log) Fatal(msg string, args ...zap.Field)

func (*Log) Fatalf

func (c *Log) Fatalf(format string, args ...interface{})

func (*Log) Info

func (c *Log) Info(msg string, args ...zap.Field)

func (*Log) InfoFw

func (c *Log) InfoFw(field []zap.Field, format string, args ...interface{})

func (*Log) Infof

func (c *Log) Infof(format string, args ...interface{})

func (*Log) ViewQueueFunc

func (c *Log) ViewQueueFunc(w http.ResponseWriter, r *http.Request)

func (*Log) ViewStatsFunc

func (c *Log) ViewStatsFunc(w http.ResponseWriter, r *http.Request)

func (*Log) Warn

func (c *Log) Warn(msg string, args ...zap.Field)

func (*Log) Warnf

func (c *Log) Warnf(format string, args ...interface{})

func (*Log) With

func (c *Log) With(k string, v interface{}) zap.Field

func (*Log) WithError

func (c *Log) WithError(err error) zap.Field

type LogOptions

type LogOptions struct {
	// Encoding sets the logger's encoding. Valid values are "json" and
	// "console", as well as any third-party encodings registered via
	// RegisterEncoder.
	Encoding      string             `json:"encoding" yaml:"encoding" toml:"encoding"`
	InfoFilename  string             `json:"info_filename" yaml:"info_filename" toml:"info_filename"`
	ErrorFilename string             `json:"error_filename" yaml:"error_filename" toml:"error_filename"`
	MaxSize       int                `json:"max_size" yaml:"max_size" toml:"max_size"` // mb 默认100mb
	MaxBackups    int                `json:"max_backups" yaml:"max_backups" toml:"max_backups"`
	MaxAge        int                `json:"max_age" yaml:"max_age" toml:"max_age"` // day 默认不限
	Compress      bool               `json:"compress" yaml:"compress" toml:"compress"`
	Division      string             `json:"division" yaml:"division" toml:"division"`
	LevelSeparate bool               `json:"level_separate" yaml:"level_separate" toml:"level_separate"`
	TimeUnit      TimeUnit           `json:"time_unit" yaml:"time_unit" toml:"time_unit"`
	Stacktrace    bool               `json:"stacktrace" yaml:"stacktrace" toml:"stacktrace"`
	SentryConfig  SentryLoggerConfig `json:"sentry_config" yaml:"sentry_config" toml:"sentry_config"`
	Fields        []zap.Field        `json:"fields,omitempty" yaml:"fields" toml:"fields"`
	// contains filtered or unexported fields
}

func New

func New() *LogOptions

func (*LogOptions) AddField

func (c *LogOptions) AddField(k string, v any)

func (*LogOptions) CloseConsoleDisplay

func (c *LogOptions) CloseConsoleDisplay()

func (*LogOptions) ErrorQueue

func (c *LogOptions) ErrorQueue() *circularFifoQueue

func (*LogOptions) GetStats

func (c *LogOptions) GetStats() *stats

func (*LogOptions) InfoQueue

func (c *LogOptions) InfoQueue() *circularFifoQueue

func (*LogOptions) InitLogger

func (c *LogOptions) InitLogger() *Log

func (*LogOptions) QueueSize

func (c *LogOptions) QueueSize() uint

func (*LogOptions) SetCaller

func (c *LogOptions) SetCaller(b bool)

func (*LogOptions) SetCallerSkip

func (c *LogOptions) SetCallerSkip(skip int)

func (*LogOptions) SetDivision

func (c *LogOptions) SetDivision(division string)

func (*LogOptions) SetEnableQueue

func (c *LogOptions) SetEnableQueue(enableQueue bool)

func (*LogOptions) SetEnableStats

func (c *LogOptions) SetEnableStats(enable bool)

func (*LogOptions) SetEncoding

func (c *LogOptions) SetEncoding(encoding string)

func (*LogOptions) SetErrorFile

func (c *LogOptions) SetErrorFile(path string)

func (*LogOptions) SetInfoFile

func (c *LogOptions) SetInfoFile(path string)

func (*LogOptions) SetQueueSize

func (c *LogOptions) SetQueueSize(queueSize uint)

func (*LogOptions) SetStatsClearIntervalDay

func (c *LogOptions) SetStatsClearIntervalDay(statsClearIntervalDay uint8)

func (*LogOptions) SetStatsFormat

func (c *LogOptions) SetStatsFormat(format string)

func (*LogOptions) SetTimeUnit

func (c *LogOptions) SetTimeUnit(t TimeUnit)

type SentryLoggerConfig

type SentryLoggerConfig struct {
	DSN              string `toml:"dsn" yaml:"dsn" json:"dsn"`
	Debug            bool
	AttachStacktrace bool
	Environment      string
	Tags             map[string]string
}

type TimeSizeRotator

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

TimeSizeRotator 实现了 io.Writer 接口, 能够同时根据日期和文件大小来轮转日志。 当天内的轮转会以 "-1", "-2" 的序号形式命名。

func (*TimeSizeRotator) Write

func (r *TimeSizeRotator) Write(p []byte) (n int, err error)

Write 实现了 io.Writer 接口

type TimeUnit

type TimeUnit string

func (TimeUnit) Format

func (t TimeUnit) Format() string

func (TimeUnit) RotationGap

func (t TimeUnit) RotationGap() time.Duration

Jump to

Keyboard shortcuts

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