log

package
v0.0.0-...-32ff608 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2023 License: Apache-2.0 Imports: 13 Imported by: 2

Documentation

Overview

Package log provides a log for the framework and applications.

Index

Constants

View Source
const (
	OutputConsole = "console"
	OutputFile    = "file"
)

output name, default support console and file.

View Source
const (
	// WriteSync writes synchronously.
	WriteSync = 1
	// WriteAsync writes asynchronously.
	WriteAsync = 2
	// WriteFast writes fast(may drop logs asynchronously).
	WriteFast = 3
)
View Source
const (
	// RollBySize rolls logs by file size.
	RollBySize = "size"
	// RollByTime rolls logs by time.
	RollByTime = "time"
)

By which log rolls.

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"
)
View Source
const (
	ConsoleZapCore = "console"
	FileZapCore    = "file"
)

Some ZapCore constants.

Variables

View Source
var (
	// DefaultConsoleWriterFactory is the default console output implementation.
	DefaultConsoleWriterFactory = &ConsoleWriterFactory{}
	// DefaultFileWriterFactory is the default file output implementation.
	DefaultFileWriterFactory = &FileWriterFactory{}
)
View Source
var LevelNames = map[string]Level{
	"trace": LevelTrace,
	"debug": LevelDebug,
	"info":  LevelInfo,
	"warn":  LevelWarn,
	"error": LevelError,
	"fatal": LevelFatal,
}

LevelNames is the map from string to log level.

View Source
var LevelStrings = map[Level]string{
	LevelTrace: "trace",
	LevelDebug: "debug",
	LevelInfo:  "info",
	LevelWarn:  "warn",
	LevelError: "error",
	LevelFatal: "fatal",
}

LevelStrings is the map from log level to its string representation.

View Source
var Levels = map[string]zapcore.Level{
	"":      zapcore.DebugLevel,
	"debug": zapcore.DebugLevel,
	"info":  zapcore.InfoLevel,
	"warn":  zapcore.WarnLevel,
	"error": zapcore.ErrorLevel,
	"fatal": zapcore.FatalLevel,
}

Levels is the map from string to zapcore.Level.

Functions

func CustomTimeFormat

func CustomTimeFormat(t time.Time, format string) string

CustomTimeFormat customize time format.

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 DefaultTimeFormat

func DefaultTimeFormat(t time.Time) []byte

DefaultTimeFormat returns the default time format.

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 GetLogEncoderKey

func GetLogEncoderKey(defKey, key string) string

GetLogEncoderKey gets user defined log output name, uses defKey if empty.

func GetWriter

func GetWriter(name string) plugin.Plugin

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 NewTimeEncoder

func NewTimeEncoder(format string) zapcore.TimeEncoder

NewTimeEncoder creates a time format encoder.

func RedirectStdLog

func RedirectStdLog(logger Logger) (func(), error)

RedirectStdLog redirects std log as log level INFO. After redirection, log flag is zero, the prefix is empty. The returned function may be used to recover log flag and prefix, and redirect output to os.Stderr.

func RedirectStdLogAt

func RedirectStdLogAt(logger Logger, level zapcore.Level) (func(), error)

RedirectStdLogAt redirects std log with a specific level. After redirection, log flag is zero, the prefix is empty. The returned function may be used to recover log flag and prefix, and redirect output to os.Stderr.

func Register

func Register(name string, logger Logger)

Register registers Logger. It supports multiple Logger implementation.

func RegisterWriter

func RegisterWriter(name string, writer plugin.Plugin)

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 "0", "1" or "2".

func SetLogger

func SetLogger(logger Logger)

SetLogger sets the default Logger.

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 ConsoleWriterFactory

type ConsoleWriterFactory struct {
}

ConsoleWriterFactory is the console writer instance.

func (*ConsoleWriterFactory) Setup

func (f *ConsoleWriterFactory) Setup(name string, dec plugin.Decoder) error

Setup starts, loads and registers console output writer.

func (*ConsoleWriterFactory) Type

func (f *ConsoleWriterFactory) Type() string

Type returns log file type.

type Decoder

type Decoder struct {
	OutputConfig *OutputConfig
	Core         zapcore.Core
	ZapLevel     zap.AtomicLevel
}

Decoder decodes the log.

func (*Decoder) Decode

func (d *Decoder) Decode(cfg interface{}) error

Decode decodes writer configuration, copy one.

type Factory

type Factory struct {
}

Factory is the log plugin factory. When server start, the configuration is feed to Factory to generate a log instance.

func (*Factory) Setup

func (f *Factory) Setup(name string, dec plugin.Decoder) error

Setup starts, load and register logs.

func (*Factory) Type

func (f *Factory) Type() string

Type returns the log plugin type.

type Field

type Field struct {
	Key   string
	Value interface{}
}

Field is the user defined log field.

type FileWriterFactory

type FileWriterFactory struct {
}

FileWriterFactory is the file writer instance Factory.

func (*FileWriterFactory) Setup

func (f *FileWriterFactory) Setup(name string, dec plugin.Decoder) error

Setup starts, loads and register file output writer.

func (*FileWriterFactory) Type

func (f *FileWriterFactory) Type() string

Type returns log file type.

type FormatConfig

type FormatConfig struct {
	// TimeFmt is the time format of log output, default as "2006-01-02 15:04:05.000" on empty.
	TimeFmt string `yaml:"time_fmt"`

	// TimeKey is the time key of log output, default as "T".
	TimeKey string `yaml:"time_key"`
	// LevelKey is the level key of log output, default as "L".
	LevelKey string `yaml:"level_key"`
	// NameKey is the name key of log output, default as "N".
	NameKey string `yaml:"name_key"`
	// CallerKey is the caller key of log output, default as "C".
	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 "M".
	MessageKey string `yaml:"message_key"`
	// StackTraceKey is the stack trace key of log output, default as "S".
	StacktraceKey string `yaml:"stacktrace_key"`
}

FormatConfig is the log format config.

type Level

type Level int

Level is the log level.

const (
	LevelNil Level = iota
	LevelTrace
	LevelDebug
	LevelInfo
	LevelWarn
	LevelError
	LevelFatal
)

Enums log level constants.

func GetLevel

func GetLevel(output string) Level

GetLevel gets log level for different output.

func (*Level) String

func (lv *Level) String() string

String turns the LogLevel to string.

type Logger

type Logger interface {
	// Trace logs to TRACE log. Arguments are handled in the manner of fmt.Print.
	Trace(args ...interface{})
	// Tracef logs to TRACE log. Arguments are handled in the manner of fmt.Printf.
	Tracef(format string, args ...interface{})
	// Debug logs to DEBUG log. Arguments are handled in the manner of fmt.Print.
	Debug(args ...interface{})
	// Debugf logs to DEBUG log. Arguments are handled in the manner of fmt.Printf.
	Debugf(format string, args ...interface{})
	// Info logs to INFO log. Arguments are handled in the manner of fmt.Print.
	Info(args ...interface{})
	// Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf.
	Infof(format string, args ...interface{})
	// Warn logs to WARNING log. Arguments are handled in the manner of fmt.Print.
	Warn(args ...interface{})
	// Warnf logs to WARNING log. Arguments are handled in the manner of fmt.Printf.
	Warnf(format string, args ...interface{})
	// Error logs to ERROR log. Arguments are handled in the manner of fmt.Print.
	Error(args ...interface{})
	// Errorf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.
	Errorf(format string, 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.
	Fatal(args ...interface{})
	// Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf.
	Fatalf(format string, args ...interface{})

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

	// SetLevel set the output log level.
	SetLevel(output string, level Level)
	// GetLevel get the output log level.
	GetLevel(output string) Level
	// WithFields set some user defined data to logs, such as uid, imei, etc.
	// Fields must be paired.
	// Deprecated: use With instead.
	WithFields(fields ...string) Logger
	// With add user defined fields to Logger. Fields support multiple values.
	With(fields ...Field) Logger
}

Logger is the underlying logging work for server.

var (
	// DefaultLogger the default Logger. The initial output is console. When frame start, it is
	// over write by configuration.
	DefaultLogger Logger
	// DefaultLogFactory is the default log loader. Users may replace it with their own
	// implementation.
	DefaultLogFactory = &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 NewZapLog

func NewZapLog(c Config) Logger

NewZapLog creates a workflow default Logger from zap whose caller skip is set to 2.

func NewZapLogWithCallerSkip

func NewZapLogWithCallerSkip(c Config, callerSkip int) Logger

NewZapLogWithCallerSkip creates a workflow default Logger from zap.

func With

func With(fields ...Field) Logger

With adds user defined fields to Logger. Field support multiple values.

type LoggerOption

type LoggerOption func(*LoggerOptions)

LoggerOption modifies the LoggerOptions.

type LoggerOptions

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

LoggerOptions is the log options.

type OutputConfig

type OutputConfig struct {
	// Writer is the output of log, such as console or file.
	Writer      string
	WriteConfig WriteConfig `yaml:"writer_config"`

	// Formatter is the format of log, such as console or json.
	Formatter    string
	FormatConfig FormatConfig `yaml:"formatter_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.
	Level string

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

OutputConfig is the output config, includes console, file and remote.

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 WriteConfig

type WriteConfig struct {
	// LogPath is the log path
	LogPath string `yaml:"log_path"`
	// Filename is the file name.
	Filename string `yaml:"filename"`
	// WriteMode is the log write mod. 1: sync, 2: async, 3: fast(maybe dropped).
	WriteMode int `yaml:"write_mode"`
	// RollType is the log rolling type. Split files by size/time, default by size.
	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 day.
	// It takes effect only when split by time.
	TimeUnit TimeUnit `yaml:"time_unit"`
}

WriteConfig is the local file config.

type WriteMode

type WriteMode int

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

type ZapLogWrapper

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

ZapLogWrapper delegates zapLogger which was introduced in this By ZapLogWrapper proxy, we can add a layer to the debug series function calls, so that the caller information can be set correctly.

func (*ZapLogWrapper) Debug

func (z *ZapLogWrapper) Debug(args ...interface{})

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

func (*ZapLogWrapper) Debugf

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

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

func (*ZapLogWrapper) Error

func (z *ZapLogWrapper) Error(args ...interface{})

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

func (*ZapLogWrapper) Errorf

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

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

func (*ZapLogWrapper) Fatal

func (z *ZapLogWrapper) Fatal(args ...interface{})

Fatal logs to FATAL log. Arguments are handled in the manner of fmt.Print.

func (*ZapLogWrapper) Fatalf

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

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

func (*ZapLogWrapper) GetLevel

func (z *ZapLogWrapper) GetLevel(output string) Level

GetLevel gets output log level.

func (*ZapLogWrapper) GetLogger

func (z *ZapLogWrapper) GetLogger() Logger

GetLogger returns interval zapLog.

func (*ZapLogWrapper) Info

func (z *ZapLogWrapper) Info(args ...interface{})

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

func (*ZapLogWrapper) Infof

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

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

func (*ZapLogWrapper) SetLevel

func (z *ZapLogWrapper) SetLevel(output string, level Level)

SetLevel set output log level.

func (*ZapLogWrapper) Sync

func (z *ZapLogWrapper) Sync() error

Sync calls the zap logger's Sync method, and flushes any buffered log entries. Applications should take care to call Sync before exiting.

func (*ZapLogWrapper) Trace

func (z *ZapLogWrapper) Trace(args ...interface{})

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

func (*ZapLogWrapper) Tracef

func (z *ZapLogWrapper) Tracef(format string, args ...interface{})

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

func (*ZapLogWrapper) Warn

func (z *ZapLogWrapper) Warn(args ...interface{})

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

func (*ZapLogWrapper) Warnf

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

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

func (*ZapLogWrapper) With

func (z *ZapLogWrapper) With(fields ...Field) Logger

With add user defined fields to Logger. Fields support multiple values.

func (*ZapLogWrapper) WithFields

func (z *ZapLogWrapper) WithFields(fields ...string) Logger

WithFields set some user defined data to logs, such as uid, imei, etc. Use this function at the beginning of each request. The returned new Logger should be used to print logs. Fields must be paired. Deprecated: use With instead.

Directories

Path Synopsis
Package rollwriter provides a high performance rolling file log.
Package rollwriter provides a high performance rolling file log.

Jump to

Keyboard shortcuts

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