zeus_log

package module
v0.0.0-...-b81e666 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2023 License: MIT Imports: 8 Imported by: 0

README

zeus-log

Documentation

Index

Constants

View Source
const (
	OutputConsole = "console"
	OutputFile    = "file"
)
View Source
const (
	// RollingBySize rolls logs by file size.
	RollingBySize RollType = iota + 1
	// RollingByTime rolls logs by time.
	RollingByTime

	RollingBySizeStr = "size"
	RollingByTimeStr = "time"
)
View Source
const (
	// TimeFormatMinute is accurate to the minute.
	TimeFormatMinute = "%Y%m%d%H%M"
	// TimeFormatHour is accurate to the hour.
	TimeFormatHour = "%Y%m%d%H"
	// TimeFormatDay is accurate to the day.
	TimeFormatDay = "%Y%m%d"
	// TimeFormatMonth is accurate to the month.
	TimeFormatMonth = "%Y%m"
	// TimeFormatYear is accurate to the year.
	TimeFormatYear = "%Y"
)

Some common used time formats.

View Source
const (
	// Minute splits by the minute.
	Minute = "minute"
	// Hour splits by the hour.
	Hour = "hour"
	// Day splits by the day.
	Day = "day"
	// Month splits by the month.
	Month = "month"
	// Year splits by the year.
	Year = "year"
)

Variables

View Source
var (
	// WriteModeStrings is the map from write mod to its string representation.
	WriteModeStrings = map[WriteMode]string{
		WriteSync:  "sync",
		WriteAsync: "async",
		WriteFast:  "fast",
	}
	// WriteModeNames is the map from string to write mod.
	WriteModeNames = map[string]WriteMode{
		"sync":  WriteSync,
		"async": WriteAsync,
		"fast":  WriteFast,
	}
)
View Source
var (
	// RollTypeStrings is the map from rolling type to its string representation.
	RollTypeStrings = map[RollType]string{
		RollingBySize: RollingBySizeStr,
		RollingByTime: RollingByTimeStr,
	}
	// RollTypeNames is the map from string to rolling type.
	RollTypeNames = map[string]RollType{
		RollingBySizeStr: RollingBySize,
		RollingByTimeStr: RollingByTime,
	}
)
View Source
var (
	// LevelStrings is the map from log level to its string representation.
	LevelStrings = map[Level]string{
		LevelTrace: "trace",
		LevelDebug: "debug",
		LevelInfo:  "info",
		LevelWarn:  "warn",
		LevelError: "error",
		LevelFatal: "fatal",
		LevelPanic: "panic",
	}
	// LevelNames is the map from string to log level.
	LevelNames = map[string]Level{
		"trace": LevelTrace,
		"debug": LevelDebug,
		"info":  LevelInfo,
		"warn":  LevelWarn,
		"error": LevelError,
		"fatal": LevelFatal,
		"panic": LevelPanic,
	}
)
View Source
var (
	// DefaultConsoleWriterFactory is the default console output implementation.
	DefaultConsoleWriterFactory plugin.Factory
	// DefaultFileWriterFactory is the default file output implementation.
	DefaultFileWriterFactory plugin.Factory
)

Functions

func Debug

func Debug(args ...interface{})

Debug logs to DEBUG log. Arguments are handled in the manner of fmt.Print.

func Debugf

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

Debugf logs to DEBUG log. Arguments are handled in the manner of fmt.Printf.

func Debugln

func Debugln(args ...any)

Debugf logs to DEBUG log. Arguments are handled in the manner of fmt.Println.

func Error

func Error(args ...interface{})

Error logs to ERROR log. Arguments are handled in the manner of fmt.Print.

func Errorf

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

Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.

func Fatal

func Fatal(args ...interface{})

Fatal logs to ERROR log. Arguments are handled in the manner of fmt.Print. All Fatal logs will exit by calling os.Exit(1). Implementations may also call os.Exit() with a non-zero exit code.

func Fatalf

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

Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.

func GetRollingType

func GetRollingType(rollingType RollType) string

func GetWriter

func GetWriter(name string) plugin.Factory

GetWriter gets log output writer, returns nil if not exist.

func Info

func Info(args ...interface{})

Info logs to INFO log. Arguments are handled in the manner of fmt.Print.

func Infof

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

Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf.

func Register

func Register(name string, logger Logger)

Register registers Logger. It supports multiple Logger implementation.

func RegisterWriter

func RegisterWriter(name string, writer plugin.Factory)

RegisterWriter registers log output writer. Writer may have multiple implementations.

func SetLevel

func SetLevel(output string, level Level)

SetLevel sets log level for different output which may be "trace", "debug", "info".

func SetLogger

func SetLogger(logger Logger)

SetLogger sets the default Logger.

func Sync

func Sync()

Sync syncs all registered loggers.

func Trace

func Trace(args ...any)

Trace logs to TRACE log. Arguments are handled in the manner of fmt.Print.

func TraceContext

func TraceContext(ctx context.Context, args ...any)

TraceContext logs to TRACE log. Arguments are handled in the manner of fmt.Print.

func TraceContextf

func TraceContextf(ctx context.Context, format string, args ...any)

TraceContextf logs to TRACE log. Arguments are handled in the manner of fmt.Printf.

func TraceContextln

func TraceContextln(ctx context.Context, args ...any)

TraceContextln logs to TRACE log. Arguments are handled in the manner of fmt.Printf.

func Tracef

func Tracef(format string, args ...any)

Tracef logs to TRACE log. Arguments are handled in the manner of fmt.Printf.

func Traceln

func Traceln(args ...any)

Traceln logs to TRACE log. Arguments are handled in the manner of fmt.Printf.

func Warn

func Warn(args ...interface{})

Warn logs to WARNING log. Arguments are handled in the manner of fmt.Print.

func Warnf

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

Warnf logs to WARNING log. Arguments are handled in the manner of fmt.Printf.

Types

type Config

type Config []OutputConfig

Config is the log config. Each log may have multiple outputs.

type Field

type Field struct {
	Key   string
	Value any
}

Field is the user defined log field.

type FormatConfig

type FormatConfig struct {
	// TimeFormat specifies the time format for log output, with a default
	// value of "2006-01-02 15:04:05.000" when left empty.
	TimeFormat string `yaml:"time_format"`

	// TimeKey is the time key of log output, default as "time".
	TimeKey string `yaml:"time_key"`
	// LevelKey is the level key of log output, default as "level".
	LevelKey string `yaml:"level_key"`
	// LoggerKey is the logger key of log output, default as "logger".
	NameKey string `yaml:"name_key"`
	// CallerKey is the caller key of log output, default as "caller".
	CallerKey string `yaml:"caller_key"`
	// FunctionKey is the function key of log output, default as "", which means
	// not to print function name.
	FunctionKey string `yaml:"function_key"`
	// MessageKey is the message key of log output, default as "msg".
	MessageKey string `yaml:"message_key"`
	// StacktraceKey is the stack trace key of log output, default as "stacktrace".
	StacktraceKey string `yaml:"stacktrace_key"`
}

FormatConfig is the log format config.

type Level

type Level int
const (
	// LevelOff disables log output.
	LevelOff Level = iota
	LevelTrace
	LevelDebug
	LevelInfo
	LevelWarn
	LevelError
	LevelFatal
	LevelPanic
)

func GetLevel

func GetLevel(output string) Level

GetLevel gets log level for different output.

func (*Level) String

func (lv *Level) String() string

type Logger

type Logger interface {
	// Trace logs the provided arguments at [LevelTrace]. Spaces are added between
	// arguments when neither is a string.
	Trace(args ...any)
	// Tracef formats the message according to the format specifier and logs it at [LevelTrace].
	Tracef(format string, args ...any)
	// Traceln logs a message at [LevelTrace]. Spaces are always added between arguments.
	Traceln(args ...any)
	// Debug logs the provided arguments at [LevelDebug]. Spaces are added between
	// arguments when neither is a string.
	Debug(args ...any)
	// Debugf formats the message according to the format specifier and logs it at [LevelDebug].
	Debugf(format string, args ...any)
	// Debugln logs a message at [LevelDebug]. Spaces are always added between arguments.
	Debugln(args ...any)
	// Info logs the provided arguments at [LevelInfo]. Spaces are added between
	// arguments when neither is a string.
	Info(args ...any)
	// Infof formats the message according to the format specifier and logs it at [LevelInfo].
	Infof(format string, args ...any)
	// Infoln logs a message at [LevelInfo]. Spaces are always added between arguments.
	Infoln(args ...any)
	// Warn logs the provided arguments at [LevelWarn]. Spaces are added between
	// arguments when neither is a string.
	Warn(args ...any)
	// Warnf formats the message according to the format specifier and logs it at [LevelWarn].
	Warnf(format string, args ...any)
	// Warnln logs a message at [LevelWarn]. Spaces are always added between arguments.
	Warnln(args ...any)
	// Error logs the provided arguments at [LevelError]. Spaces are added between
	// arguments when neither is a string.
	Error(args ...any)
	// Errorf formats the message according to the format specifier and logs it at [LevelError].
	Errorf(format string, args ...any)
	// Errorln logs a message at [LevelError]. Spaces are always added between arguments.
	Errorln(args ...any)
	// Fatal logs the provided arguments at [LevelFatal]. Spaces are added between
	// arguments when neither is a string.
	Fatal(args ...any)
	// Fatalf formats the message according to the format specifier and logs it at [LevelFatal].
	Fatalf(format string, args ...any)
	// Fatalln logs a message at [LevelFatal]. Spaces are always added between arguments.
	Fatalln(args ...any)
	// Panic logs the provided arguments at [LevelPanic]. Spaces are added between
	// arguments when neither is a string.
	Panic(args ...any)
	// Panicf formats the message according to the format specifier and logs it at [LevelPanic].
	Panicf(format string, args ...any)
	// Panicln logs a message at [LevelPanic]. Spaces are always added between arguments.
	Panicln(args ...any)

	// Sync calls the underlying Core's Sync method, flushing any buffer log entries.
	// Applications should take care to call Sync before exiting.
	Sync() error

	// SetLevel sets the output log level.
	SetLevel(output string, level Level)

	// GetLevel gets the output log level.
	GetLevel(output string) Level

	// With returns a new logger with key/value paris.
	With(args ...any) Logger

	// WithFields returns a new logger with `fields` set.
	WithFields(fields ...Field) Logger
}

Logger provides an abstract definition for logging functionality.

var (
	DefaultLogger  Logger
	DefaultFactory plugin.Factory
)

func Get

func Get(name string) Logger

Get returns the Logger implementation by log name. log.Debug use DefaultLogger to print logs. You may also use log.Get("name").Debug.

func GetDefaultLogger

func GetDefaultLogger() Logger

GetDefaultLogger gets the default Logger. To configure it, set key in configuration file to default. The console output is the default value.

func With

func With(args ...any) Logger

func WithContext

func WithContext(ctx context.Context, args ...any) Logger

func WithFields

func WithFields(fields ...Field) Logger

func WithFieldsContext

func WithFieldsContext(ctx context.Context, fields ...Field) Logger

type LoggerOption

type LoggerOption func(options *LoggerOptions)

LoggerOption modifies the LoggerOptions.

type LoggerOptions

type LoggerOptions struct {
	LogLevel Level
	Pattern  string
	Writer   io.Writer
}

LoggerOptions is the log options.

type Option

type Option func(*Options)

Option modifies the options of OptionLogger.

func WithAdditionalCallerSkip

func WithAdditionalCallerSkip(skip int) Option

WithAdditionalCallerSkip adds additional caller skip.

type OptionLogger

type OptionLogger interface {
	WithOptions(opts ...Option) Logger
}

type Options

type Options struct {
	Skip int
}

type OutputConfig

type OutputConfig struct {
	// Writer is the output of log, includes console, file and remote.
	Writer       string       `yaml:"writer"`
	WriterConfig WriterConfig `yaml:"writer_config"`

	// Formatter is the format of log, such as console or json.
	Formatter    string       `yaml:"formatter"`
	FormatConfig FormatConfig `yaml:"format_config"`

	// RemoteConfig is the remote config. It's defined by business and should be
	// registered by third-party modules.
	RemoteConfig yaml.Node `yaml:"remote_config"`

	// Level controls the log level, like debug, info or error, etc...
	Level string `yaml:"level"`

	// CallerSkip controls the nesting depth of log function.
	CallerSkip int `yaml:"caller_skip"`

	// EnableColor determines if the output is colored. The default value is false.
	EnableColor bool `yaml:"enable_color"`
}

type RollType

type RollType int

RollType is the log rolling type, one of 1, 2.

func (*RollType) String

func (rt *RollType) String() string

type TimeUnit

type TimeUnit string

TimeUnit is the time unit by which files are split, one of minute/hour/day/month/year.

func (TimeUnit) Format

func (t TimeUnit) Format() string

Format returns a string preceding with `.`. Use TimeFormatDay as default.

func (TimeUnit) RotationGap

func (t TimeUnit) RotationGap() time.Duration

RotationGap returns the time.Duration for time unit. Use one day as the default.

type WriteMode

type WriteMode int

WriteMode is the log write mode, one of 1, 2, 3.

const (
	// WriteSync writes synchronously.
	WriteSync WriteMode = iota + 1
	// WriteAsync writes asynchronously.
	WriteAsync
	// WriteFast writes fast(may drop logs asynchronously).
	WriteFast
)

func GetWriteMode

func GetWriteMode(mode string) WriteMode

func (*WriteMode) String

func (wm *WriteMode) String() string

type WriterConfig

type WriterConfig struct {
	// LogPath is the log path like "/usr/local/logs" or
	// "C:\Users<YourUsername>\AppData\Local\Temp".
	LogPath string `yaml:"log_path"`
	// FileName is the file name like "app.log".
	FileName string `yaml:"file_name"`
	// WriteMode is the log write mod. sync, async, fast.(default as fast)
	WriteMode string `yaml:"write_mode"`
	// RollType is the log rolling type. Split files by size/time.(default as time)
	RollType string `yaml:"roll_type"`
	// MaxAge is the max expire times(day).
	MaxAge int `yaml:"max_age"`
	// MaxBackups is the max backup files.
	MaxBackups int `yaml:"max_backups"`
	// Compress defines whether log should be compressed.
	Compress bool `yaml:"compress"`
	// MaxSize is the max size of log file(MB).
	MaxSize int `yaml:"max_size"`

	// TimeUnit splits files by time unit, like year/month/hour/minute, default
	// as day. It takes effect only when split by time.
	TimeUnit TimeUnit `yaml:"time_unit"`
}

WriterConfig is the local file config.

Directories

Path Synopsis
internal
env
log
zap

Jump to

Keyboard shortcuts

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