formatter

package module
v1.4.4 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2024 License: MIT Imports: 20 Imported by: 0

README

nested-logrus-formatter

Build Status Go Report Card GoDoc

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使用

	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.3.9
git push --tags 

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AppName string

Functions

func FeishuRobotDetail added in v1.4.1

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

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文件夹下面的分级日志(一定会输出)

func PanicHandler added in v1.4.0

func PanicHandler()

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

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)

Types

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)

NewMailAuthHook 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 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