log

package module
v0.4.5 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2024 License: MIT Imports: 16 Imported by: 16

README

glog

godoc license Coverage

中文

Glog is a library of asynchronous loggers, with configurable cache sizes to accommodate different high concurrency requirements. It also controls the different behaviors and logging methods of the logger through various fine-grained configurations.

Quick start

package main

import (
	"time"

	"github.com/ml444/glog"
)

func main() {
	log.Info()
	log.Debug("hello world")                            // No output by default
	log.Info("hello world")
	log.Warn("hello world")
	log.Error("hello world")
	time.Sleep(time.Millisecond * 10)
	log.Printf("%s alone could waken love!", "Love")    // No output by default
	log.Debugf("%s alone could waken love!", "Love")    // No output by default
	log.Infof("%s alone could waken love!", "Love")
	log.Warnf("%s alone could waken love!", "Love")
	log.Errorf("%s alone could waken love!", "Love")
}

Similar result: !QuickStart

By default, the logs are output to standard output and the logger level is set to Info level, so the Debug level logs in this example are not output. Different logging levels are identified by different colors.

General config

By default, logs are output to standard output, If you want to save the log in a file, you need to make the following settings (simple):

package main

import (
	"os"

	"github.com/ml444/glog"
)

func main() {
	err := InitLogger()
	if err != nil {
		log.Errorf("err: %v", err)
		os.Exit(-1)
	}
	// doing something
	log.Info("hello world")
	// doing something
}

// InitLogger simple configuration:
func InitLogger() error {
	return log.InitLog(
		log.SetLoggerName("serviceName"),   // optional
		log.SetWorkerConfigs(log.NewDefaultTextFileWorkerConfig("./logs")),
	)
}

// InitLogger2 Simple JSON format configuration:
func InitLogger2() error {
	return log.InitLog(
		log.SetLoggerName("serviceName"),   // optional
		log.SetWorkerConfigs(log.NewDefaultJsonFileWorkerConfig("./logs")),
	)
}

More detailed settings:

package main

import (
	"os"
	
	"github.com/ml444/glog"
)

func main() {
	err := InitLogger()
	if err != nil {
		log.Errorf("err: %v", err)
		os.Exit(-1)
	}
	// doing something
	log.Info("hello world")
	// doing something
}

// InitLogger detailed configuration:
func InitLogger() error {
	return log.InitLog(
		log.SetLoggerName("serviceName"),   // optional
		log.SetRecordCaller(0),        // enable record caller info
		log.SetWorkerConfigs(
			log.NewWorkerConfig(log.InfoLevel, 1024).SetFileHandlerConfig(
                log.NewDefaultFileHandlerConfig("logs").
					WithFileName("text_log").       // also specify a file name
					WithFileSize(1024*1024*1024).   // 1GB
					WithBackupCount(12).            // number of log files to keep
					WithBulkSize(1024*1024).        // batch write size to hard drive
					WithInterval(60*60).            // logs are cut on an hourly basis on a rolling basis
					WithRotatorType(log.FileRotatorTypeTimeAndSize),            
            ).SetJSONFormatterConfig(
                log.NewDefaultJSONFormatterConfig().WithBaseFormatterConfig(
                    log.NewDefaultBaseFormatterConfig().
                        WithEnableHostname().       // record the hostname of the server
                        WithEnableTimestamp().      // record timestamp
                        WithEnablePid().            // record process id
                        WithEnableIP(),             // record server ip
                ),
            ),
		),
	)
}

In the log storage selection with files, use the rolling way to keep the files, the default value to keep the latest 24 copies, you can adjust the number of backups according to your actual needs SetFileBackupCount2Logger(). And the way of scrolling can be done by scrolling by specified size (FileRotatorTypeTime), scrolling by time (FileRotatorTypeSize), scrolling by time and size common limit (FileRotatorTypeTimeAndSize). The third type of FileRotatorTypeTimeAndSize is described here in particular. It scrolls by time, but when it reaches the specified size limit, it stops logging and discards the rest of the log until the next point in time before a new file starts. This is done to protect the server's disk.

More detailed configuration can be seen in the code: config/option.go and config/config.go.

Enum of levels

To be compatible with the logging levels of the standard library, three levels of print, fatal and panic have been added.

package level

type LogLevel int8
const (
	DebugLevel LogLevel = iota + 1
	PrintLevel
	InfoLevel
	WarnLevel
	ErrorLevel
	FatalLevel
	PanicLevel
)

Multi-Worker processing features

In production environment sometimes we need to store some special logs, such as:

  1. keep the error logs to keep them for a longer period of time. To facilitate us to trace some bugs.
  2. when some high level logs need to be notified by the system alarm component, developers do not need to develop these special logging components.
  3. when some special logs need special operations, such as operation logs into the database.
  4. etc.

By enabling multiple Workers and combining it with the filter function to filter the required data and perform special operations, it makes the style and management uniform and developer-friendly.

package main

import (
	"os"

	"github.com/ml444/glog"
)

func main() {
	var err error
	err = InitLogger()
	if err != nil {
		log.Errorf("err: %v", err)
		os.Exit(-1)
	}
	// doing something
	log.Info("hello world")
	// doing something
}
func InitLogger() error {
	return log.InitLog(
		log.SetLoggerName("serviceName"),   // optional
		log.SetWorkerConfigs(
			log.NewDefaultStdoutWorkerConfig(),     // output to standard output
			log.NewDefaultJsonFileWorkerConfig("./logs").SetLevel(log.ErrorLevel),  // levels above error are output to a file
		),
	)
}

Pattern template

When using text format mode to output logs, you can control the display data and the order of each message in the log by configuring a pattern template. The default is: PatternTemplate1 = "%[LoggerName]s (%[Pid]d,%[RoutineId]d) %[DateTime]s.%[Msecs]d %[LevelName]s %[Caller]s %[Message]v" You can adjust the order of the fields and add or remove them yourself, for example: "<<%[Pid]d,%[RoutineId]d>> %[LoggerName]s %[DateTime]s %[LevelName]s %[Message]v %[Caller]s" You can configure it to your liking. The following are all the options that can be configured:

%[LoggerName]s      the name of the logger.
%[LevelName]s       the text name of the logging level.
%[ShortCaller]s     logging call (including file name, line number, function name).
%[Caller]s          logging call (including file path and name, line number, function name).
%[DateTime]s        The time of the log execution.
%[TraceId]s         the ID of the context trace.
%[IP]s              local IP address of the server.
%[HostName]s        Server host name.
%[Pid]d             Process ID.
%[RoutineId]d       Concurrent process ID.
%[Message]s         Message recorded.


%[CallerPath]s            Record the calling source file path.
%[CallerFile]s            Record the name of the source file called.
%[CallerName]s            Record the function name called.
%[CallerLine]d            Record the calling line number.

If you don't want to use %[Caller]s or %[ShortCaller]s, which is a fixed arrangement of caller information, You can use %[CallerPath]s, %[CallerFile]s, %[CallerName]s, %[CallerLine]d to customize their order. For example:

%[CallerPath]s %[CallerName]s:%[CallerLine]d
%[CallerFile]s:%[CallerLine]d

注意:

  • %[Caller]s and %[ShortCaller]s are fixedly arranged and cannot be customized. And these two fields are mutually exclusive, only one of them can be selected.
  • %[CallerPath]s, %[CallerFile]s, %[CallerName]s, %[CallerLine]d can be customized. However, the two fields %[Caller Path]s and %[Caller File]s are mutually exclusive, and only one of them can be selected.
  • %[Caller]s, %[ShortCaller]s and %[CallerPath]s, %[CallerFile]s, %[CallerName]s, %[CallerLine]d are also mutually exclusive Yes, you can only choose one of the methods.

Note: In systems with microservices, a similar TraceID is typically present to assist in stringing together the entire call chain. glog makes the logger automatically get the TraceID by configuring the hook function of TraceIDFunc.

Documentation

Index

Constants

View Source
const (
	PatternTemplateWithDefault = "%[LoggerName]s (%[Pid]d,%[RoutineId]d) %[DateTime]s %[LevelName]s %[ShortCaller]s %[Message]v"
	PatternTemplateWithSimple  = "%[LevelName]s %[DateTime]s %[ShortCaller]s %[Message]v"
	PatternTemplateWithTrace   = "<%[TradeId]s> %[LoggerName]s (%[Pid]d,%[RoutineId]d) %[DateTime]s %[LevelName]s %[ShortCaller]s %[Message]v"
)
View Source
const (
	FileRotatorSuffixFmt1 = "20060102150405"
	FileRotatorSuffixFmt2 = "2006-01-02T15-04-05"
	FileRotatorSuffixFmt3 = "2006-01-02_15-04-05"
)
View Source
const (
	FileRotatorReMatch1 = "^\\d{14}(\\.\\w+)?$"
	FileRotatorReMatch2 = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}-\\d{2}-\\d{2}(\\.\\w+)?$"
	FileRotatorReMatch3 = "^\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}-\\d{2}(\\.\\w+)?$"
)
View Source
const (
	DefaultDateTimeFormat = "01-02T15:04:05.000000" // microsecond

)

Variables

View Source
var (
	Conf = NewDefaultConfig()
)

Functions

func Debug

func Debug(args ...interface{})

func Debugf

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

func Error

func Error(args ...interface{})

func Errorf

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

func ExitHook added in v0.3.0

func ExitHook(_ int)

func Fatal

func Fatal(args ...interface{})

func Fatalf

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

func GetCallerFrame added in v0.4.4

func GetCallerFrame(callerSkip int) *runtime.Frame

func Info

func Info(args ...interface{})

func Infof

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

func InitLog

func InitLog(opts ...OptionFunc) error

func Panic

func Panic(args ...interface{})

func Panicf

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

func Print

func Print(args ...interface{})

func Printf

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

func SetLogger

func SetLogger(g ILogger)

func Stop added in v0.4.0

func Stop()

func Warn

func Warn(args ...interface{})

func Warnf

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

Types

type BaseFormatterConfig added in v0.4.0

type BaseFormatterConfig = formatter.BaseFormatterConfig

func NewDefaultBaseFormatterConfig added in v0.4.1

func NewDefaultBaseFormatterConfig() BaseFormatterConfig

type ChannelEngine added in v0.4.0

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

func NewChannelEngine added in v0.4.0

func NewChannelEngine(cfg *Config) (*ChannelEngine, error)

func (*ChannelEngine) Send added in v0.4.0

func (e *ChannelEngine) Send(entry *message.Entry)

func (*ChannelEngine) Start added in v0.4.0

func (e *ChannelEngine) Start() error

func (*ChannelEngine) Stop added in v0.4.0

func (e *ChannelEngine) Stop() (err error)

type Config

type Config struct {
	// Set the name of the Logger. If not set, the default is `glog`.
	LoggerName string

	// Set the global log level. Logs below this level will not be processed.
	// If not set, the default is `Info Level`.
	LoggerLevel Level

	// What level of logging is set here will trigger an exception to be thrown.
	// If this value is set, an exception will be thrown when an error of this level occurs.
	// You can only choose three levels: `FatalLevel`, `PanicLevel`, and `NoneLevel`.
	// The default setting is `NoneLevel`, which will not throw an exception.
	// For example, if it is set to FatalLevel, an exception will be thrown
	// when a FatalLevel error occurs.
	ThrowOnLevel Level

	// Enable recording of caller information
	EnableRecordCaller bool

	CallerSkipCount int

	// enable color rendering. Only enabled by default in the text formatter.
	EnableColorRender *bool

	// time layout string, for example: "2006-01-02 15:04:05.000"
	TimeLayout string

	// For log processing configuration, multiple Worker coroutines can be set,
	// and each Worker can set different cache sizes, log levels, formatting
	// methods, filters, and output methods.
	// Output currently defines multiple modes, such as console, file, network, etc.
	// If not set, the default is a Worker, the cache size is 1000, the log level
	// is `Info Level`, and the output mode is the console.
	// Of course, if there is no suitable output method, you can customize the Handler.
	WorkerConfigList []*WorkerConfig

	// When ThrowOnLevel is set, if a ThrowOnLevel error occurs, this function
	// will be called before exiting. The default is `os.Exit()`.
	ExitFunc func(code int)

	// If an unexpected error occurs in asynchronous logic, you can use this
	// callback function to handle the error, such as saving it to other places
	// or alerting notifications, etc. The default is to print to stderr.
	OnError func(v interface{}, err error)

	// Link tracking solutions are often used in microservices, where the
	// tracking ID is the core of the entire call link. Customize this
	// function to return the Trace ID, and then record it in the log.
	TraceIDFunc func(entry *message.Entry) string
}

func NewDefaultConfig added in v0.4.0

func NewDefaultConfig() *Config

func (*Config) Check added in v0.4.0

func (c *Config) Check()

type FileHandlerConfig added in v0.4.0

type FileHandlerConfig = handler.FileHandlerConfig

func NewDefaultFileHandlerConfig added in v0.4.1

func NewDefaultFileHandlerConfig(dir string) *FileHandlerConfig

type FormatterConfig added in v0.4.0

type FormatterConfig struct {
	Text *TextFormatterConfig
	JSON *JSONFormatterConfig
	XML  *XMLFormatterConfig
}

type HandlerConfig added in v0.4.0

type HandlerConfig struct {
	File   *FileHandlerConfig
	Stream *StreamHandlerConfig
	Syslog *SyslogHandlerConfig
}

type IEngine added in v0.4.0

type IEngine interface {
	Start() error
	Stop() error
	Send(entry *message.Entry)
}

type ILogger

type ILogger interface {
	GetLoggerName() string
	SetLoggerName(string)

	GetLevel() Level
	SetLevel(Level)

	Debug(...interface{})
	Info(...interface{})
	Warn(...interface{})
	Error(...interface{})

	Print(...interface{})
	Fatal(...interface{})
	Panic(...interface{})

	Debugf(template string, args ...interface{})
	Infof(template string, args ...interface{})
	Warnf(template string, args ...interface{})
	Errorf(template string, args ...interface{})

	Printf(template string, args ...interface{})
	Fatalf(template string, args ...interface{})
	Panicf(template string, args ...interface{})

	Stop() error
}

func GetLogger

func GetLogger() ILogger

type JSONFormatterConfig added in v0.4.0

type JSONFormatterConfig = formatter.JSONFormatterConfig

func NewDefaultJSONFormatterConfig added in v0.4.1

func NewDefaultJSONFormatterConfig() *JSONFormatterConfig

type Level added in v0.4.0

type Level = level.LogLevel
const (
	NoneLevel Level = iota
	DebugLevel
	PrintLevel
	InfoLevel
	WarnLevel
	ErrorLevel
	PanicLevel
	FatalLevel
)

type Logger

type Logger struct {
	Name         string
	Level        Level
	ThrowOnLevel Level
	ExitFunc     func(code int) // Function to exit the application, defaults to `os.Exit()`
	TraceIDFunc  func(entry *message.Entry) string
	// contains filtered or unexported fields
}

func NewLogger

func NewLogger(cfg *Config) (*Logger, error)

NewLogger returns a new ILogger

func (*Logger) Debug

func (l *Logger) Debug(args ...interface{})

func (*Logger) Debugf

func (l *Logger) Debugf(template string, args ...interface{})

func (*Logger) Error

func (l *Logger) Error(args ...interface{})

func (*Logger) Errorf

func (l *Logger) Errorf(template string, args ...interface{})

func (*Logger) Fatal

func (l *Logger) Fatal(args ...interface{})

func (*Logger) Fatalf

func (l *Logger) Fatalf(template string, args ...interface{})

func (*Logger) Fatalln

func (l *Logger) Fatalln(args ...interface{})

func (*Logger) GetLevel

func (l *Logger) GetLevel() Level

func (*Logger) GetLoggerName added in v0.2.12

func (l *Logger) GetLoggerName() string

func (*Logger) Info

func (l *Logger) Info(args ...interface{})

func (*Logger) Infof

func (l *Logger) Infof(template string, args ...interface{})

func (*Logger) Panic

func (l *Logger) Panic(args ...interface{})

func (*Logger) Panicf

func (l *Logger) Panicf(template string, args ...interface{})

func (*Logger) Panicln

func (l *Logger) Panicln(args ...interface{})

func (*Logger) Print

func (l *Logger) Print(args ...interface{})

func (*Logger) Printf

func (l *Logger) Printf(template string, args ...interface{})

func (*Logger) Println

func (l *Logger) Println(args ...interface{})

func (*Logger) SetLevel

func (l *Logger) SetLevel(lvl Level)

func (*Logger) SetLoggerName added in v0.2.12

func (l *Logger) SetLoggerName(name string)

func (*Logger) Stop

func (l *Logger) Stop() error

func (*Logger) Warn

func (l *Logger) Warn(args ...interface{})

func (*Logger) Warnf

func (l *Logger) Warnf(template string, args ...interface{})

type OptionFunc added in v0.4.0

type OptionFunc func(config *Config)

func SetColorRender added in v0.4.3

func SetColorRender(enable bool) OptionFunc

SetColorRender enable color rendering. Only enabled by default in the text formatter.

func SetExitFunc added in v0.4.0

func SetExitFunc(fn func(code int)) OptionFunc

func SetLoggerLevel added in v0.4.0

func SetLoggerLevel(lvl Level) OptionFunc

SetLoggerLevel Set the global log level. Logs below this level will not be processed.

func SetLoggerName added in v0.4.0

func SetLoggerName(name string) OptionFunc

SetLoggerName Set the name of the logger, the default is the name of the program.

func SetOnError added in v0.4.0

func SetOnError(fn func(v interface{}, err error)) OptionFunc

func SetRecordCaller added in v0.4.5

func SetRecordCaller(skip int) OptionFunc

SetRecordCaller Enable recording of caller information

func SetThrowOnLevel added in v0.4.0

func SetThrowOnLevel(lvl Level) OptionFunc

SetThrowOnLevel what level of logging is set here will trigger an exception to be thrown.

func SetTimeLayout added in v0.4.3

func SetTimeLayout(layout string) OptionFunc

SetTimeLayout time layout string, for example: "2006-01-02 15:04:05.000"

func SetTraceIDFunc added in v0.4.0

func SetTraceIDFunc(fn func(entry *message.Entry) string) OptionFunc

func SetWorkerConfigs added in v0.4.0

func SetWorkerConfigs(list ...*WorkerConfig) OptionFunc

type RotatorType added in v0.4.0

type RotatorType = handler.RotatorType
const (
	FileRotatorTypeTime        RotatorType = 1
	FileRotatorTypeSize        RotatorType = 2
	FileRotatorTypeTimeAndSize RotatorType = 3
)

type StdLogger

type StdLogger interface {
	Print(...interface{})
	Println(...interface{})
	Printf(string, ...interface{})

	Fatal(...interface{})
	Fatalln(...interface{})
	Fatalf(string, ...interface{})

	Panic(...interface{})
	Panicln(...interface{})
	Panicf(string, ...interface{})
}

type StreamHandlerConfig added in v0.4.0

type StreamHandlerConfig = handler.StreamHandlerConfig

type SyslogHandlerConfig added in v0.4.0

type SyslogHandlerConfig = handler.SyslogHandlerConfig

type TextFormatterConfig added in v0.4.0

type TextFormatterConfig = formatter.TextFormatterConfig

func NewDefaultTextFormatterConfig added in v0.4.1

func NewDefaultTextFormatterConfig() *TextFormatterConfig

type Worker added in v0.4.0

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

func (*Worker) Close added in v0.4.0

func (w *Worker) Close()

func (*Worker) Run added in v0.4.0

func (w *Worker) Run()

type WorkerConfig added in v0.4.0

type WorkerConfig struct {
	CacheSize       int
	Level           Level
	HandlerCfg      HandlerConfig
	FormatterCfg    FormatterConfig
	CustomHandler   handler.IHandler
	CustomFilter    filter.IFilter
	CustomFormatter formatter.IFormatter
}

func NewDefaultJsonFileWorkerConfig added in v0.4.1

func NewDefaultJsonFileWorkerConfig(dir string) *WorkerConfig

func NewDefaultStdoutWorkerConfig added in v0.4.1

func NewDefaultStdoutWorkerConfig() *WorkerConfig

func NewDefaultTextFileWorkerConfig added in v0.4.1

func NewDefaultTextFileWorkerConfig(dir string) *WorkerConfig

func NewWorkerConfig added in v0.4.0

func NewWorkerConfig(level Level, size int) *WorkerConfig

func (*WorkerConfig) SetCacheSize added in v0.4.2

func (w *WorkerConfig) SetCacheSize(size int) *WorkerConfig

func (*WorkerConfig) SetFileHandlerConfig added in v0.4.0

func (w *WorkerConfig) SetFileHandlerConfig(c *FileHandlerConfig) *WorkerConfig

func (*WorkerConfig) SetFilter added in v0.4.0

func (w *WorkerConfig) SetFilter(f filter.IFilter) *WorkerConfig

func (*WorkerConfig) SetFormatter added in v0.4.0

func (w *WorkerConfig) SetFormatter(f formatter.IFormatter) *WorkerConfig

func (*WorkerConfig) SetHandler added in v0.4.0

func (w *WorkerConfig) SetHandler(h handler.IHandler) *WorkerConfig

func (*WorkerConfig) SetJSONFormatterConfig added in v0.4.0

func (w *WorkerConfig) SetJSONFormatterConfig(c *JSONFormatterConfig) *WorkerConfig

func (*WorkerConfig) SetLevel added in v0.4.2

func (w *WorkerConfig) SetLevel(lvl Level) *WorkerConfig

func (*WorkerConfig) SetStreamHandlerConfig added in v0.4.0

func (w *WorkerConfig) SetStreamHandlerConfig(c *StreamHandlerConfig) *WorkerConfig

func (*WorkerConfig) SetSyslogHandlerConfig added in v0.4.0

func (w *WorkerConfig) SetSyslogHandlerConfig(c *SyslogHandlerConfig) *WorkerConfig

func (*WorkerConfig) SetTextFormatterConfig added in v0.4.0

func (w *WorkerConfig) SetTextFormatterConfig(c *TextFormatterConfig) *WorkerConfig

func (*WorkerConfig) SetXMLFormatterConfig added in v0.4.0

func (w *WorkerConfig) SetXMLFormatterConfig(c *XMLFormatterConfig) *WorkerConfig

type XMLFormatterConfig added in v0.4.0

type XMLFormatterConfig = formatter.XMLFormatterConfig

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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