glogs

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2021 License: Apache-2.0 Imports: 26 Imported by: 6

README

使用介绍

引入日志包

import "github.com/layasugar/glogs"

日志打印

参数默认值
    glogs.SetLogAppName(genv.AppName()),            // 默认应用名称"default-app"
    glogs.SetLogAppMode(genv.AppMode()),            // 默认应用环境"dev"
    glogs.SetLogType(genv.LogType()),               // 默认日志类型"file"
    glogs.SetLogPath(genv.LogPath()),               // 默认文件目录"/home/log/app"
    glogs.SetLogChildPath("自定义/%Y-%m-%d %H.log"), // 默认子目录"glogs/%Y-%m-%d.log"
    glogs.SetLogMaxSize(32*1024*1024),              // 默认值32M
    glogs.SetLogMaxAge(7*24*time.Hour),             // 设置文件保留最大天数,默认值保留7天
    glogs.SetRotationTime(time.Hour),               // 设置文件分割时间、默认值24*time.Hour(按天分割)
    glogs.SetRotationCount(100),                    // 设置保留的最大文件数量、默认值不限制)
    glogs.SetNoBuffWriter(),                        // 设置无缓冲写入日志
使用默认值初始化,只需要配置appName和appMode(一般情况使用这个就满足需求了)
  • 文件路径在/home/logs/app/${appName}/glogs/2021-05-21.log
  • 文件满32M会自动拆分(2021-05-21.1.log 2021-05-21.2.log)按照数字增加
  • 文件每天会分割一次文件
  • 文件最大保留时间为7天
  • 文件保留个数不限制
	glogs.InitLog(
		glogs.SetLogAppName(AppName),
		glogs.SetLogAppMode(AppMode),
	)
	
	glogs.Info(template string, args ...interface{})
	glogs.Info("asda%s","sas",glogs.string("sadas","asdasd"))
    glogs.InfoF(c *gin.Context, title string, template string, args ...interface{})
    glogs.Warn(template string, args ...interface{})
    glogs.WarnF(c *gin.Context, title string, template string, args ...interface{})
    glogs.Error(template string, args ...interface{})
    glogs.ErrorF(c *gin.Context, title string, template string, args ...interface{})
特殊定制
	glogs.InitLog(
		glogs.SetLogAppName(genv.AppName()),
		glogs.SetLogAppMode(genv.AppMode()),
		glogs.SetLogType(genv.LogType()),
		glogs.SetLogPath(genv.LogPath()),
		glogs.SetLogChildPath("自定义/%Y-%m-%d %H.log"),
		glogs.SetLogMaxSize(5*1024),
		glogs.SetLogMaxAge(7*24*time.Hour),
		glogs.SetRotationTime(time.Hour),
		glogs.SetRotationCount(100),
	)
	glogs.Info(template string, args ...interface{})
    glogs.InfoF(c *gin.Context, title string, template string, args ...interface{})
    glogs.Warn(template string, args ...interface{})
    glogs.WarnF(c *gin.Context, title string, template string, args ...interface{})
    glogs.Error(template string, args ...interface{})
    glogs.ErrorF(c *gin.Context, title string, template string, args ...interface{})
想打印到其他日志文件
	Logger := glogs.NewLogger(
		glogs.SetLogAppName(genv.AppName()),
		glogs.SetLogAppMode(genv.AppMode()),
		glogs.SetLogType(genv.LogType()),
		glogs.SetLogPath(genv.LogPath()),
		glogs.SetLogChildPath("自定义/%Y-%m-%d %H.log"),
		glogs.SetLogMaxSize(5*1024),
		glogs.SetLogMaxAge(7*24*time.Hour),
		glogs.SetRotationTime(time.Hour),
		glogs.SetRotationCount(100),
	)
	Logger.Info(template string, args ...interface{})
    Logger.InfoF(c *gin.Context, title string, template string, args ...interface{})
    Logger.Warn(template string, args ...interface{})
    Logger.WarnF(c *gin.Context, title string, template string, args ...interface{})
    Logger.Error(template string, args ...interface{})
    Logger.ErrorF(c *gin.Context, title string, template string, args ...interface{})
将gin的log也定向到文件
// 设置gin的请求日志
	ginLogFile := genv.LogPath() + "/" + genv.AppName() + "/gin-http" + "/%Y-%m-%d.log"
	gin.DefaultWriter = glogs.GetWriter(
		ginLogFile,
		rotatelogs.WithRotationSize(64*1024*1024),
	)
备注
  • 带F的方法会记录title和request_id
  • logPath 配置如下"/home/logs/app/appName"到appName结束,不带最后一个斜杠

gorm_logger的使用

初始化db连接的时候载入logger
  import "gorm.io/gorm"
  import "gorm.io/gorm/logger"
    
  DB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
    Logger: glogs.Default(glogs.Sugar, logger.Info),
  })
备注
  • glogs.Sugar是uber的zap包的*zap.Logger,可用自己实现的,也可用glogs包
  • logger.Info是info类型,gorm的logger还提供的warn和error类型

trace (zipkin的链路追踪)

初始化
glogs.InitTrace(genv.AppName(), genv.HttpListen(), zipkinAddr, mod)
使用
  • 配合gin使用,加入已下中间件
// gin全局trace中间件
func SetTrace(c *gin.Context) {
	if !gutils.InSliceString(c.Request.RequestURI, gutils.IgnoreRoutes) {
		span := glogs.StartSpanR(c.Request, c.Request.RequestURI)
		if span != nil {
			span.Tag(glogs.RequestIDName, c.GetHeader(glogs.RequestIDName))
			_ = glogs.Inject(context.WithValue(context.Background(), glogs.GetSpanContextKey(), span.Context()), c.Request)
			c.Next()
			span.Finish()
		}
	}
}
  • 配合gin使用,平级使用,span1和span2是平级
span1 := glogs.StartSpanFromReq(c.Request, "我是span1")
time.Sleep(time.Second)
glogs.StopSpan(span1)

span2 := glogs.StartSpanFromReq(c.Request, "我是span2")
time.Sleep(100 * time.Microsecond)
glogs.StopSpan(span2)
  • 配合gin使用,上下级使用,span3的上级是span2,span2的上级是span1
span1 := glogs.StartSpanR(c.Request, "我是span1")
time.Sleep(time.Second)
glogs.StopSpan(span1)

span2 := glogs.StartSpanP(span1.Context(), "我是span2")
time.Sleep(100 * time.Microsecond)
glogs.StopSpan(span2)

span3 := glogs.StartSpanP(span2.Context(), "我是span3")
time.Sleep(200 * time.Microsecond)
glogs.StopSpan(span3)
  • 单独使用,平级和上下级, span2和span3都是span1的子集,span2和span3是平级
span1 := glogs.StartSpan("我是span1")
time.Sleep(time.Second)
glogs.StopSpan(span1)

span2 := glogs.StartSpanP(span1.Context(), "我是span2")
time.Sleep(100 * time.Microsecond)
glogs.StopSpan(span2)

span3 := glogs.StartSpanP(span1.Context(), "我是span3")
time.Sleep(200 * time.Microsecond)
glogs.StopSpan(span3)
备注

钉钉推送

初始化
glogs.InitDing(robotKey, robotHost)
使用
var alarmData = &glogs.AlarmData{
    Title:       "我是一个快乐的机器人",
    Description: "快乐的机器人",
    Content: map[string]interface{}{
        "time": time.Now(),
        "haha": "流弊机器人",
    },
}
glogs.SendDing(alarmData)
备注
  • 钉钉推送不需要开协程,方法里面已经做了处理

Documentation

Overview

Package glogs is a global internal glogs glogs: this is extend package, use https://github.com/uber-go/zap

Index

Constants

View Source
const (
	DefaultAppName       = "default-app"        // 默认应用名称
	DefaultAppMode       = "dev"                // 默认应用环境
	DefaultLogType       = "file"               // 默认日志类型
	DefaultLogPath       = "/home/logs/app"     // 默认文件目录
	DefaultChildPath     = "glogs/%Y-%m-%d.log" // 默认子目录
	DefaultRotationSize  = 32 * 1024 * 1024     // 默认大小为32M
	DefaultRotationCount = 0                    // 默认不限制
	DefaultRotationTime  = 24 * time.Hour       // 默认每天轮转一次
	DefaultNoBuffWrite   = false                // 不不开启无缓冲写入
	DefaultMaxAge        = 90 * 24 * time.Hour  // 默认保留90天

	LevelInfo  = "info"
	LevelWarn  = "warn"
	LevelError = "error"
)

Variables

View Source
var (
	RequestIDName    = "x-b3-traceid"
	HeaderAppName    = "app-name"
	KeyPath          = "path"
	KeyTitle         = "title"
	KeyOriginAppName = "origin_app_name"
)
View Source
var (
	Sugar *zap.Logger

	DefaultConfig = &Config{
		appName:       DefaultAppName,
		appMode:       DefaultAppMode,
		logType:       DefaultLogType,
		logPath:       DefaultLogPath,
		childPath:     DefaultChildPath,
		RotationSize:  DefaultRotationSize,
		RotationCount: DefaultRotationCount,
		NoBuffWrite:   DefaultNoBuffWrite,
		RotationTime:  DefaultRotationTime,
		MaxAge:        DefaultMaxAge,
	}
)
View Source
var DingCh = make(chan *AlarmData, 10)
View Source
var SpanContextKey = "default_app_context_span"

SpanContextKey ctx key,约定ctx的key名称

View Source
var SqlLogger = "sql_logger"
View Source
var Tracer *zipkin.Tracer

Tracer 引擎

Functions

func Default

func Default(writer *zap.Logger, level logger.LogLevel) logger.Interface

func Error

func Error(template string, args ...interface{})

func ErrorF

func ErrorF(r *http.Request, title string, template string, args ...interface{})

func GetSpanContextKey

func GetSpanContextKey() string

func GetWriter

func GetWriter(filename string, lc *Config) io.Writer

GetWriter 按天切割按大小切割 filename 文件名 RotationSize 每个文件的大小 MaxAge 文件最大保留天数 RotationCount 最大保留文件个数 RotationTime 设置文件分割时间 RotationCount 设置保留的最大文件数量

func Info

func Info(template string, args ...interface{})

func InfoF

func InfoF(r *http.Request, title string, template string, args ...interface{})

func InitDing

func InitDing(key, host string)

func InitLog

func InitLog(options ...LogOptionFunc)

InitLog 初始化日志文件 logPath= /home/logs/app/appName/childPath

func InitTrace

func InitTrace(serviceName, serviceEndpoint, zipkinAddr string, mod uint64) error

InitTrace 初始化trace

func Inject

func Inject(ctx context.Context, r *http.Request) error

Inject 注入span信息到请求头

func SendDing

func SendDing(d *AlarmData)

func StartSpan

func StartSpan(name string) zipkin.Span

StartSpan 根据上下文创建span

func StartSpanP

func StartSpanP(ctx model.SpanContext, name string) zipkin.Span

func StartSpanR

func StartSpanR(r *http.Request, name string) zipkin.Span

StartSpanR 根据请求头创建span

func StopSpan

func StopSpan(span zipkin.Span)

StopSpan 结束

func String

func String(key string, value interface{}) zap.Field

func Warn

func Warn(template string, args ...interface{})

func WarnF

func WarnF(r *http.Request, title string, template string, args ...interface{})

func WithRequest added in v0.0.3

func WithRequest(r *http.Request) context.Context

func WithValue added in v0.0.3

func WithValue(value string) context.Context

Types

type AlarmAt

type AlarmAt struct {
	AtMobiles []string `json:"atMobiles"`
	IsAtAll   bool     `json:"isAtAll"`
}

type AlarmData

type AlarmData struct {
	Title       string                 //报警标题
	Description string                 //报警描述
	Content     map[string]interface{} //kv数据
}

func (*AlarmData) SendAlarm

func (ad *AlarmData) SendAlarm() error

type AlarmMarkdown

type AlarmMarkdown struct {
	Title string `json:"title"`
	Text  string `json:"text"`
}

type AlarmMsg

type AlarmMsg struct {
	MsgType  string        `json:"msgtype"`
	Text     AlarmText     `json:"text"`
	Markdown AlarmMarkdown `json:"markdown"`
	At       AlarmAt       `json:"at"`
}

type AlarmText

type AlarmText struct {
	Content string `json:"content"`
}

type Config added in v0.0.2

type Config struct {
	RotationSize  int64         // 单个文件大小
	RotationCount uint          // 可以保留的文件个数
	NoBuffWrite   bool          // 设置无缓冲日志写入
	RotationTime  time.Duration // 日志分割的时间
	MaxAge        time.Duration // 日志最大保留的天数
	// contains filtered or unexported fields
}

type CusLog

type CusLog struct {
	Logger *zap.Logger
	Config *Config
}

func NewLogger

func NewLogger(options ...LogOptionFunc) *CusLog

NewLogger 得到一个zap.Logger

func (*CusLog) Error

func (l *CusLog) Error(template string, args ...interface{})

func (*CusLog) ErrorF

func (l *CusLog) ErrorF(r *http.Request, title string, template string, args ...interface{})

func (*CusLog) Info

func (l *CusLog) Info(template string, args ...interface{})

func (*CusLog) InfoF

func (l *CusLog) InfoF(r *http.Request, title string, template string, args ...interface{})

func (*CusLog) Warn

func (l *CusLog) Warn(template string, args ...interface{})

func (*CusLog) WarnF

func (l *CusLog) WarnF(r *http.Request, title string, template string, args ...interface{})

type GormCtx added in v0.0.3

type GormCtx struct {
	context.Context
	// contains filtered or unexported fields
}

func (*GormCtx) String added in v0.0.3

func (c *GormCtx) String() string

type LogOptionFunc

type LogOptionFunc func(*Config)

func SetLogAppMode

func SetLogAppMode(appMode string) LogOptionFunc

设置环境变量,标识当前应用运行的环境,默认值dev

func SetLogAppName

func SetLogAppName(appName string) LogOptionFunc

设置应用名称,默认值default-app

func SetLogChildPath

func SetLogChildPath(childPath string) LogOptionFunc

设置子目录—+文件名,保证一个类型的文件在同一个文件夹下面便于区分、默认值glogs/%Y-%m-%d.log

func SetLogMaxAge

func SetLogMaxAge(maxAge time.Duration) LogOptionFunc

SetLogMaxAge 设置文件最大保留时间、默认值7天

func SetLogMaxSize

func SetLogMaxSize(size int64) LogOptionFunc

设置单个文件最大值byte,默认值32M

func SetLogPath

func SetLogPath(logPath string) LogOptionFunc

设置日志目录,这个是主目录,程序会给此目录拼接上项目名,子目录以及文件,默认值/home/logs/app

func SetLogType

func SetLogType(logType string) LogOptionFunc

设置日志类型,日志类型目前分为2种,console和file,默认值file

func SetNoBuffWriter

func SetNoBuffWriter() LogOptionFunc

SetNoBuffWriter 设置无缓冲写入日志,比较消耗性能

func SetRotationCount

func SetRotationCount(n uint) LogOptionFunc

SetRotationCount 设置保留的最大文件数量、没有默认值(表示不限制)

func SetRotationTime

func SetRotationTime(rotationTime time.Duration) LogOptionFunc

SetRotationTime 设置文件分割时间、默认值24*time.Hour(按天分割)

type Trace

type Trace struct {
	ServiceName     string // 服务名
	ServiceEndpoint string // 当前服务节点
	ZipkinAddr      string // zipkin地址
	Mod             uint64 // 采样率,0==不进行链路追踪,1==全量。值越大,采样率月底,对性能影响越小
}

func GetNewTrace

func GetNewTrace(serviceName, serviceEndpoint, zipkinAddr string, mod uint64) *Trace

GetNewTrace 获取配置

func (*Trace) GetTrace

func (t *Trace) GetTrace() (*zipkin.Tracer, error)

GetTrace 获取tracer

func (*Trace) InitTracer

func (t *Trace) InitTracer() error

InitTracer 初始化tracer

Directories

Path Synopsis
log
package rotatelogs is a port of File-RotateLogs from Perl (https://metacpan.org/release/File-RotateLogs), and it allows you to automatically rotate output files when you write to them according to the filename pattern that you can specify.
package rotatelogs is a port of File-RotateLogs from Perl (https://metacpan.org/release/File-RotateLogs), and it allows you to automatically rotate output files when you write to them according to the filename pattern that you can specify.

Jump to

Keyboard shortcuts

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