logger

package module
v0.0.17 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2026 License: MIT Imports: 19 Imported by: 37

README

Logger

一个基于 logrus 的 Go 日志库,提供日志轮转、自动清理和灵活配置。

快速开始

import "github.com/WQGroup/logger"

func main() {
    // 零配置,直接使用
    logger.Info("应用程序启动")
    // 输出:2024-01-01 12:00:00.123 - [INFO]: 应用程序启动

    logger.WithField("user_id", 12345).Info("用户登录")
    // 输出:2024-01-01 12:00:00.123 - [INFO]: 用户登录 user_id=12345
}

默认日志级别为 Info,日志文件写入 ./Logs/ 目录,按天轮转,保留 7 天。

配置方式

通过代码
import "github.com/sirupsen/logrus"

settings := logger.NewSettings()
settings.LogNameBase = "myapp"
settings.Level = logrus.DebugLevel
settings.MaxAgeDays = 30
settings.MaxSizeMB = 100
settings.UseHierarchicalPath = true

logger.SetLoggerSettings(settings)
通过 YAML

创建 config.yaml

log_root: "/var/log/myapp"
log_name_base: "myapp"
level: "info"
days_to_keep: 7
max_size_mb: 0
use_hierarchical_path: false
err := logger.SetLoggerFromYAML("config.yaml")
if err != nil {
    panic(err)
}

日志存储

默认扁平结构(UseHierarchicalPath = false):

./Logs/
├── myapp--202401010800--.log
├── myapp--202401020800--.log
└── myapp--202401030800--.log

分层结构(UseHierarchicalPath = true)按 YYYY/MM/DD 组织目录。

更多

依赖

许可证

MIT

Documentation

Index

Constants

View Source
const (
	NameDef = "logger"

	// 格式器类型常量
	FormatterTypeWithField = "withField"
	FormatterTypeEasy      = "easy"
	FormatterTypeJSON      = "json"
	FormatterTypeText      = "text"
)

Variables

This section is empty.

Functions

func CleanupExpiredLogs added in v0.0.14

func CleanupExpiredLogs(root string, days int) error

func Close added in v0.0.16

func Close() error

Close 关闭日志器并释放所有资源 应用程序退出前应该调用此函数以确保所有日志被正确写入

func CurrentFileName added in v0.0.6

func CurrentFileName() string

CurrentFileName 当前日志文件名

func Debug

func Debug(args ...interface{})

func Debugf

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

func Debugln

func Debugln(args ...interface{})

func Error

func Error(args ...interface{})

func Errorf

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

func Errorln

func Errorln(args ...interface{})

func Fatal

func Fatal(args ...interface{})

func Fatalf

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

func Fatalln

func Fatalln(args ...interface{})

func GetLogger added in v0.0.2

func GetLogger() (*logrus.Logger, error)

func GetLoggerUnsafe added in v0.0.16

func GetLoggerUnsafe() *logrus.Logger

GetLoggerUnsafe 保持向后兼容的包装函数,忽略错误

func Info

func Info(args ...interface{})

func Infof

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

func Infoln

func Infoln(args ...interface{})

func LogLinkFileFPath added in v0.0.6

func LogLinkFileFPath() string

LogLinkFileFPath returns the path of the current log file.

func NewLogHelper

func NewLogHelper(settings *Settings) *logrus.Logger

func NewLogHelperWithError added in v0.0.16

func NewLogHelperWithError(settings *Settings) (*logrus.Logger, error)

NewLogHelperWithError 创建日志助手,返回错误

func Panic

func Panic(args ...interface{})

func Panicf

func Panicf(format string, args ...interface{})

func Panicln

func Panicln(args ...interface{})

func Print

func Print(args ...interface{})

func Printf

func Printf(format string, args ...interface{})

func Println

func Println(args ...interface{})

func SetCustomFormatter added in v0.0.15

func SetCustomFormatter(formatter logrus.Formatter)

SetCustomFormatter 设置用户自定义格式器

func SetLoggerFromYAML added in v0.0.14

func SetLoggerFromYAML(path string) error

func SetLoggerName

func SetLoggerName(name string)

SetLoggerName 设置日志名称(向后兼容)

func SetLoggerSettings added in v0.0.11

func SetLoggerSettings(inSettings ...*Settings)

func SetLoggerSettingsWithError added in v0.0.16

func SetLoggerSettingsWithError(inSettings ...*Settings) error

SetLoggerSettingsWithError 设置日志配置,返回错误

func Warn

func Warn(args ...interface{})

func Warnf

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

func Warning

func Warning(args ...interface{})

func Warningf

func Warningf(format string, args ...interface{})

func Warningln

func Warningln(args ...interface{})

func Warnln

func Warnln(args ...interface{})

func WithField added in v0.0.15

func WithField(key string, value interface{}) *logrus.Entry

WithField 返回一个带有单个字段的 logrus.Entry

func WithFields added in v0.0.15

func WithFields(fields map[string]interface{}) *logrus.Entry

WithFields 返回一个带有多个字段的 logrus.Entry

Types

type FormatterFactory added in v0.0.15

type FormatterFactory struct{}

FormatterFactory 格式器工厂

func (*FormatterFactory) CreateFormatter added in v0.0.15

func (f *FormatterFactory) CreateFormatter(settings *Settings) logrus.Formatter

CreateFormatter 根据设置创建相应的格式器

type Settings added in v0.0.11

type Settings struct {
	OnlyMsg             bool          // 废弃:仅输出消息,不包含时间戳等额外信息(向后兼容,内部映射到 FormatterType)
	Level               logrus.Level  // 日志级别
	LogRootFPath        string        // 日志根目录
	LogNameBase         string        // 日志名称
	RotationTime        time.Duration // 日志轮转时间
	MaxAge              time.Duration // 日志最大保存时间
	MaxAgeDays          int
	MaxSizeMB           int
	UseHierarchicalPath bool // 是否使用分层路径(YYYY/MM/DD)

	// 新增的格式器配置字段
	FormatterType    string           // 格式器类型:"withField", "easy", "json", "text"
	TimestampFormat  string           // 时间戳格式(默认 "2006-01-02 15:04:05.000")
	CustomFormatter  logrus.Formatter // 用户自定义格式器
	DisableTimestamp bool             // 是否禁用时间戳
	DisableLevel     bool             // 是否禁用日志级别
	DisableCaller    bool             // 是否禁用调用者信息
	FullTimestamp    bool             // 是否显示完整时间戳
	LogFormat        string           // 自定义日志格式(用于 easy-formatter)
}

func LoadSettingsFromYAML added in v0.0.14

func LoadSettingsFromYAML(path string) (*Settings, error)

func NewSettings added in v0.0.11

func NewSettings() *Settings

NewSettings 创建一个新的日志设置

type WithFieldFormatter added in v0.0.15

type WithFieldFormatter struct {
	TimestampFormat  string // 时间戳格式
	DisableTimestamp bool   // 是否禁用时间戳
	DisableLevel     bool   // 是否禁用日志级别
	DisableCaller    bool   // 是否禁用调用者信息
}

WithFieldFormatter 自定义日志格式器,支持结构化字段输出 输出格式:2025-12-18 18:32:07.379 - [INFO]: 【实时通知】事件广播成功 operation=(a+b)-c result=123.45

func (*WithFieldFormatter) Format added in v0.0.15

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

Format 实现 logrus.Formatter 接口

type YamlConfig added in v0.0.14

type YamlConfig struct {
	LogRoot             string `yaml:"log_root"`
	LogNameBase         string `yaml:"log_name_base"`
	Level               string `yaml:"level"`
	DaysToKeep          int    `yaml:"days_to_keep"`
	MaxSizeMB           int    `yaml:"max_size_mb"`
	UseHierarchicalPath bool   `yaml:"use_hierarchical_path"`

	// 新增的格式器配置字段
	FormatterType    string `yaml:"formatter_type"`
	TimestampFormat  string `yaml:"timestamp_format"`
	DisableTimestamp bool   `yaml:"disable_timestamp"`
	DisableLevel     bool   `yaml:"disable_level"`
	DisableCaller    bool   `yaml:"disable_caller"`
	FullTimestamp    bool   `yaml:"full_timestamp"`
	LogFormat        string `yaml:"log_format"`
}

Directories

Path Synopsis
examples
concurrent_demo command
demo command
formatter_demo command
gui_demo command
rotation_demo command

Jump to

Keyboard shortcuts

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