formatter

package module
v1.6.7 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2025 License: MIT Imports: 23 Imported by: 0

README

nested-logrus-formatter

Build Status Go Report Card GoDoc

主要功能

  1. 控制台输出与文件写入
  2. 日志文件与行号定位,支持跳转
  3. 支持GORM的日志接管,适配其日志的打印。github.com/aohanhongzhi/gormv2-logrus
  4. 邮件报警
  5. 飞书报警
  6. http机器人报警
控制台输出与文件写入

img.png

日志文件与行号定位,支持跳转

img_1.png

支持GORM的日志接管,适配其日志的打印。

https://github.com/aohanhongzhi/gormv2-logrus

这里注意一个点,本来下面这行查询语句并不是日志记录语句,而是通过特殊栈查找,打印的该文件和行号,这样方便GORM定位与调试。

img_2.png

代码介绍

Human-readable log formatter, converts logrus fields to a nested structure:

Screenshot

Configuration:

type Formatter struct {
	// FieldsOrder - default: fields sorted alphabetically
	FieldsOrder []string

	// TimestampFormat - default: time.StampMilli = "Jan _2 15:04:05.000"
	TimestampFormat string

	// HideKeys - show [fieldValue] instead of [fieldKey:fieldValue]
	HideKeys bool

	// NoColors - disable colors
	NoColors bool

	// NoFieldsColors - apply colors only to the level, default is level + fields
	NoFieldsColors bool

	// NoFieldsSpace - no space between fields
	NoFieldsSpace bool

	// ShowFullLevel - show a full level [WARNING] instead of [WARN]
	ShowFullLevel bool

	// NoUppercaseLevel - no upper case for level value
	NoUppercaseLevel bool

	// TrimMessages - trim whitespaces on messages
	TrimMessages bool

	// CallerFirst - print caller info first
	CallerFirst bool

	// CustomCallerFormatter - set custom formatter for caller info
	CustomCallerFormatter func(*runtime.Frame) string
}

Usage

import (
	nested "github.com/antonfisher/nested-logrus-formatter"
	"github.com/sirupsen/logrus"
)

log := logrus.New()
log.SetFormatter(&nested.Formatter{
	HideKeys:    true,
	FieldsOrder: []string{"component", "category"},
})

log.Info("just info message")
// Output: Jan _2 15:04:05.000 [INFO] just info message

log.WithField("component", "rest").Warn("warn message")
// Output: Jan _2 15:04:05.000 [WARN] [rest] warn message

See more examples in the tests file.

Development

# run tests:
make test

# run demo:
make demo
GOPROXY=https://goproxy.cn,direct
或者
GOPROXY=https://goproxy.io,direct

新的使用方式

	nested "github.com/aohanhongzhi/nested-logrus-formatter"
	log "github.com/sirupsen/logrus"

    //手动初始化下就好了
    nested.LogInit(true)

img.png

	// -noConsole=true 在启动命令行加上这个,就可以实现线上不需要控制台输出,本地开发需要控制台。
	noConsole := flag.Bool("noConsole", false, "开发环境")
	flag.Parse()
	// 数据库配置
	gin.DefaultWriter = nested.LogInit(*noConsole)

配合gin使用

    gin.DefaultWriter = nested.LogInit(true)

配合gorm使用

github.com/aohanhongzhi/gormv2-logrus

	gormLogger := gormv2logrus.NewGormlog(gormv2logrus.WithLogrus(logrus.StandardLogger()))
	gormLogger.LogMode(logger.Warn)
	gormConfig := &gorm.Config{
		Logger: gormLogger,
		NamingStrategy: schema.NamingStrategy{
			TablePrefix:   "tb_",
			SingularTable: true,
		},
	}

	// 数据库配置
	var err error
	dsn := "username:password@tcp(mysq.host.com:3306)/km?charset=utf8mb4&parseTime=True&loc=Local"
	Gormdb, err = gorm.Open(
		mysql.New(mysql.Config{
			DSN:               dsn,
			DefaultStringSize: 256,
		}), gormConfig)
	if err != nil {
		panic("failed to connect database")
	}
	Gormdb.AutoMigrate(&model.NPCComputerInfo{})

输出颜色

输入图片说明

发布

git tag v1.5.2
git push --tags 

本地调试

replace github.com/aohanhongzhi/nested-logrus-formatter => /home/eric/Project/Go/nested-logrus-formatter

Tag 专属日志

为不改变现有接口,新增可选能力:启用后,任一包含字段 tag 的日志将被“旁路”写入 ./log/tag/<tag>.log,原有日志流保持不变。

nested.LogInitWithLevel(false, "my-app", log.DebugLevel)
// 开启 tag 旁路写入能力
nested.EnableTagFileRouter()

// 任意位置打印带 tag 的日志
log.WithField("tag", "orders").Info("created order #1")
log.WithField("tag", "orders").Error("order failed")
// 也可以使用其他 tag
log.WithField("tag", "book").Warn("book warn")

说明:

  • tag 文件路径:<初始化dir>/log/tag/<tag>.log
  • 滚动策略(大小、保留天数、备份数)与主日志一致
  • 异步写入,低开销;程序退出时会自动 Flush(也可手动调用 formatter.FlushAsyncHooks()

Documentation

Index

Constants

View Source
const DefaultReserveDuration = time.Duration(72) * time.Hour
View Source
const DefaultRotationSize int64 = 20 * 1024 * 1024

Variables

View Source
var (
	GlobalReserveDuration       = DefaultReserveDuration
	GlobalRotationSize    int64 = DefaultRotationSize
	GlobalMaxBackups            = 3
)

供扩展能力(如标签日志)复用的全局配置(由 LogrusInit 赋值)

View Source
var AppName string
View Source
var LogBaseDir string

LogBaseDir 保存日志的根目录(由 LogrusInit 赋值)

Functions

func EnableTagFileRouter added in v1.6.6

func EnableTagFileRouter()

EnableTagFileRouter 启用 Tag 旁路写入能力 默认查找字段名 "tag",例如: log.WithField("tag", "order").Info("created") 开闭原则:不改变任何现有接口,由业务层在初始化后主动调用启用

func FeishuRobotDetail added in v1.4.1

func FeishuRobotDetail(msg string, appName ...string)

func FlushAsyncHooks added in v1.6.2

func FlushAsyncHooks()

FlushAsyncHooks 刷新所有异步Hook中的日志

func GetCurrentPath added in v1.5.1

func GetCurrentPath() string

获取当前执行文件的目录,但是IDE下获取当前工程目录。两者都需要兼容。

func LogInit

func LogInit(noConsole bool) io.Writer

考虑单元测试里面的兼容性,所以新增增加的函数名不一样

func LogInitRobot added in v1.4.0

func LogInitRobot(noConsole, robot bool, appName string) io.Writer

本配置处理了三个日志输出,1. 控制台(二选一) 2. all.log 所有日志 (二选一) 3. log文件夹下面的分级日志(一定会输出) Deprecated

func LogInitWithDir added in v1.6.6

func LogInitWithDir(noConsole bool, appName string, logDir string, level logrus.Level, reserveDuration time.Duration, rotationSize int64, maxBackups int) io.Writer

func LogInitWithLevel added in v1.5.3

func LogInitWithLevel(noConsole bool, appName string, level logrus.Level) io.Writer

func LogInitWithMaxBackup added in v1.6.4

func LogInitWithMaxBackup(noConsole bool, appName string, level logrus.Level, reserveDuration time.Duration, rotationSize int64, maxBackups int) io.Writer

func LogInitWithName added in v1.5.1

func LogInitWithName(noConsole bool, appName string) io.Writer

本配置处理了三个日志输出,1. 控制台(二选一) 2. all.log 所有日志 (二选一) 3. log文件夹下面的分级日志(一定会输出)

func LogInitWithParam added in v1.5.8

func LogInitWithParam(noConsole bool, appName string, level logrus.Level, reserveDuration time.Duration, rotationSize int64) io.Writer

func LogrusInit added in v1.5.3

func LogrusInit(noConsole bool, appName, dir string, level logrus.Level, reserveDuration time.Duration, rotationSize int64, maxBackups int) io.Writer

支持日志存放位置

func MkLogdir added in v1.5.7

func MkLogdir(logPath string)

FIXME: 这里注意日志文件启动路径会不会随着脚本启动的时候执行目录不一样,日志文件存储也不一样。日志不是与可执行文件同一目录,而是与执行启动目录在一起。

func PanicHandler added in v1.4.0

func PanicHandler()

异常处理 https://blog.csdn.net/xia_xing/article/details/80597472

func RegisterAsyncHook added in v1.6.2

func RegisterAsyncHook(hook *AsyncHook)

RegisterAsyncHook 注册一个异步Hook以便程序退出时刷新

func RequestJson added in v1.3.8

func RequestJson(method string, url string, paramBody io.Reader, headerMap map[string]string)

func SendRobotMessage added in v1.3.8

func SendRobotMessage(content string, talkType, ReceiverId, RobotId int)

func SendToRobotMessage added in v1.4.0

func SendToRobotMessage(appName, msg string, talkType, ReceiverId, RobotId int)

func SetupSignalHandler added in v1.6.2

func SetupSignalHandler()

SetupSignalHandler 设置信号处理程序,在程序退出前刷新日志

Types

type AsyncHook added in v1.6.2

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

AsyncHook 是一个异步的logrus hook,用于避免日志写入阻塞主程序

func NewAsyncHook added in v1.6.2

func NewAsyncHook(hook logrus.Hook, bufSize int) *AsyncHook

NewAsyncHook 创建一个新的AsyncHook

func (*AsyncHook) Fire added in v1.6.2

func (h *AsyncHook) Fire(entry *logrus.Entry) error

Fire 实现Hook接口,将日志条目发送到异步处理通道

func (*AsyncHook) Flush added in v1.6.2

func (h *AsyncHook) Flush()

Flush 等待所有日志条目被处理

func (*AsyncHook) Levels added in v1.6.2

func (h *AsyncHook) Levels() []logrus.Level

Levels 返回此Hook处理的日志级别

type Formatter

type Formatter struct {
	// FieldsOrder - default: fields sorted alphabetically
	FieldsOrder []string

	// TimestampFormat - default: time.StampMilli = "Jan _2 15:04:05.000"
	TimestampFormat string

	// HideKeys - show [fieldValue] instead of [fieldKey:fieldValue]
	HideKeys bool

	// NoColors - disable colors
	NoColors bool

	// NoFieldsColors - apply colors only to the level, default is level + fields
	NoFieldsColors bool

	// NoFieldsSpace - no space between fields
	NoFieldsSpace bool

	// ShowFullLevel - show a full level [WARNING] instead of [WARN]
	ShowFullLevel bool

	// NoUppercaseLevel - no upper case for level value
	NoUppercaseLevel bool

	// TrimMessages - trim whitespaces on messages
	TrimMessages bool

	// CallerFirst - print caller info first
	CallerFirst bool

	// CustomCallerFormatter - set custom formatter for caller info
	CustomCallerFormatter func(*runtime.Frame) string
}

Formatter - logrus formatter, implements logrus.Formatter

func (*Formatter) Format

func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error)

Format an log entry

type MailAuthHook added in v1.3.4

type MailAuthHook struct {
	AppName  string
	Host     string
	Port     int
	From     *mail.Address
	To       *mail.Address
	Username string
	Password string
}

MailAuthHook to sends logs by email with authentication.

func NewMailAuthHook added in v1.3.4

func NewMailAuthHook(appname string, host string, port int, from string, to string, username string, password string) (*MailAuthHook, error)

creates a hook to be added to an instance of logger.

func (*MailAuthHook) Fire added in v1.3.4

func (hook *MailAuthHook) Fire(entry *logrus.Entry) error

Fire is called when a log event is fired.

func (*MailAuthHook) Levels added in v1.3.4

func (hook *MailAuthHook) Levels() []logrus.Level

Levels returns the available logging levels.

type MailHook added in v1.3.4

type MailHook struct {
	AppName string
	// contains filtered or unexported fields
}

MailHook to sends logs by email without authentication.

func NewMailHook added in v1.3.4

func NewMailHook(appname string, host string, port int, from string, to string) (*MailHook, error)

NewMailHook creates a hook to be added to an instance of logger.

func (*MailHook) Fire added in v1.3.4

func (hook *MailHook) Fire(entry *logrus.Entry) error

Fire is called when a log event is fired.

func (*MailHook) Levels added in v1.3.4

func (hook *MailHook) Levels() []logrus.Level

Levels returns the available logging levels.

type MessageParamIM added in v1.3.8

type MessageParamIM struct {
	TalkType   int    `form:"talk_type" json:"talk_type" binding:"required,oneof=1 2" label:"talk_type"`
	ReceiverId int    `form:"receiver_id" json:"receiver_id" binding:"required,numeric,gt=0" label:"receiver_id"`
	Text       string `form:"text" json:"text" binding:"required,max=3000" label:"text"`
	RobotId    int    `form:"robot_id" json:"robot_id" label:"robot_id"`
}

type NewMessageParamIM added in v1.4.0

type NewMessageParamIM struct {
	Type string `json:"type"`
	//SenderId int           `json:"sender_id"` // TODO 最好传过来,可以标记是极兔助手还是快码机器人。但是总体来说没啥关系。
	Content  string        `json:"content"`
	QuoteId  string        `json:"quote_id"`
	Mentions []interface{} `json:"mentions"`
	Receiver struct {
		ReceiverId int `json:"receiver_id"`
		TalkType   int `json:"talk_type"`
	} `json:"receiver"`
}

type NewRobotTextMessageRequest added in v1.4.0

type NewRobotTextMessageRequest struct {
	NewMessageParamIM
	RobotId int `json:"robot_id"`
}

type RobotLog added in v1.3.8

type RobotLog struct {
	AppName string
}

func NewRobotLogger added in v1.3.8

func NewRobotLogger(AppName string) *RobotLog

func (*RobotLog) Fire added in v1.3.8

func (hook *RobotLog) Fire(entry *log.Entry) error

func (*RobotLog) Levels added in v1.3.8

func (hook *RobotLog) Levels() []log.Level

type TagRouterHook added in v1.6.6

type TagRouterHook struct{}

TagRouterHook 根据 entry.Data["tag"] 将日志额外写入 tag 专属文件 注意:该 Hook 不改变原有日志流,只做“旁路”追加

func (*TagRouterHook) Fire added in v1.6.6

func (h *TagRouterHook) Fire(entry *logrus.Entry) error

func (*TagRouterHook) Levels added in v1.6.6

func (h *TagRouterHook) Levels() []logrus.Level

type TenantAccessTokenBody added in v1.4.1

type TenantAccessTokenBody struct {
	Code              int `json:"code"`
	Expire            int `json:"expire"`
	RequestTime       time.Time
	Msg               string `json:"msg"`
	TenantAccessToken string `json:"tenant_access_token"`
}
var LatestToken TenantAccessTokenBody // 最新的token

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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