xlog

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2021 License: Apache-2.0 Imports: 14 Imported by: 51

README

xlog

Go Report Card Go Reference Build status

xlog是一个go日志框架,提供简单易用的日志API

xlog同时实现了logr API (v0.2.0) (xlogr)

xlog各层可以自行实现接口进行替换,根据实际业务进行配置:

alt

安装

go get github.com/xfali/xlog

使用

1. 快速入门
logger := xlog.GetLogger()
logger.Infof("hello %s\n", "world")
logger.Panic("panic !")

// 或使用默认函数
xlog.Infof("hello %s\n", "world")
xlog.Panic("panic !")
2. 配置日志级别

xlog共支持6个日志级别:

类型 说明
DEBUG 最低级别,默认不输出
INFO 默认的日志级别
WARN 警告级别
ERROR 错误级别
PANIC Panic级别,会触发panic,参数类型为xlog.KeyValues(内置logging可配置panic函数)
FATAL 致命错误,会触发程序退出(内置logging可配置退出函数)
xlog.SetSeverityLevel(xlog.WARN)
3. 配置输出Writer

xlog默认输出到os.Stdout,可以通过下面方法配置输出的writer

// 所有日志级别统一配置为参数的输出writer
xlog.SetOutput(w)

// 或者按日志级别配置输出writer
xlog.SetOutputBySeverity(xlog.WARN, w)
4. 配置日志格式Formatter

内置支持的Formatter有:

  • xlog.TextFormatter
  • xlog.JsonFormatter
xlog.SetFormatter(f)
5. 使用logr API
logr := xlogr.NewLogr()
logr.Info("this is a test", "time", time.Now(), "float", 3.14)

内置Writer

xlog内置的输出writer有:

  • AsyncBufferLogWriter: 线程安全的异步带缓存的writer
  • AsyncLogWriter: 线程安全的异步无缓存的writer
  • RotateFileWriter: 滚动记录日志的writer

(一般RotateFileWriter结合AsyncBufferLogWriter使用)

也可以使用第三方输出writer,如:

file-rotatelogs

使用内置输出writer配置如下(详细配置请参考参数的注释说明):

w := writer.NewRotateFileWriter(&writer.RotateFile{
		Path:            "./test.log",
		RotateFrequency: writer.RotateEveryDay,
		RotateFunc:      writer.ZipLogsAsync,
	}, writer.Config{
	
	})
xlog.SetOutput(w)

Documentation

Index

Constants

View Source
const (
	//不显示调用信息
	CallerNone = 0
	//只显示文件名
	CallerShortFile = 1
	//显示文件名及路径
	CallerLongFile = 1 << 1
	//file mask
	CallerFileMask = 3
	//只显示函数名
	CallerShortFunc = 1 << 2
	//显示完整函数名
	CallerLongFunc = 1 << 3
	//显示简单函数名
	CallerSimpleFunc = 1 << 4
	//func mask
	CallerFuncMask = 7 << 2
)
View Source
const (
	//自动填充颜色
	AutoColor = iota
	//禁用颜色
	DisableColor
	//强制使用颜色
	ForceColor
)
View Source
const (
	// 时间戳的Key
	KeyTimestamp = "LogTime"
	// 日志级别key
	KeySeverityLevel = "LogLevel"
	// 调用者Key
	KeyCaller = "LogCaller"
	// 日志内容Key
	KeyContent = "LogContent"
	// 日志名称Key
	KeyName = "LogName"
)

Variables

View Source
var (
	// 默认日志深度
	LogDepth value.Value = value.NewSimpleValue(int(1))
	// 默认日志附加信息(无)
	LogFields value.Value = value.NewSimpleValue(nil)
)
View Source
var (
	//前景色
	ColorGreen   = string([]byte{27, 91, 57, 55, 59, 52, 50, 109})
	ColorWhite   = string([]byte{27, 91, 57, 48, 59, 52, 55, 109})
	ColorYellow  = string([]byte{27, 91, 57, 48, 59, 52, 51, 109})
	ColorRed     = string([]byte{27, 91, 57, 55, 59, 52, 49, 109})
	ColorBlue    = string([]byte{27, 91, 57, 55, 59, 52, 52, 109})
	ColorMagenta = string([]byte{27, 91, 57, 55, 59, 52, 53, 109})
	ColorCyan    = string([]byte{27, 91, 57, 55, 59, 52, 54, 109})
	ColorReset   = string([]byte{27, 91, 48, 109})

	ForeGreen   = "\033[97;32m"
	ForeWhite   = "\033[90;37m"
	ForeYellow  = "\033[90;33m"
	ForeRed     = "\033[97;31m"
	ForeBlue    = "\033[97;34m"
	ForeMagenta = "\033[97;35m"
	ForeCyan    = "\033[97;36m"

	//背景色
	BackGreen   = "\033[97;42m"
	BackWhite   = "\033[90;47m"
	BackYellow  = "\033[90;43m"
	BackRed     = "\033[97;41m"
	BackBlue    = "\033[97;44m"
	BackMagenta = "\033[97;45m"
	BackCyan    = "\033[97;46m"

	ResetColor = "\033[0m"
)
View Source
var (
	DefaultColorFlag     = DisableColor
	DefaultPrintFileFlag = CallerShortFile
	DefaultFatalNoTrace  = false
	DefaultLevel         = INFO
	DefaultWriters       = map[Level]io.Writer{
		DEBUG: os.Stdout,
		INFO:  os.Stdout,
		WARN:  os.Stdout,
		ERROR: os.Stderr,
		PANIC: os.Stderr,
		FATAL: os.Stderr,
	}
)

默认值

View Source
var LogTag = map[Level]string{
	DEBUG: "DEBUG",
	INFO:  "INFO",
	WARN:  "WARN",
	ERROR: "ERROR",
	PANIC: "PANIC",
	FATAL: "FATAL",
}

级别及名称映射

Functions

func CallerFormat added in v0.0.6

func CallerFormat(file string, line int, funcName string) string

func Debug

func Debug(args ...interface{})

使用默认的Logging,输出Debug级别的日志

func Debugf

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

使用默认的Logging,输出Debug级别的日志

func Debugln

func Debugln(args ...interface{})

使用默认的Logging,输出Debug级别的日志

func Error

func Error(args ...interface{})

使用默认的Logging,输出Error级别的日志

func Errorf

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

使用默认的Logging,输出Error级别的日志

func Errorln

func Errorln(args ...interface{})

使用默认的Logging,输出Error级别的日志

func Fatal

func Fatal(args ...interface{})

使用默认的Logging,输出Fatal级别的日志,注意会触发程序退出

func Fatalf

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

使用默认的Logging,输出Fatal级别的日志,注意会触发程序退出

func Fatalln

func Fatalln(args ...interface{})

使用默认的Logging,输出Fatal级别的日志,注意会触发程序退出

func FramesToCaller

func FramesToCaller() int

func GetOutputBySeverity added in v0.0.6

func GetOutputBySeverity(severity Level) io.Writer

获得默认Logging对应日志级别的输出

func Info

func Info(args ...interface{})

使用默认的Logging,输出Info级别的日志

func Infof

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

使用默认的Logging,输出Info级别的日志

func Infoln

func Infoln(args ...interface{})

使用默认的Logging,输出Info级别的日志

func InitOnce added in v0.0.9

func InitOnce(logging, factory value.Value)

配置默认的Logging、Factory value(线程安全且只能初始化一次) 可以配置为线程安全(value.AtomicValue)的和非线程安全的(value.SimpleValue)

func InitUnsafe added in v0.0.9

func InitUnsafe(logging, factory value.Value)

配置默认的Logging、Factory value(非线程安全) 可以配置为线程安全(value.AtomicValue)的和非线程安全的(value.SimpleValue)

func IsEnabled added in v0.1.1

func IsEnabled(severityLevel Level) bool

检查是否输出参数级别的日志

func NewDefaultFactory

func NewDefaultFactory(opts ...LoggingOpt) *loggerFactory

func NewFactory

func NewFactory(logging Logging) *loggerFactory

func NewFactoryWithValue added in v0.0.9

func NewFactoryWithValue(v value.Value) *loggerFactory

func NewHookLevelLogging

func NewHookLevelLogging(logging Logging, hook LevelHook) *hookLevelLogging

func NewMutableFactory added in v0.0.8

func NewMutableFactory(logging Logging) *mutableLoggerFactory

func NewMutableFactoryWithValue added in v0.0.9

func NewMutableFactoryWithValue(v value.Value) *mutableLoggerFactory

func Panic

func Panic(args ...interface{})

使用默认的Logging,输出Panic级别的日志,注意会触发panic

func Panicf

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

使用默认的Logging,输出Panic级别的日志,注意会触发panic

func Panicln

func Panicln(args ...interface{})

使用默认的Logging,输出Panic级别的日志,注意会触发panic

func ResetFactory

func ResetFactory(fac LoggerFactory)

重新配置全局的默认LoggerFactory,该方法同时会重置全局的默认Logging 由于线程安全性受defaultLogging、defaultFactory初始化(调用InitOnce)的Value决定, 所以需要确定是否确实需要调用该方法重置Logging,并保证Value线程安全

func ResetLogging added in v0.0.9

func ResetLogging(logging Logging)

重新配置全局的默认Logging,该方法同时会重置全局的默认LoggerFactory的Logging 由于线程安全性受defaultLogging、defaultFactory初始化(调用InitOnce)的Value决定, 所以需要确定是否确实需要调用该方法重置Logging,并保证Value线程安全

func SetCallerFlag added in v0.0.6

func SetCallerFlag(flag int) func(*logging)

配置内置Logging实现的文件输出标志,有ShortFile、LongFile

func SetCallerFormatter added in v0.0.6

func SetCallerFormatter(f func(file string, line int, funcName string) string) func(*logging)

配置内置Logging实现的时间格式化函数

func SetColorFlag

func SetColorFlag(flag int) func(*logging)

配置内置Logging实现的颜色的标志,有AutoColor、DisableColor、ForceColor

func SetExitFunc added in v0.0.6

func SetExitFunc(f ExitFunc) func(*logging)

配置内置Logging Fatal退出处理函数

func SetFatalNoTrace

func SetFatalNoTrace(noTrace bool) func(*logging)

配置内置Logging实现是否在发生致命错误时打印堆栈,默认打印

func SetFormatter

func SetFormatter(f Formatter)

设置默认Logging的日志格式化工具

func SetOutput

func SetOutput(w io.Writer)

设置默认Logging的输出

func SetOutputBySeverity

func SetOutputBySeverity(severity Level, w io.Writer)

设置默认Logging对应日志级别的输出

func SetPanicFunc added in v0.0.7

func SetPanicFunc(f PanicFunc) func(*logging)

配置内置Logging Panic处理函数

func SetSeverityLevel

func SetSeverityLevel(severity Level)

设置默认Logging的日志严重级别

func SetTimeFormatter

func SetTimeFormatter(f func(t time.Time) string) func(*logging)

配置内置Logging实现的时间格式化函数

func SimplifyNameFirstLetter

func SimplifyNameFirstLetter(s string) string

func TimeFormat

func TimeFormat(t time.Time) string

func Warn

func Warn(args ...interface{})

使用默认的Logging,输出Warn级别的日志

func Warnf

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

使用默认的Logging,输出Warn级别的日志

func Warnln

func Warnln(args ...interface{})

使用默认的Logging,输出Warn级别的日志

func WithDepth added in v0.0.6

func WithDepth(depth int)

配置默认的调用深度

func WithFields added in v0.0.6

func WithFields(keyAndValues ...interface{})

配置默认附件信息

Types

type ExitFunc added in v0.0.7

type ExitFunc func(code int)

type Formatter

type Formatter interface {
	// 将日志keyValues格式化,并输出到writer,注意writer为配置给logging的对应级别writer。
	Format(writer io.Writer, keyValues KeyValues) error
}

type Iterator

type Iterator interface {
	HasNext() bool
	Next() (string, interface{})
}

type JsonFormatter

type JsonFormatter struct {
}

func (*JsonFormatter) Format

func (f *JsonFormatter) Format(writer io.Writer, keyValues KeyValues) error

type KeyValues added in v0.0.6

type KeyValues interface {
	Add(keyAndValues ...interface{}) error
	GetAll() map[string]interface{}
	Keys() []string
	Get(key string) interface{}
	Remove(key string) error
	Len() int

	Iterator() Iterator

	Clone() KeyValues
}

func MergeKeyValues added in v0.0.6

func MergeKeyValues(keyValues ...KeyValues) (KeyValues, error)

func NewKeyValues added in v0.0.6

func NewKeyValues(keyAndValues ...interface{}) KeyValues

type Level

type Level = int32
const (
	FATAL Level = 0
	PANIC Level = 1
	ERROR Level = 2
	WARN  Level = 3
	INFO  Level = 4
	DEBUG Level = 5
)

type LevelHook

type LevelHook func(Level) Level

type LogDebug

type LogDebug interface {
	DebugEnabled() bool
	Debug(args ...interface{})
	Debugln(args ...interface{})
	Debugf(fmt string, args ...interface{})
}

type LogError

type LogError interface {
	ErrorEnabled() bool
	Error(args ...interface{})
	Errorln(args ...interface{})
	Errorf(fmt string, args ...interface{})
}

type LogFatal

type LogFatal interface {
	FatalEnabled() bool
	Fatal(args ...interface{})
	Fatalln(args ...interface{})
	Fatalf(fmt string, args ...interface{})
}

type LogInfo

type LogInfo interface {
	InfoEnabled() bool
	Info(args ...interface{})
	Infoln(args ...interface{})
	Infof(fmt string, args ...interface{})
}

type LogPanic

type LogPanic interface {
	PanicEnabled() bool
	Panic(args ...interface{})
	Panicln(args ...interface{})
	Panicf(fmt string, args ...interface{})
}

type LogWarn

type LogWarn interface {
	WarnEnabled() bool
	Warn(args ...interface{})
	Warnln(args ...interface{})
	Warnf(fmt string, args ...interface{})
}

type Logger

type Logger interface {
	// Debug级别日志接口
	LogDebug
	// Info级别日志接口
	LogInfo
	// Warn级别日志接口
	LogWarn
	// Error级别日志接口
	LogError
	// Panic级别日志接口,注意会触发Panic
	LogPanic
	// Fatal级别日志接口,注意会触发程序退出
	LogFatal

	// 附加日志名称,注意会附加父Logger的名称,格式为:父Logger名称 + '.' + name
	WithName(name string) Logger

	// 附加日志信息,注意会附加父Logger的附加信息,如果相同则会覆盖
	WithFields(keyAndValues ...interface{}) Logger

	// 配置日志的调用深度,注意会在父Logger的基础上调整深度
	WithDepth(depth int) Logger
}

Logger是xlog的日志封装工具,实现了常用的日志方法

func GetLogger

func GetLogger(o ...interface{}) Logger

通过全局默认LoggerFactory获取Logger Param:根据默认实现,o可不填,直接返回一个没有名称的Logger。 如果o有值,则只取第一个值,且当:

o为string时,使用string值作为Logger名称
o为其他类型时,取package path + type name作为Logger名称,以"."分隔,如g.x.x.t.TestStructInTest

type LoggerFactory

type LoggerFactory interface {
	// 根据参数获得Logger
	// Param:根据默认实现,o可不填,直接返回一个没有名称的Logger。
	// 如果o有值,则只取第一个值,且当:
	// 		o为string时,使用string值作为Logger名称
	//		o为其他类型时,取package path + type name作为Logger名称,以"."分隔,如g.x.x.t.TestStructInTest
	GetLogger(o ...interface{}) Logger

	// 重置Factory的Logging(线程安全)
	Reset(logging Logging) LoggerFactory

	// 获得Factory的Logging(线程安全),可用来配置Logging
	// 也可以通过wrap Logging达到控制日志级别、日志输出格式的目的
	GetLogging() Logging
}

type Logging

type Logging interface {
	// 输出format日志(线程安全)
	// Param: level日志级别, depth调用深度, keyValues附加的日志内容(多用于添加固定的日志信息), format格式化的格式, args参数
	Logf(level Level, depth int, keyValues KeyValues, format string, args ...interface{})

	// 解析并输出参数(线程安全)
	// Param: level日志级别, depth调用深度, keyValues附加的日志内容(多用于添加固定的日志信息), args参数
	Log(level Level, depth int, keyValues KeyValues, args ...interface{})

	// 解析并输出参数,末尾增加换行(线程安全)
	// Param: level日志级别, depth调用深度, keyValues附加的日志内容(多用于添加固定的日志信息), args参数
	Logln(level Level, depth int, keyValues KeyValues, args ...interface{})

	// 设置日志格式化工具(线程安全)
	SetFormatter(f Formatter)

	// 设置日志严重级别,低于该级别的将不被输出(线程安全)
	SetSeverityLevel(severityLevel Level)

	// 判断参数级别是否会输出(线程安全)
	IsEnabled(severityLevel Level) bool

	// 设置输出的Writer,注意该方法会将所有级别都配置为参数writer(线程安全)
	SetOutput(w io.Writer)

	// 设置对应日志级别的Writer(线程安全)
	SetOutputBySeverity(severityLevel Level, w io.Writer)

	// 获得对应日志级别的Writer(线程安全)
	GetOutputBySeverity(severityLevel Level) io.Writer

	// 获得一个clone的对象(线程安全)
	Clone() Logging
}

Logging是xlog的日志基础工具,向下对接日志输出Writer,向上提供日志操作接口

func DefaultLogging

func DefaultLogging() Logging

获得默认Logging

func GetLogging

func GetLogging() Logging

通过全局默认LoggerFactory的Logging

func NewLogging

func NewLogging(opts ...LoggingOpt) Logging

type LoggingOpt

type LoggingOpt func(l *logging)

type PanicFunc added in v0.0.7

type PanicFunc func(interface{})

type TextFormatter

type TextFormatter struct {
	TimeFormat func(t time.Time) string
	WithQuote  bool
	SortFunc   func([]string)
}

func (*TextFormatter) Format

func (f *TextFormatter) Format(writer io.Writer, keyValues KeyValues) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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