logit

package module
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2020 License: Apache-2.0 Imports: 9 Imported by: 20

README

📝 logit

License

logit 是一个简单易用并且是基于级别控制的日志库,可以应用于所有的 GoLang 应用程序中。

Read me in English.

🥇 功能特性
  • 独特的日志输出模块设计,使用 wrapper 和 handler 装载特定的模块,实现扩展功能
  • 支持日志级别控制,一共有四个日志级别,分别是 debug,info,warn 和 error。
  • 支持日志记录函数,使用回调的形式获取日志内容,对长日志内容的组织逻辑会更清晰
  • 支持开启或者关闭日志功能,线上环境可以关闭或调高日志级别
  • 支持记录日志到文件中,并且可以自定义日志文件名
  • 支持按照时间间隔进行自动划分日志文件,比如每一天划分一个日志文件
  • 支持按照文件大小进行自动划分日志文件,比如每 64 MB 划分一个日志文件
  • 增加日志处理器模块,支持用户自定义日志处理逻辑,具有很高的扩展能力
  • 支持不输出文件信息,避免 runtime.Caller 方法的调用,具有很高的性能
  • 支持调整时间格式化输出,让用户自定义时间输出的格式

历史版本的特性请查看 HISTORY.md。未来版本的新特性和计划请查看 FUTURE.md

🚀 安装方式

唯一需要的依赖就是 Golang 运行环境.

Go modules

$ go get -u github.com/FishGoddess/logit

您也可以直接编辑 go.mod 文件,然后执行 go build

module your_project_name

go 1.14

require (
    github.com/FishGoddess/logit v0.0.9
)

Go path

$ go get -u github.com/FishGoddess/logit

logit 没有任何其他额外的依赖,纯使用 Golang 标准库 完成。

package main

import (
    "math/rand"
    "strconv"
    "time"
    
    "github.com/FishGoddess/logit"
)

func main() {
    
    // Log as you want.
    logit.Debug("I am a debug message! But I will not be logged in default level!")
    logit.Info("I am an info message!")
    logit.Warn("I am a warn message!")
    logit.Error("I am an error message!")
    
    // Change logger level.
    logit.ChangeLevelTo(logit.DebugLevel)

    // If you want to output log with file info, try this:
    logit.EnableFileInfo()
    logit.Info("Show file info!")

    // If you have a long log and it is made of many variables, try this:
    // The msg is the return value of msgGenerator.
    logit.DebugFunction(func() string {
        // Use time as the source of random number generator.
        r := rand.New(rand.NewSource(time.Now().Unix()))
        return "debug rand int: " + strconv.Itoa(r.Intn(100))
    })
}
📖 参考案例

更多使用案例请查看 _examples 目录。

🔥 性能测试
$ go test -v ./_examples/benchmarks_test.go -bench=. -benchtime=1s

测试文件:_examples/benchmarks_test.go

测试 单位时间内运行次数 (越大越好) 每个操作消耗时间 (越小越好) 功能性 扩展性
logit   572947 1939 ns/op 强大
logrus   158262 7751 ns/op 正常 正常
Golog   751064 1614 ns/op 正常 正常
Golang log 1000000 1019 ns/op 一般

测试环境:I7-6700HQ CPU @ 2.6 GHZ,16 GB RAM

注意:

1. 输出文件信息会有运行时操作(runtime.Caller 方法),非常影响性能, 但是这个功能感觉还是比较实用的,尤其是在查找错误的时候,所以我们还是加了这个功能! 如果你更在乎性能,那我们也提供了一个选项可以关闭文件信息的查询!

2. v0.0.7 及以前版本的日志输出使用了 fmt 包的一些方法,经过性能检测发现这些方法存在大量使用反射的 行为,主要体现在对参数 v interface{} 进行类型检测的逻辑上,而日志输出都是字符串,这一个 判断是可以省略的,可以减少很多运行时操作时间!v0.0.8 版本开始使用了更有效率的输出方式!

3. 经过对 v0.0.8 版本的性能检测,发现时间格式化操作消耗了接近一般的处理时间, 主要体现在 time.Time.AppendFormat 的调用上。目前正在思考优化方案,或许会在之后的版本中解决!

👥 贡献者

如果您觉得 logit 缺少您需要的功能,请不要犹豫,马上参与进来,发起一个 issue

📦 使用 logit 的项目
项目 作者 描述

Documentation

Overview

Package logit provides an easy way to use foundation for your logging operations.

1. The basic usage:

// Log messages with four levels.
// Notice that the default level is info, so first line of debug message
// will not be logged! If you want to change level, see logit.ChangeLevelTo
logit.Debug("I am a debug message! But I will not be logged in default level!")
logit.Info("I am an info message!")
logit.Warn("I am a warn message!")
logit.Error("I am an error message!")

// Also, you can create a new independent Logger to use. See logit.NewLogger.

// If you want to output log with file info, try this:
logit.EnableFileInfo()
logit.Info("Show file info!")

2. logger:

// NewStdoutLogger creates a new Logger holder to standard output, generally a terminal or a console.
logger := logit.NewStdoutLogger(logit.DebugLevel)

// Then you will be easy to log!
logger.Debug("this is a debug message!")
logger.Info("this is a info message!")
logger.Warn("this is a warn message!")
logger.Error("this is a error message!")

// NewLogger creates a new Logger holder.
// The first parameter "os.Stdout" is a writer for logging.
// As you know, file also can be written, just replace "os.Stdout" with your file!
// The second parameter "logit.DebugLevel" is the level of this Logger.
logger = logit.NewLogger(os.Stdout, logit.DebugLevel)

// If you want format your time, try this:
logger.SetFormatOfTime("2006/01/02 15:04:05")
logger.Info("What time is it now?")

// If you want to output log with file info, try this:
logger.EnableFileInfo()
logger.Info("What file is it? Which line?")
logger.DisableFileInfo()

// If you have a long log and it is made of many variables, try this:
// The msg is the return value of msgGenerator.
logger.DebugFunction(func() string {
    // Use time as the source of random number generator.
    r := rand.New(rand.NewSource(time.Now().Unix()))
    return "debug rand int: " + strconv.Itoa(r.Intn(100))
})

3. enable or disable:

// Every new Logger is running.
logger := logit.NewLogger(os.Stdout, logit.DebugLevel)
logger.Info("I am running!")

// Shutdown the Logger.
// So the info message next line will not be logged!
logger.Disable()
logger.Info("I will not be logged!")

// Enable the Logger.
// The info message next line will be logged again!
logger.Enable()
logger.Info("I am running again!")

4. change logger level:

logit.Debug("Default logger level is info, so debug message will not be logged!")

// Change logger level to debug level.
logit.ChangeLevelTo(logit.DebugLevel)

logit.Debug("Now debug message will be logged!")

5. log to file:

// NewFileLogger creates a new logger which logs to file.
// It just need a file path like "D:/test.log" and a logger level.
logger := logit.NewFileLogger("D:/test.log", logit.DebugLevel)
logger.Info("我是 info 日志!")

// NewDurationRollingLogger creates a duration rolling logger with given duration.
// You should appoint a directory to store all log files generated in this time.
// Notice that duration must not less than minDuration (generally time.Second), see wrapper.minDuration.
// Also, default filename of log file is like "20200304-145246-45.log", see wrapper.NewFilename.
// If you want to appoint another filename, check this and do it by this way.
// See wrapper.NewDurationRollingFile (it is an implement of io.writer).
logger = logit.NewDurationRollingLogger("D:/", time.Second, logit.DebugLevel)
logger.Info("Rolling!!!")

// NewDayRollingLogger creates a day rolling logger.
// You should appoint a directory to store all log files generated in this time.
// See logit.NewDurationRollingLogger.
logger = logit.NewDayRollingLogger("D:/", logit.DebugLevel)
logger.Info("Today is Friday!!!")

// NewSizeRollingLogger creates a file size rolling logger with given limitedSize.
// You should appoint a directory to store all log files generated in this time.
// Notice that limitedSize must not less than minLimitedSize (generally 64 KB), see wrapper.minLimitedSize.
// Check wrapper.KB, wrapper.MB, wrapper.GB to know what unit you gonna to use.
// Also, default filename of log file is like "20200304-145246-45.log", see nextFilename.
// If you want to appoint another filename, check this and do it by this way.
// See wrapper.NewSizeRollingFile (it is an implement of io.writer).
logger = logit.NewSizeRollingLogger("D:/", 64*wrapper.KB, logit.DebugLevel)
logger.Info("file size???")

// NewDayRollingLogger creates a file size rolling logger.
// You should appoint a directory to store all log files generated in this time.
// Default means limitedSize is 64 MB. See NewSizeRollingLogger.
logger = logit.NewDefaultSizeRollingLogger("D:/", logit.DebugLevel)
logger.Info("64 MB rolling!!!")

6. logger handler:

// Create a logger holder.
// Default handler is logit.DefaultLoggerHandler.
logger := logit.NewLogger(os.Stdout, logit.InfoLevel)
logger.Info("before logging...")

// Customize your own handler.
handlers1 := func(logger *logit.Logger, level logit.LoggerLevel, now time.Time, msg string) bool {
    logger.Writer().Write([]byte("handlers1: " + msg + "\n"))
    return true
}

handlers2 := func(logger *logit.Logger, level logit.LoggerLevel, now time.Time, msg string) bool {
    logger.Writer().Write([]byte("handlers2: " + msg + "\n"))
    return true
}

// Add handlers to logger.
// There are three handlers in logger because logger has a default handler inside after creating.
// See logit.DefaultLoggerHandler.
logger.AddHandlers(handlers1, handlers2)
fmt.Println("fmt =========================================")
logger.Info("after adding handlers...")

// Set handlers to logger.
// There are two handlers in logger because the default handler inside was removed.
logger.SetHandlers(handlers1, handlers2)
fmt.Println("fmt =========================================")
logger.Info("after setting handlers...")

Index

Constants

View Source
const DefaultFormatOfTime = "2006-01-02 15:04:05"

DefaultFormatOfTime is the default format for formatting time.

View Source
const PrefixOfLogFile = ".log"

PrefixOfLogFile is the prefix of log file.

View Source
const Version = "0.0.9"

Version is the version string representation of the "logit" package.

Variables

This section is empty.

Functions

func AddHandlers added in v0.0.7

func AddHandlers(handlers ...LoggerHandler)

AddHandlers adds more handlers to logit, and all handlers added before will be retained. If you want to remove all handlers, try logit.SetHandlers(). See logit.DefaultLoggerHandler.

func ChangeLevelTo added in v0.0.2

func ChangeLevelTo(level LoggerLevel)

ChangeLevelTo will change the level of logit to newLevel.

func Debug added in v0.0.2

func Debug(msg string)

Debug will output msg as a debug message.

func DebugFunction added in v0.0.9

func DebugFunction(msgGenerator func() string)

DebugFunction will output msg as a debug message. The msg is the return value of msgGenerator. This is a better way to output a long log made of many variables.

func DefaultLoggerHandler added in v0.0.7

func DefaultLoggerHandler(logger *Logger, level LoggerLevel, now time.Time, msg string) bool

DefaultLoggerHandler is the default handler in logit. The log handled by this handler will be like "Info [2020-03-06 16:10:44] msg". If you want to customize, just code your own handler, then replace it!

func Disable added in v0.0.2

func Disable()

Disable sets logit on shutdown status.

func DisableFileInfo added in v0.0.7

func DisableFileInfo()

DisableFileInfo means every log will not contain file info like line number. If you want file info again, try logit.EnableFileInfo().

func Enable added in v0.0.2

func Enable()

Enable sets logit on running status.

func EnableFileInfo added in v0.0.7

func EnableFileInfo()

EnableFileInfo means every log will contain file info like line number. However, you should know that this is expensive in time. So be sure you really need it or keep it disabled.

func Error added in v0.0.2

func Error(msg string)

Error will output msg as an error message.

func ErrorFunction added in v0.0.9

func ErrorFunction(messageGenerator func() string)

ErrorFunction will output msg as an error message. The msg is the return value of messageGenerator. This is a better way to output a long log made of many variables.

func Info added in v0.0.2

func Info(msg string)

Info will output msg as an info message.

func InfoFunction added in v0.0.9

func InfoFunction(msgGenerator func() string)

InfoFunction will output msg as an info message. The msg is the return value of msgGenerator. This is a better way to output a long log made of many variables.

func PrefixOf added in v0.0.9

func PrefixOf(level LoggerLevel) string

prefixOf gets the prefix of this level.

func SetFormatOfTime added in v0.0.7

func SetFormatOfTime(formatOfTime string)

SetFormatOfTime sets format of time as you want. Default is "2006-01-02 15:04:05", see logit.DefaultFormatOfTime.

func SetHandlers added in v0.0.7

func SetHandlers(handlers ...LoggerHandler) bool

SetHandlers replaces logit's handlers with handlers, all handlers added before will be removed. If you want to add more handlers rather than replace them, try logit.AddHandlers(). Notice that at least one handler should be added, so if len(handlers) < 1, it returns false which means setting failed. Return true if setting is successful. See logit.DefaultLoggerHandler.

func Warn added in v0.0.4

func Warn(msg string)

Warn will output msg as a warn message.

func WarnFunction added in v0.0.9

func WarnFunction(msgGenerator func() string)

WarnFunction will output msg as a warn message. The msg is the return value of messageGenerator. This is a better way to output a long log made of many variables.

Types

type Logger

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

Logger is a struct to log.

func NewDayRollingLogger added in v0.0.6

func NewDayRollingLogger(directory string, level LoggerLevel) *Logger

NewDayRollingLogger creates a day rolling logger. You should appoint a directory to store all log files generated in this time. See NewDurationRollingLogger.

func NewDefaultSizeRollingLogger added in v0.0.6

func NewDefaultSizeRollingLogger(directory string, level LoggerLevel) *Logger

NewDayRollingLogger creates a file size rolling logger. You should appoint a directory to store all log files generated in this time. Default means limitedSize is 64 MB. See NewSizeRollingLogger.

func NewDurationRollingLogger added in v0.0.5

func NewDurationRollingLogger(directory string, duration time.Duration, level LoggerLevel) *Logger

NewDurationRollingLogger creates a duration rolling logger with given duration. You should appoint a directory to store all log files generated in this time. Notice that duration must not less than minDuration (generally one second), see wrapper.minDuration. Also, default filename of log file is like "20200304-145246-45.log", see nextFilename. If you want to appoint another filename, check this and do it by this way. See wrapper.NewDurationRollingFile (it is an implement of io.writer).

func NewFileLogger added in v0.0.5

func NewFileLogger(logFile string, level LoggerLevel) *Logger

NewFileLogger returns a Logger holder which log to a file with given logFile and level.

func NewLogger

func NewLogger(writer io.Writer, level LoggerLevel) *Logger

NewLogger creates one Logger with given out and level. The first parameter writer is the writer for logging. The second parameter level is the level of this Logger. It returns a new running Logger holder.

func NewLoggerWithHandlers added in v0.0.7

func NewLoggerWithHandlers(writer io.Writer, level LoggerLevel, handlers ...LoggerHandler) *Logger

NewLoggerWithHandlers creates one Logger with given out and level and handlers. The first parameter writer is the writer for logging. The second parameter level is the level of this Logger. The third parameter handlers is all logger handlers for handling each log. It returns a new running Logger holder.

func NewSizeRollingLogger added in v0.0.6

func NewSizeRollingLogger(directory string, limitedSize int64, level LoggerLevel) *Logger

NewSizeRollingLogger creates a file size rolling logger with given limitedSize. You should appoint a directory to store all log files generated in this time. Notice that limitedSize must not less than minLimitedSize (generally 64 KB), see wrapper.minLimitedSize. Check wrapper.KB, wrapper.MB, wrapper.GB to know what unit you gonna to use. Also, default filename of log file is like "20200304-145246-45.log", see nextFilename. If you want to appoint another filename, check this and do it by this way. See wrapper.NewSizeRollingFile (it is an implement of io.writer).

func NewStdoutLogger added in v0.0.2

func NewStdoutLogger(level LoggerLevel) *Logger

NewStdoutLogger returns a Logger holder with given logger level.

func (*Logger) AddHandlers added in v0.0.7

func (l *Logger) AddHandlers(handlers ...LoggerHandler)

AddHandlers adds more handlers to l, and all handlers added before will be retained. If you want to remove all handlers, try l.SetHandlers(). See logit.DefaultLoggerHandler.

func (*Logger) ChangeLevelTo added in v0.0.2

func (l *Logger) ChangeLevelTo(newLevel LoggerLevel)

ChangeLevelTo will change the level of current Logger to newLevel.

func (*Logger) Debug

func (l *Logger) Debug(msg string)

Debug will output msg as a debug message.

func (*Logger) DebugFunction added in v0.0.9

func (l *Logger) DebugFunction(msgGenerator func() string)

DebugFunction will output msg as a debug message. The msg is the return value of msgGenerator. This is a better way to output a long log made of many variables.

func (*Logger) Disable

func (l *Logger) Disable()

Disable sets l on shutdown status.

func (*Logger) DisableFileInfo added in v0.0.7

func (l *Logger) DisableFileInfo()

DisableFileInfo means every log will not contain file info like line number. If you want file info again, try l.EnableFileInfo().

func (*Logger) Enable

func (l *Logger) Enable()

Enable sets l on running status.

func (*Logger) EnableFileInfo added in v0.0.7

func (l *Logger) EnableFileInfo()

EnableFileInfo means every log will contain file info like line number. However, you should know that this is expensive in time. So be sure you really need it or keep it disabled.

func (*Logger) Error

func (l *Logger) Error(msg string)

Error will output msg as an error message.

func (*Logger) ErrorFunction added in v0.0.9

func (l *Logger) ErrorFunction(messageGenerator func() string)

ErrorFunction will output msg as an error message. The msg is the return value of messageGenerator. This is a better way to output a long log made of many variables.

func (*Logger) Info

func (l *Logger) Info(msg string)

Info will output msg as an info message.

func (*Logger) InfoFunction added in v0.0.9

func (l *Logger) InfoFunction(msgGenerator func() string)

InfoFunction will output msg as an info message. The msg is the return value of msgGenerator. This is a better way to output a long log made of many variables.

func (*Logger) SetFormatOfTime added in v0.0.7

func (l *Logger) SetFormatOfTime(formatOfTime string)

SetFormatOfTime sets format of time as you want. Default is "2006-01-02 15:04:05", see DefaultFormatOfTime.

func (*Logger) SetHandlers added in v0.0.7

func (l *Logger) SetHandlers(handlers ...LoggerHandler) bool

SetHandlers replaces l.handlers with handlers, all handlers added before will be removed. If you want to add more handlers rather than replace them, try l.AddHandlers. Notice that at least one handler should be added, so if len(handlers) < 1, it returns false which means setting failed. Return true if setting is successful. See logit.DefaultLoggerHandler.

func (*Logger) Warn added in v0.0.4

func (l *Logger) Warn(msg string)

Warn will output msg as a warn message.

func (*Logger) WarnFunction added in v0.0.9

func (l *Logger) WarnFunction(msgGenerator func() string)

WarnFunction will output msg as a warn message. The msg is the return value of messageGenerator. This is a better way to output a long log made of many variables.

func (*Logger) Writer added in v0.0.7

func (l *Logger) Writer() io.Writer

Writer returns the writer of l.

type LoggerHandler added in v0.0.7

type LoggerHandler func(logger *Logger, level LoggerLevel, now time.Time, msg string) bool

LoggerHandler is a struct representation of log handler. Every log will handle by this handler, and you can customize your own handler to handle logs in your way. The return value is meaningful, false means next handler will not be handled, only true will go on handling process. Notice that if one handler returns false, then all handlers after it will not use anymore.

type LoggerLevel added in v0.0.4

type LoggerLevel uint8

LoggerLevel is the type representation of the level.

const (
	DebugLevel LoggerLevel = iota
	InfoLevel
	WarnLevel
	ErrorLevel
)

Constants about logger level.

func (LoggerLevel) String added in v0.0.9

func (ll LoggerLevel) String() string

The String method is used to print values passed as an operand to any format that accepts a string or to an printer without format such as Print.

Directories

Path Synopsis
Package wrapper provides some writers to extend your Logger.
Package wrapper provides some writers to extend your Logger.

Jump to

Keyboard shortcuts

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