wslog

package module
v0.0.0-...-11af102 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2023 License: Apache-2.0 Imports: 20 Imported by: 5

README

wslog

wslog is a wrapper for slog.

In order to ensure only relying on the standard library, the lumberjack package is copied to implement log rolling.

If you don't know how to configure log rolling, please refer to lumberjack.

Installation
go get -u github.com/zc2638/wslog
Definition
Format
  • json represents the JSON format log
  • text represents the Text format log
  • others represent the default Log format log
Examples
package main

import (
	"github.com/zc2638/wslog"
)

func main() {
	cfg := wslog.Confg{
		Format: "json",
		Level:  "info",
	}
	l := wslog.New(cfg)
	l.Info("the info log")
	l.Log(wslog.LevelInfo+1, "the info+1 log")
	l.Log(1, "another info+1 log")
}

Support digital definition level.

cfg := wslog.Confg{
    Format: "json",
    Level:  "info+2", // equivalent to `wslog.LevelInfo+2`
}

Use with context

logger := wslog.New(cfg)
ctx := wslog.WithContext(context.Backgroud(), logger)
l := wslog.FromContext(ctx)
l.Info("the info log")

You can get the built-in level to realize the level change during the running of the program.

level := l.Level().(*wslog.LevelVar)
level.Set(LevelInfo)

You can use a custom Leveler.

level := new(wslog.LevelVar)
wslog.New(cfg, level)

You can use a custom HandlerOptions.

cfg := wslog.Confg{
    Format: "text",
    Level:  "info",
}
handlerOptions := cfg.HandlerOptions()
wslog.New(cfg, handlerOptions)

You can use a custom Handler.

handler := wslog.NewLogHandler(os.Stdout, nil)
wslog.New(cfg, handler)

You can use a custom io.Writer.

wslog.New(cfg, io.Writer(os.Stdout))

Log rolling is built in by default, you can also use the lumberjack package as a writer.

w := &lumberjack.Logger{}
wslog.New(cfg, io.Writer(w))

You may want to replace some key associated content in the log by default.

replaceAttrFunc := func (groups []string, a Attr) Attr {
    // Remove time.
    if a.Key == slog.TimeKey && len(groups) == 0 {
        return slog.Attr{}
    }
    // Remove the directory from the source's filename.
    if a.Key == slog.SourceKey {
        source := a.Value.Any().(*slog.Source)
        source.File = filepath.Base(source.File)
    }
    return a
}
wslog.New(cfg, replaceAttrFunc)

You can combine multiple output sources.

h1 := wslog.NewLogHandler(os.Stdout, nil, false)
h2 := slog.NewJSONHandler(os.Stdout, nil)
h3 := NewKafkaHandler() // custom writer, like kafka
multiHandler := wslog.NewMultiHandler(h1, h2, h3)
wslog.New(cfg, multiHandler)

Documentation

Index

Constants

View Source
const (
	LevelDebug = slog.LevelDebug
	LevelInfo  = slog.LevelInfo
	LevelWarn  = slog.LevelWarn
	LevelError = slog.LevelError
)
View Source
const (
	KindAny       = slog.KindAny
	KindBool      = slog.KindBool
	KindDuration  = slog.KindDuration
	KindFloat64   = slog.KindFloat64
	KindInt64     = slog.KindInt64
	KindString    = slog.KindString
	KindTime      = slog.KindTime
	KindUint64    = slog.KindUint64
	KindGroup     = slog.KindGroup
	KindLogValuer = slog.KindLogValuer
)
View Source
const (
	// TimeKey is the key used by the built-in handlers for the time
	// when the log method is called. The associated Value is a [time.Time].
	TimeKey = slog.TimeKey
	// LevelKey is the key used by the built-in handlers for the level
	// of the log call. The associated value is a [Level].
	LevelKey = slog.LevelKey
	// MessageKey is the key used by the built-in handlers for the
	// message of the log call. The associated value is a string.
	MessageKey = slog.MessageKey
	// SourceKey is the key used by the built-in handlers for the source file
	// and line of the log call. The associated value is a string.
	SourceKey = slog.SourceKey
)
View Source
const BadKey = "!BADKEY"

Variables

This section is empty.

Functions

func Debug

func Debug(msg string, args ...any)

Debug calls Logger.Debug on the default logger.

func DebugCtx

func DebugCtx(ctx context.Context, msg string, args ...any)

DebugCtx calls Logger.DebugCtx on the default logger.

func Debugf

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

Debugf calls Logger.Debugf on the default logger.

func Error

func Error(msg string, args ...any)

Error calls Logger.Error on the default logger.

func ErrorCtx

func ErrorCtx(ctx context.Context, msg string, args ...any)

ErrorCtx calls Logger.ErrorCtx on the default logger.

func Errorf

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

Errorf calls Logger.Errorf on the default logger.

func Info

func Info(msg string, args ...any)

Info calls Logger.Info on the default logger.

func InfoCtx

func InfoCtx(ctx context.Context, msg string, args ...any)

InfoCtx calls Logger.InfoCtx on the default logger.

func Infof

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

Infof calls Logger.Infof on the default logger.

func Log

func Log(level Level, msg string, args ...any)

Log calls Logger.Log on the default logger.

func LogAttrs

func LogAttrs(level Level, msg string, attrs ...Attr)

LogAttrs calls Logger.LogAttrs on the default logger.

func LogAttrsCtx

func LogAttrsCtx(ctx context.Context, level Level, msg string, attrs ...Attr)

LogAttrsCtx calls Logger.LogAttrsCtx on the default logger.

func LogCtx

func LogCtx(ctx context.Context, level Level, msg string, args ...any)

LogCtx calls Logger.LogCtx on the default logger.

func NewWriter

func NewWriter(cfg Config) io.WriteCloser

func ParseLevel

func ParseLevel(ls SLevel) slog.Level

func RegisterLevel

func RegisterLevel(ls SLevel, ln Level)

func SetDefault

func SetDefault(l *Logger)

SetDefault makes l the default Logger. After this call, output from the log package's default Logger (as with log.Print, etc.) will be logged at LevelInfo using l's Handler.

func Warn

func Warn(msg string, args ...any)

Warn calls Logger.Warn on the default logger.

func WarnCtx

func WarnCtx(ctx context.Context, msg string, args ...any)

WarnCtx calls Logger.WarnCtx on the default logger.

func Warnf

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

Warnf calls Logger.Warnf on the default logger.

func WithContext

func WithContext(ctx context.Context, logger *Logger) context.Context

WithContext returns a new context with the provided logger. Use in combination with logger.With(key, value) for great effect.

Types

type Attr

type Attr = slog.Attr

type Config

type Config struct {
	Level  SLevel `json:"level,omitempty" yaml:"level,omitempty"`
	Format string `json:"format,omitempty" yaml:"format,omitempty"`
	Source bool   `json:"source,omitempty" yaml:"source,omitempty"`

	// only use for default log handler
	DisableColor bool `json:"disableColor,omitempty" yaml:"disableColor,omitempty"`

	Filename   string `json:"filename,omitempty" yaml:"filename,omitempty"`
	MaxSize    int    `json:"maxSize,omitempty" yaml:"maxSize,omitempty"`
	MaxAge     int    `json:"maxAge,omitempty" yaml:"maxAge,omitempty"`
	MaxBackups int    `json:"maxBackups,omitempty" yaml:"maxBackups,omitempty"`
	LocalTime  bool   `json:"localTime,omitempty" yaml:"localTime,omitempty"`
	Compress   bool   `json:"compress,omitempty" yaml:"compress,omitempty"`
}

func (*Config) HandlerOptions

func (c *Config) HandlerOptions() *HandlerOptions

func (*Config) Writer

func (c *Config) Writer() io.Writer

type Handler

type Handler = slog.Handler

func NewLogHandler

func NewLogHandler(w io.Writer, opts *HandlerOptions, disableColor bool) Handler

func NewMultiHandler

func NewMultiHandler(handlers ...Handler) Handler

type HandlerOptions

type HandlerOptions = slog.HandlerOptions

type Kind

type Kind = slog.Kind

type Level

type Level = slog.Level

type LevelVar

type LevelVar = slog.LevelVar

type Leveler

type Leveler = slog.Leveler

type Logger

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

func Default

func Default() *Logger

Default returns the default Logger.

func FromContext

func FromContext(ctx context.Context) *Logger

FromContext retrieves the current logger from the context. If no logger is available, the default logger is returned.

func FromRequest

func FromRequest(r *http.Request) *Logger

FromRequest retrieves the current logger from the request. If no logger is available, the default logger is returned.

func New

func New(cfg Config, opts ...any) *Logger

func NewLogger

func NewLogger(h Handler) *Logger

NewLogger creates a new Logger with the given non-nil Handler.

func NewLoggerSkip

func NewLoggerSkip(h Handler, skip int) *Logger

func With

func With(args ...any) *Logger

With calls Logger.With on the default logger.

func (*Logger) Debug

func (l *Logger) Debug(msg string, args ...any)

Debug logs at LevelDebug.

func (*Logger) DebugCtx

func (l *Logger) DebugCtx(ctx context.Context, msg string, args ...any)

DebugCtx logs at LevelDebug with the given context.

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...any)

Debugf logs at LevelDebug with the given format.

func (*Logger) Enabled

func (l *Logger) Enabled(level Level) bool

Enabled reports whether l emits log records at the given level.

func (*Logger) EnabledCtx

func (l *Logger) EnabledCtx(ctx context.Context, level Level) bool

EnabledCtx reports whether l emits log records at the given context and level.

func (*Logger) Error

func (l *Logger) Error(msg string, args ...any)

Error logs at LevelError.

func (*Logger) ErrorCtx

func (l *Logger) ErrorCtx(ctx context.Context, msg string, args ...any)

ErrorCtx logs at LevelError with the given context.

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...any)

Errorf logs at LevelError with the given format.

func (*Logger) Handler

func (l *Logger) Handler() Handler

func (*Logger) Info

func (l *Logger) Info(msg string, args ...any)

Info logs at LevelInfo.

func (*Logger) InfoCtx

func (l *Logger) InfoCtx(ctx context.Context, msg string, args ...any)

InfoCtx logs at LevelInfo with the given context.

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...any)

Infof logs at LevelInfo with the given format.

func (*Logger) Log

func (l *Logger) Log(level Level, msg string, args ...any)

func (*Logger) LogAttrs

func (l *Logger) LogAttrs(level Level, msg string, attrs ...Attr)

func (*Logger) LogAttrsCtx

func (l *Logger) LogAttrsCtx(ctx context.Context, level Level, msg string, attrs ...Attr)

LogAttrsCtx is a more efficient version of Logger.Log that accepts only Attrs.

func (*Logger) LogCtx

func (l *Logger) LogCtx(ctx context.Context, level Level, msg string, args ...any)

LogCtx emitting a log record with the current time and the given level and message. The Record's Attrs consist of the Logger's attributes followed by the Attrs specified by args.

The attribute arguments are processed as follows:

  • If an argument is an Attr, it is used as is.
  • If an argument is a string and this is not the last argument, the following argument is treated as the value and the two are combined into an Attr.
  • Otherwise, the argument is treated as a value with key `!BADKEY`.

func (*Logger) Warn

func (l *Logger) Warn(msg string, args ...any)

Warn logs at LevelWarn.

func (*Logger) WarnCtx

func (l *Logger) WarnCtx(ctx context.Context, msg string, args ...any)

WarnCtx logs at LevelWarn with the given context.

func (*Logger) Warnf

func (l *Logger) Warnf(format string, args ...any)

Warnf logs at LevelWarn with the given format.

func (*Logger) With

func (l *Logger) With(args ...any) *Logger

func (*Logger) WithGroup

func (l *Logger) WithGroup(name string) *Logger

WithGroup returns a Logger that starts a group if the name is non-empty. The keys of all attributes added to the Logger will be qualified by the given name. (How that qualification happens depends on the [Handler.WithGroup] method of the Logger's Handler.)

If the name is empty, WithGroup returns the receiver.

type Record

type Record = slog.Record

type SLevel

type SLevel string
const (
	SLevelDebug SLevel = "debug"
	SLevelInfo  SLevel = "info"
	SLevelWarn  SLevel = "warn"
	SLevelError SLevel = "error"
)

func (SLevel) Level

func (l SLevel) Level() Level

func (SLevel) String

func (l SLevel) String() string

type Writer

type Writer 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

	// MaxSize is the maximum size in megabytes of the log file before it gets
	// rotated. It defaults to 100 megabytes.
	MaxSize int

	// 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

	// 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

	// 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

	// Compress determines if the rotated log files should be compressed
	// using gzip. The default is not to perform compression.
	Compress bool
	// contains filtered or unexported fields
}

func (*Writer) Close

func (l *Writer) Close() error

Close implements io.Closer, and closes the current logfile.

func (*Writer) Rotate

func (l *Writer) Rotate() error

Rotate causes Logger to close the existing log file and immediately create a new one. This is a helper function for applications that want to initiate rotations outside of the normal rotation rules, such as in response to SIGHUP. After rotating, this initiates compression and removal of old log files according to the configuration.

func (*Writer) Write

func (l *Writer) Write(p []byte) (n int, err error)

Write implements io.Writer. If a write would cause the log file to be larger than MaxSize, the file is closed, renamed to include a timestamp of the current time, and a new log file is created using the original log file name. If the length of the write is greater than MaxSize, an error is returned.

Jump to

Keyboard shortcuts

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