log package - github.com/expgo/log - Go Packages

log

package module
v0.0.0-...-6051c6e Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2025 License: MIT Imports: 18 Imported by: 9

README

config file controlled logging system for golang

Build a logging system that can be controlled by a config file.

config file

logging:                 # default logging section name
  level:
    "*": debug           # all loggers will be set to debug level
    "*MyLog": warn       # only MyLog will be set to warn level
  console:
    stream: stdout       # console output stream, will be `no`, `stdout` or `stderr`, default is `stdout`. `no` means no console output.
    encoder: text        # encoder type, will be `text` or `json`, default is `text`.
  file:
    filename: log/a.log  # log file name, Backup log files will be retained in the same directory
    encoder: text        # log file encoder
    maxsize: 100         # log file max size, the maximum size in megabytes of the log file before it gets rotated, It defaults to 100 megabytes.
    maxage: 30           # log file max age, the maximum number of days to retain old log files based on the timestamp encoded in their filename. Default is 30 days.
    maxbackups: 30       # log file max backups, the maximum number of old log files to retain. Default is 30.
    compress: true       # determines if the rotated log files should be compressed using gzip. Default is true.
    encoder: text        # log file encoder, will be `text` or `json`, default is `text`.
  withcaller: true       # configures the Logger to annotate each message with the filename, line number, and function name of caller. Default is true.
  withlogname: short     # If log the file type name. will be `short`, `full` or `none`. Default is `short`. `short` means the file name without the directory path. `full` means the file name with the directory path. `none` means no file name.

log1:                    # custom logging section name       
  level:
    "*MyLog1": debug
  console:
    stream: stdout
    encoder: json
  file:
    filename: log/b.log

how to use custom level name

  • If no config file, there will be a default "*": info under the level section.
  • The level of the key is the structure full type with path. For example, a struct MyLog github.com/mind/log/v2/logger.go file, the full key will be "github.com/mind/log/v2.MyLog": debug.

all the level name

  • debug
  • info
  • warn
  • error
  • dpanic
  • panic
  • fatal
  • invalid

use custom logging section name

If use ag factory to autowire create the logging instance, you can use the value attribute to specify the custom logging section name.

type MyLog1 struct {
	log log.Logger `new:"self,value:log1"`
}

func (ml *MyLog1) WriteLog() {
	ml.log.Debug("debug 1")
	ml.log.Info("info 2")
	ml.log.Warn("warn 3")
	ml.log.Error("error 4")
}

Documentation

Index

Constants

View Source
const DefaultConfigPath = "logging"

Variables

View Source
var ErrInvalidConsole = errors.New("not a valid Console")
View Source
var ErrInvalidEncoder = errors.New("not a valid Encoder")
View Source
var ErrInvalidLevel = errors.New("not a valid Level")
View Source
var ErrInvalidName = errors.New("not a valid Name")

Functions

func SetDefaultLogFile

func SetDefaultLogFile(filename string) error

func SetLevel

func SetLevel(logPathGlob string, level Level)

func SetPipeWriter

func SetPipeWriter(writer *os.File)

func Sync

func Sync() error

func TemporarySetLevel

func TemporarySetLevel(logPath string, level Level, d time.Duration)

Types

type Config

type Config struct {
	Level       map[string]Level
	Console     ConsoleLog
	File        FileLog
	Pipe        PipeLog
	WithCaller  bool `json:"withcaller" yaml:"withcaller" value:"true"`
	WithLogName Name `json:"withlogname" yaml:"withlogname" value:"short"`
}

func (*Config) GetName

func (c *Config) GetName(typePath string) string

func (*Config) GetZapLevelByType

func (c *Config) GetZapLevelByType(typePath string) Level

func (*Config) Init

func (c *Config) Init()

type Console

type Console string

Console is en enum

@Enum {
	no
	stdout
	stderr
}
const (
	// ConsoleNo is a Console of type no.
	ConsoleNo Console = "no"
	// ConsoleStdout is a Console of type stdout.
	ConsoleStdout Console = "stdout"
	// ConsoleStderr is a Console of type stderr.
	ConsoleStderr Console = "stderr"
)

func ParseConsole

func ParseConsole(value string) (Console, error)

ParseConsole converts a string to a Console.

func (Console) IsValid

func (x Console) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (Console) MarshalText

func (x Console) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (Console) Name

func (x Console) Name() string

Name is the attribute of Console.

func (Console) String

func (x Console) String() string

String implements the Stringer interface.

func (*Console) UnmarshalText

func (x *Console) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

func (Console) Val

func (x Console) Val() string

Val is the attribute of Console.

type ConsoleLog

type ConsoleLog struct {
	Stream  Console `json:"stream" yaml:"stream" value:"stdout"`
	Encoder Encoder `json:"encoder" yaml:"encoder" value:"text"`
}

type Encoder

type Encoder int

Encoder

@Enum {
	text
	json
}
const (
	// EncoderText is an Encoder of type text.
	EncoderText Encoder = iota
	// EncoderJson is an Encoder of type json.
	EncoderJson
)

func ParseEncoder

func ParseEncoder(value string) (Encoder, error)

ParseEncoder converts a string to an Encoder.

func (Encoder) IsValid

func (x Encoder) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (Encoder) MarshalText

func (x Encoder) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (Encoder) Name

func (x Encoder) Name() string

Name is the attribute of Encoder.

func (Encoder) String

func (x Encoder) String() string

String implements the Stringer interface.

func (*Encoder) UnmarshalText

func (x *Encoder) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

func (Encoder) Val

func (x Encoder) Val() int

Val is the attribute of Encoder.

type Factory

type Factory struct {
}

func (*Factory) Init

func (f *Factory) Init(c *Config)

type FileLog

type FileLog struct {
	// Filename is the file to write logs to.  Backup log files will be retained
	// in the same directory.  It uses <processname>-lumberjack.log in
	// os.TempDir() if empty.
	Filename string `json:"filename" yaml:"filename"`

	// MaxSize is the maximum size in megabytes of the log file before it gets
	// rotated. It defaults to 100 megabytes.
	MaxSize int `json:"maxsize" yaml:"maxsize" value:"100"`

	// MaxAge is the maximum number of days to retain old log files based on the
	// timestamp encoded in their filename.  Note that a day is defined as 24
	// hours and may not exactly correspond to calendar days due to daylight
	// savings, leap seconds, etc. The default is not to remove old log files
	// based on age.
	MaxAge int `json:"maxage" yaml:"maxage" value:"30"`

	// MaxBackups is the maximum number of old log files to retain.  The default
	// is to retain all old log files (though MaxAge may still cause them to get
	// deleted.)
	MaxBackups int `json:"maxbackups" yaml:"maxbackups" value:"30"`

	// LocalTime determines if the time used for formatting the timestamps in
	// backup files is the computer's local time.  The default is to use UTC
	// time.
	LocalTime bool `json:"localtime" yaml:"localtime"  value:"false"`

	// Compress determines if the rotated log files should be compressed
	// using gzip. The default is not to perform compression.
	Compress bool `json:"compress" yaml:"compress"  value:"true"`

	Encoder Encoder `json:"encoder" yaml:"encoder" value:"text"`
}

type ITemporarySetLevel

type ITemporarySetLevel interface {
	TemporarySetLevel(level Level, d time.Duration)
}

type InnerLog

type InnerLog struct {
	L Logger `new:""`
}

InnerLog inner log struct

type Level

type Level int8

Level is an enum

@EnumConfig(PanicIfInvalid)
@Enum {
	Debug = -1
	Info
	Warn
	Error
	DPanic
	Panic
	Fatal
	Invalid
}
const (
	// LevelDebug is a Level of type Debug.
	LevelDebug Level = -1
	// LevelInfo is a Level of type Info.
	LevelInfo Level = 0
	// LevelWarn is a Level of type Warn.
	LevelWarn Level = 1
	// LevelError is a Level of type Error.
	LevelError Level = 2
	// LevelDpanic is a Level of type DPanic.
	LevelDpanic Level = 3
	// LevelPanic is a Level of type Panic.
	LevelPanic Level = 4
	// LevelFatal is a Level of type Fatal.
	LevelFatal Level = 5
	// LevelInvalid is a Level of type Invalid.
	LevelInvalid Level = 6
)

func ParseLevel

func ParseLevel(value string) (Level, error)

ParseLevel converts a string to a Level.

func (Level) IsValid

func (x Level) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (Level) MarshalText

func (x Level) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (Level) Name

func (x Level) Name() string

Name is the attribute of Level.

func (Level) String

func (x Level) String() string

String implements the Stringer interface.

func (Level) ToZapLevel

func (l Level) ToZapLevel() zapcore.Level

func (*Level) UnmarshalText

func (x *Level) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

func (Level) Val

func (x Level) Val() int8

Val is the attribute of Level.

type Logger

type Logger interface {
	Level() Level
	SetLevel(lvl Level)
	TemporarySetLevel(lvl Level, d time.Duration)
	AddHook(func(level Level, t time.Time, name string, msg string))
	Writer() io.Writer
	Sync() error

	Log(lvl Level, args ...any)
	Debug(args ...any)
	Info(args ...any)
	Warn(args ...any)
	Error(args ...any)
	Panic(args ...any)
	Fatal(args ...any)

	Logf(lvl Level, template string, args ...any)
	Debugf(template string, args ...any)
	Infof(template string, args ...any)
	Warnf(template string, args ...any)
	Errorf(template string, args ...any)
	Panicf(template string, args ...any)
	Fatalf(template string, args ...any)

	Logw(lvl Level, msg string, keysAndValues ...any)
	Debugw(msg string, keysAndValues ...any)
	Infow(msg string, keysAndValues ...any)
	Warnw(msg string, keysAndValues ...any)
	Errorw(msg string, keysAndValues ...any)
	Panicw(msg string, keysAndValues ...any)
	Fatalw(msg string, keysAndValues ...any)
}

func Log

func Log[T any]() Logger

func LogWithConfig

func LogWithConfig[T any](cfg *Config) Logger

func LogWithConfigPath

func LogWithConfigPath[T any](cfgPath string) Logger

func New

func New(t any) Logger

func NewWithConfigPath

func NewWithConfigPath(t any, cfgPath string) Logger

@Factory(params={self, "value:logging"})

func NewWithTypePathAndConfig

func NewWithTypePathAndConfig(typePath string, cfg *Config) Logger

func NewWithTypePathAndConfigPath

func NewWithTypePathAndConfigPath(typePath string, cfgPath string) Logger

type Name

type Name string

Name is en enum

@Enum {
	no       // no name
	short    // with short path
	full   // with full path
}
const (
	// NameNo is a Name of type no.
	NameNo Name = "no" // no name
	// NameShort is a Name of type short.
	NameShort Name = "short" // with short path
	// NameFull is a Name of type full.
	NameFull Name = "full" // with full path
)

func ParseName

func ParseName(value string) (Name, error)

ParseName converts a string to a Name.

func (Name) IsValid

func (x Name) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (Name) MarshalText

func (x Name) MarshalText() ([]byte, error)

MarshalText implements the text marshaller method.

func (Name) Name

func (x Name) Name() string

Name is the attribute of Name.

func (Name) String

func (x Name) String() string

String implements the Stringer interface.

func (*Name) UnmarshalText

func (x *Name) UnmarshalText(text []byte) error

UnmarshalText implements the text unmarshaller method.

func (Name) Val

func (x Name) Val() string

Val is the attribute of Name.

type PipeLog

type PipeLog struct {
	Writer  *os.File `json:"-"`
	Encoder Encoder  `json:"encoder" yaml:"encoder" value:"json"`
}

pipe log's writer is not set in config, it will be set in api

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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