slog

package
v0.5.20 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2024 License: Apache-2.0 Imports: 23 Imported by: 9

Documentation

Index

Constants

View Source
const (
	TimeNoNano      = "15:04:05Z07:00"                      // text-logging timestamp format: time only, without nano second part
	TimeNano        = "15:04:05.000000Z07:00"               // text-logging timestamp format: time only
	DateTime        = "2006-01-0215:04:05Z07:00"            // text-logging timestamp format: date and time, with timezone
	RFC3339Nano     = "2006-01-02T15:04:05.000000Z07:00"    // text-logging timestamp format: RFC3339Nano
	RFC3339NanoOrig = "2006-01-02T15:04:05.999999999Z07:00" // text-logging timestamp format: RFC3339Nano with 9 bits nano seconds
)
View Source
const BADKEY = "!BADKEY"
View Source
const MaxLengthShortTag = 6 // Level string length while formatting and printing
View Source
const MinRead = 512

MinRead is the minimum slice size passed to a Read call by Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond what is required to hold the contents of r, ReadFrom will not grow the underlying buffer.

View Source
const (
	Version = "v0.5.20" // new Version of logg/slog
)

Variables

View Source
var ErrTooLarge = errors.New("logg/slog.PrintCtx: too large")

ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer.

Functions

func AddCodeHostingProviders

func AddCodeHostingProviders(provider, repl string)

AddCodeHostingProviders appends more provider, repl pair to reduce the caller text width.

The builtin providers are:

  • "github.com" -> "GH"
  • "gitlab.com" -> "GL"
  • "gitee.com" -> "GT"
  • "bitbucket.com" -> "BB"
  • ...

func AddFlags

func AddFlags(flagsToAdd ...Flags)

AddFlags adds some Flags (bitwise Or operation).

These ways can merge flags into internal settings:

AddFlags(Lprivacypathregexp | Lprivacypath)
AddFlags(Lprivacypathregexp, Lprivacypath)

func AddKnownPathMapping

func AddKnownPathMapping(pathname, repl string)

AddKnownPathMapping appends more (pathname, repl) pair to reduce the caller filepath width.

Such as:

  • "$HOME" -> "~"
  • pwd -> "." (current directory -> '.', that means any abs-path will be converted to rel-path)

func AddKnownPathRegexpMapping

func AddKnownPathRegexpMapping(pathnameRegexpExpr, repl string)

AddKnownPathRegexpMapping adds regexp pattern, repl pair to reduce the called filepath width.

func Debug

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

func DebugContext

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

DebugContext with Default Logger.

func Error

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

func ErrorContext

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

ErrorContext with Default Logger.

func Fail

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

func FailContext

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

FailContext with Default Logger.

func Fatal

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

func FatalContext

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

FatalContext with Default Logger.

func GetDefaultLoggersWriter

func GetDefaultLoggersWriter() (wr io.Writer)

func GetDefaultWriter

func GetDefaultWriter() (wr io.Writer)

func GetTtySize

func GetTtySize() (cols, rows int)

GetTtySize returns the window size in columns and rows in the active console window. The return value of this function is in the order of cols, rows.

func Info

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

func InfoContext

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

InfoContext with Default Logger.

func IsAllBitsSet

func IsAllBitsSet(f Flags) bool

func IsAnsiEscaped added in v0.5.3

func IsAnsiEscaped(s string) bool

IsAnsiEscaped detects a string if it contains ansi color escaped sequences

func IsAnyBitsSet

func IsAnyBitsSet(f Flags) bool

func IsColoredTty

func IsColoredTty(w io.Writer) bool

IsColoredTty detects a writer if it is a colorful tty device.

A colorful tty device can receive ANSI escaped sequences and draw its.

func IsTty

func IsTty(w io.Writer) bool

IsTty detects a writer if it is abstracting from a tty (console, terminal) device.

func IsTtyEscaped

func IsTtyEscaped(s string) bool

IsTtyEscaped detects a string if it contains ansi color escaped sequences

func NewFileWriter

func NewFileWriter(pathname string) *filewr

func NewLogLogger

func NewLogLogger(h Logger, lvl Level) *log.Logger

NewLogLogger returns a new log.Logger such that each call to its Output method dispatches a Record to the specified handler. The logger acts as a bridge from the older log API to newer structured logging handlers.

func NewLogWriter

func NewLogWriter(w io.Writer) *logwr

func NewSlogHandler

func NewSlogHandler(logger Logger, config *HandlerOptions) logslog.Handler

NewSlogHandler makes a log/slog Handler to adapt into std slog.

func OK

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

func OKContext

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

OKContext with Default Logger.

func Panic

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

func PanicContext

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

PanicContext with Default Logger.

func Print

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

func PrintContext

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

PrintContext with Default Logger.

func Println

func Println(args ...any)

Println with Default Logger.

func PrintlnContext

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

PrintlnContext with Default Logger.

func ReadPassword

func ReadPassword() (text string, err error)

ReadPassword reads the password from stdin with safe protection

func RegisterLevel

func RegisterLevel(levelValue Level, title string, opts ...RegOpt) error

RegisterLevel records the given Level value as stocked.

func RemoveFlags

func RemoveFlags(flagsToRemove ...Flags)

RemoveFlags removes some Flags (bitwise And negative operation).

These ways can strip flags off from internal settings:

RemoveFlags(Lprivacypathregexp | Lprivacypath)
RemoveFlags(Lprivacypathregexp, Lprivacypath)

func Reset

func Reset()

Reset clear user settings and restore Default to default.

func ResetFlags

func ResetFlags()

func ResetLevel

func ResetLevel()

ResetLevel restore the default logger level to factory value (WarnLevel).

func SaveFlagsAndMod

func SaveFlagsAndMod(addingFlags Flags, removingFlags ...Flags) (deferFn func())

SaveFlagsAndMod saves old flags, modify it, and restore the old at defer time.

A typical usage might be:

// Inside a test case, you wanna add date part to timestamp output,
// and disable panic (by Panic or Fatal) breaking the testing flow.
// So this line will make those temporary modifications:
defer SaveFlagsAndMod(Ldate | LnoInterrupt)()
// ...
// concrete testing codes here

func SaveLevelAndSet

func SaveLevelAndSet(lvl Level) func()

SaveLevelAndSet sets Default logger's level and default logger level.

SaveLevelAndSet saves old level and return a functor to restore it. So a typical usage is:

func A() {
    defer slog.SaveLevelAndSet(slog.PanicLevel)()
    l := slog.New().WithLevel(slog.WarnLevel)
    ...
}

GetLevel and SetLevel can access the default logger level.

func SetDefault

func SetDefault(l Logger)

func SetFlags

func SetFlags(f Flags)

func SetLevel

func SetLevel(lvl Level)

SetLevel sets the default logger level

func SetLevelColors

func SetLevelColors(lvl Level, fg, bg color.Color)

SetLevelColors defines your fore-/background color for printing the leveled text to terminal.

func SetLevelOutputWidth

func SetLevelOutputWidth(width int)

SetLevelOutputWidth sets how many characters of level string should be formatted and output to logging lines.

While you are customizing your level, a 1..5 characters array is required for formatting purpose.

For example:

const NoticeLevel = slog.Level(17) // A custom level must have a value greater than slog.MaxLevel
slog.RegisterLevel(NoticeLevel, "NOTICE",
    slog.RegWithShortTags([6]string{"", "N", "NT", "NTC", "NOTC", "NOTIC"}),
    slog.RegWithColor(color.FgWhite, color.BgUnderline),
    slog.RegWithTreatedAsLevel(slog.InfoLevel),
))

func SetMessageMinimalWidth

func SetMessageMinimalWidth(w int)

SetMessageMinimalWidth modify the minimal width between message and attributes. It works for only colorful mode.

The default width is 36, that means a message will be left padding to take 36 columns, filled by space char (' ').

func SetSkip

func SetSkip(extraFrames int)

func StripEscapes

func StripEscapes(str string) (strCleaned string)

StripEscapes removes any ansi color escaped sequences from a string

func Success

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

func SuccessContext

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

SuccessContext with Default Logger.

func Trace

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

func TraceContext

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

TraceContext with Default Logger.

func Verbose

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

func VerboseContext

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

func Warn

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

func WarnContext

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

WarnContext with Default Logger.

Types

type ArrayMarshaller

type ArrayMarshaller interface {
	MarshalSlogArray(enc *PrintCtx) error
}

ArrayMarshaller to allow your slice or array object serialized by our PrintCtx

type Attr

type Attr interface {
	Key() string
	Value() any
	SetValue(v any) // to modify the value dynamically
}

Attr for external adapters

func Any

func Any(key string, val any) Attr

func Bool

func Bool(key string, val bool) Attr

func Complex128

func Complex128(key string, val complex128) Attr

func Complex64

func Complex64(key string, val complex64) Attr

func Duration

func Duration(key string, val time.Duration) Attr

func Float32

func Float32(key string, val float32) Attr

func Float64

func Float64(key string, val float64) Attr

func Group

func Group(key string, args ...any) Attr

Group constructs grouped k-v pair container, which can hold a set of normal attrs.

See String for performance tip.

For example:

g := Group("source",
   String("file", filename),
   Int("line", lineno),
)

func Int

func Int(key string, val int) Attr

func Int16

func Int16(key string, val int16) Attr

func Int32

func Int32(key string, val int32) Attr

func Int64

func Int64(key string, val int64) Attr

func Int8

func Int8(key string, val int8) Attr

func NewAttr

func NewAttr(key string, val any) Attr

func NewGroupedAttr

func NewGroupedAttr(key string, as ...Attr) Attr

func NewGroupedAttrEasy

func NewGroupedAttrEasy(key string, as ...any) Attr

func Numeric

func Numeric[T Numerics](key string, val T) Attr

func String

func String(key, val string) Attr

String constructs a key-value pair with string value like log/slog.

The different is we have not optimized these functions (String, Int, ...) for performance and memory allocations. So they are just compatible with log/slog.

For performance, using With(attrs...) / WithAttrs(...) to get prefer effects.

func Time

func Time(key string, val time.Time) Attr

func Uint

func Uint(key string, val uint) Attr

func Uint16

func Uint16(key string, val uint16) Attr

func Uint32

func Uint32(key string, val uint32) Attr

func Uint64

func Uint64(key string, val uint64) Attr

func Uint8

func Uint8(key string, val uint8) Attr

type Attrs

type Attrs []Attr // slice of Attr

func NewAttrs

func NewAttrs(args ...any) Attrs

func (Attrs) SerializeValueTo

func (s Attrs) SerializeValueTo(pc *PrintCtx)

type BasicLogger

type BasicLogger interface {
	Printer
	PrinterWithContext
	Builder

	Enabled(requestingLevel Level) bool // to test the requesting logging level should be allowed.
	EnabledContext(ctx context.Context, requestingLevel Level) bool

	LogAttrs(ctx context.Context, level Level, msg string, args ...any) // Attr, Attrs in args will be recognized as is
	Log(ctx context.Context, level Level, msg string, args ...any)      // Attr, Attrs in args will be recognized as is

	// WithSkip create a new child logger with specified extra
	// ignored stack frames, which will be plussed over the
	// internal stack frames stripping tool.
	//
	// A child logger is super lite commonly. It'll take a little
	// more resource usages only if you have LattrsR set globally.
	// In that case, child logger looks up all its parents for
	// collecting all attributes and logging them.
	WithSkip(extraFrames int) Entry

	// SetSkip is very similar with WithSkip but no child logger
	// created, it modifies THIS logger.
	//
	// Use it when you know all what u want.
	SetSkip(extraFrames int)
	Skip() int // return current frames count should be ignored in addition. 0 for most cases.

	Name() string // this logger's name
}

BasicLogger supplies basic logging apis.

type BoolSlice

type BoolSlice[T bool] []T // BoolSlice declares slice of boolean generic type

type Builder

type Builder interface {
	New(args ...any) BasicLogger // 1st of args is name, the rest are k, v pairs

	WithJSONMode(b ...bool) Entry          // entering JSON mode, the output are json format
	WithColorMode(b ...bool) Entry         // entering Colorful mode for the modern terminal. false means using logfmt format.
	WithUTCMode(b ...bool) Entry           // default is local mode, true will switch to UTC mode
	WithTimeFormat(layout ...string) Entry // specify your timestamp format layout string
	WithLevel(lvl Level) Entry             //
	WithAttrs(attrs ...Attr) Entry         //
	WithAttrs1(attrs Attrs) Entry          //
	With(args ...any) Entry                // key1,val1,key2,val2,.... Of course, Attr, Attrs in args will be recognized as is

	WithContextKeys(keys ...any) Entry // given keys will be tried extracting from context.Context automatically

	WithWriter(wr io.Writer) Entry          // use the given writer
	AddWriter(wr io.Writer) Entry           // append more writers via this interface
	AddErrorWriter(wr io.Writer) Entry      //
	ResetWriters() Entry                    //
	GetWriter() (wr LogWriter)              // return level-matched writer
	GetWriterBy(level Level) (wr LogWriter) // return writer matched given level

	AddLevelWriter(lvl Level, w io.Writer) Entry
	RemoveLevelWriter(lvl Level, w io.Writer) Entry
	ResetLevelWriter(lvl Level) Entry
	ResetLevelWriters() Entry

	WithValueStringer(vs ValueStringer) Entry
}

Builder is used for building a new logger

type ComplexSlice

type ComplexSlice[T Complexes] []T // ComplexSlice declares slice of complex number generic type

type Complexes

type Complexes interface {
	complex64 | complex128
}

Complexes declares complex number generic type

type Entries

type Entries map[string]Entry

Entries collects many entry objects as a map

type Entry

type Entry interface {
	BasicLogger

	Close() // Closeable interface

	String() string // Stringer interface

	Parent() Entry // parent logger of a sub-logger
	Root() Entry   // root logger (always is Default) of a sub-logger

	Level() Level // logging level associated with this logger

}

Entry is a small and efficient tiny logger, which is the entity of real logger.

func WithSkip

func WithSkip(extraFrames int) Entry

WithSkip make a child logger from Default and set the extra ignored frames with given value.

By default, LattrsR is not enabled. So the new child logger cannot print the parent's attrs. You could have to AddFlags(LattrsR) to give WithSkip a better behavior.

If you dislike to make another one new child Logger instance, using SetSkip pls.

type Flags

type Flags int64
const (
	Ldate              Flags = 1 << iota // do print date part
	Ltime                                // do print time part
	Lmicroseconds                        // do print microseconds part
	LlocalTime                           // use local time instead of UTC
	Lattrs                               // do print Attr key-value pairs
	LattrsR                              // collect Attr along with entry and Logger chains
	Llineno                              // do print caller info (file:line)
	Lcaller                              // do print Caller information (function)
	Lcallerpackagename                   // do print the package name of caller, such as: GH/hedzr/logg/slog_test.TestSlogLogfmt

	Lprivacypath       // Privacy hardening flag. A string slice will be used for hiding disk pathname.
	Lprivacypathregexp // Privacy hardening flag. A regexp pattern slice will be used.

	LsmartJSONMode // enable JSON mode if the current output device is not terminal/tty

	LnoInterrupt     // don't interrupt app running when Fatal or Panic
	Linterruptalways // raise panic or os.Exit always even if in testing mode

	// LstdFlags is the default flags when unboxed
	LstdFlags = Ltime | Lmicroseconds | LlocalTime | Llineno | Lcaller | Lattrs |
		Lprivacypath | Lprivacypathregexp

	Ldatetimeflags = Ldate | Ltime | Lmicroseconds // for timestamp formatting

	Lempty Flags = 0 // for algor
)

func GetFlags

func GetFlags() Flags

type FloatSlice

type FloatSlice[T Floats] []T // FloatSlice declares slice of float number generic type

type Floats

type Floats interface {
	float32 | float64
}

Floats declares float number generic type

type HandlerOptions

type HandlerOptions struct {
	NoColor  bool  // is colorful outputting?
	NoSource bool  // has caller info?
	JSON     bool  // logging as JSON format?
	Level    Level // zero value means no setup level. Note that zero value represents indeed PanicLevel, so it cannot be used for SetLevel.
}

HandlerOptions is used for our log/slog Handler

type IntSlice

type IntSlice[T Integers] []T // IntSlice declares slice of signed integers generic type

type Integers

type Integers interface {
	int | int8 | int16 | int32 | int64
}

Integers declares signed integers generic type

type LWs

type LWs []LogWriter

func (LWs) Close

func (s LWs) Close() (err error)

func (LWs) Write

func (s LWs) Write(p []byte) (n int, err error)

type Level

type Level int // logging level
const (

	// PanicLevel level, highest level of severity. Logs and then calls panic with the
	// message passed to Debug, Info, ...
	PanicLevel Level = iota
	// FatalLevel level. Logs and then calls `os.Exit(-9)`. It will exit even if the
	// logging level is set to PanicLevel.
	FatalLevel
	// ErrorLevel level. Logs. Used for errors that should definitely be noted.
	// Commonly used for hooks to send errors to an error tracking service.
	ErrorLevel
	// WarnLevel level. Non-critical entries that deserve eyes.
	WarnLevel
	// InfoLevel level. General operational entries about what's going on inside the
	// application.
	InfoLevel
	// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
	DebugLevel
	// TraceLevel level. Designates finer-grained informational events than the DebugLevel.
	TraceLevel

	// OffLevel level. The logger will be shutdown.
	OffLevel
	// AlwaysLevel level. Used for Print, Printf, Println, OK, Success and Fail (use ErrorLevel).
	AlwaysLevel

	OKLevel      // OKLevel for operation okay.
	SuccessLevel // SuccessLevel for operation successfully.
	FailLevel    // FailLevel for operation failed.

	MaxLevel // maximal level value for algorithm usage
)

func AllLevels

func AllLevels() []Level

AllLevels is a constant exposing all logging levels

func GetLevel

func GetLevel() Level

GetLevel returns the default logger level

func ParseLevel

func ParseLevel(lvl string) (Level, error)

ParseLevel takes a string level and returns the Logrus log level constant.

func (Level) Enabled

func (level Level) Enabled(ctx context.Context, testingLevel Level) bool

func (Level) MarshalJSON

func (level Level) MarshalJSON() ([]byte, error)

func (Level) MarshalText

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

MarshalText convert Level to string and []byte.

Available level names are:

  • "disable"
  • "fatal"
  • "error"
  • "warn"
  • "info"
  • "debug"
  • ...

func (Level) ShortTag

func (level Level) ShortTag(length int) string

ShortTag convert Level to a short tag string. eg. PanicLevel becomes "P".

func (Level) String

func (level Level) String() string

Convert the Level to a string. eg. PanicLevel becomes "panic".

func (*Level) UnmarshalJSON

func (level *Level) UnmarshalJSON(text []byte) error

func (*Level) UnmarshalText

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

UnmarshalText implements encoding.TextUnmarshaler.

type LogLoggerAware

type LogLoggerAware interface {
	WriteInternal(ctx context.Context, lvl Level, pc uintptr, buf []byte) (n int, err error)
}

LogLoggerAware for external adapters

type LogSlogAware

type LogSlogAware interface {
	WriteThru(ctx context.Context, lvl Level, timestamp time.Time, pc uintptr, msg string, attrs Attrs)
}

LogSlogAware for external adapters

type LogValuer

type LogValuer interface {
	Value() Attr
}

LogValuer for external adapters

type LogWriter

type LogWriter interface {
	io.Writer
	io.Closer
}

LogWriter for external adapters

type LogWriters

type LogWriters interface{} //nolint:revive

LogWriters for external adapters

type Logger

type Logger interface {
	Entry
}

Logger interface can be used for others logging kits or apps.

func Default

func Default() Logger

func New

func New(args ...any) Logger

New creates a new detached logger and you can make it default by SetDefault.

You also call the package-level logging functions directly. Such as: Info, Debug, Trace, Warn, Error, Fatal, Panic, ...

There are some special severities by calling OK, Success and Fail.

From a logger, you can make new child logger cascaded with its parent. It has different logging context and also share the parent's context like common attributes.

First of args must be a string to identify this logger, i.e., it's the logger name.

The rest of args can be these sequences:

  1. one or more element(s) with type Attr or Attrs
  2. one or more element(s) with type Opt
  3. one or more key-value-pair(s)

For example:

logger := slog.New("standalone-logger-for-app",
    slog.NewAttr("attr1", 2),
    slog.NewAttrs("attr2", 3, "attr3", 4.1),
    "attr4", true, "attr3", "string",
    slog.WithLevel(slog.DebugLevel), // an Opt here is allowed
)

The logger name is a unique name. Reusing a used name will pick the exact child.

Passing an empty name is allowed, a random name will be generated.

For example:

logger := slog.New("my-app")

type Numerics

type Numerics interface {
	Integers | Uintegers | Floats | Complexes
}

Numerics declares numeric generic type

type ObjectMarshaller

type ObjectMarshaller interface {
	MarshalSlogObject(enc *PrintCtx) error
}

ObjectMarshaller to allow your object serialized by our PrintCtx

type ObjectSerializer

type ObjectSerializer interface {
	SerializeValueTo(pc *PrintCtx)
}

ObjectSerializer to allow your object serialized by our PrintCtx

type Opt

type Opt func(s *entry) // can be passed to New as args

func AddErrorWriter

func AddErrorWriter(wr io.Writer) Opt

AddErrorWriter adds a stderr writers to Default logger. It is a Opt functor so you have to invoke it at New(,,,).

For each child loggers, uses their method [entry.AddErrorWriter],

func AddLevelWriter

func AddLevelWriter(lvl Level, w io.Writer) Opt

AddLevelWriter add a leveled writer in Default logger. It is a Opt functor so you have to invoke it at New(,,,).

For each child loggers, uses their method [entry.AddLevelWriter],

A leveled writer has higher priorities than normal writers, see AddWriter and AddErrorWriter.

func AddWriter

func AddWriter(wr io.Writer) Opt

AddWriter adds a stdout writers to Default logger. It is a Opt functor so you have to invoke it at New(,,,).

For each child loggers, uses their method [entry.AddWriter],

func RemoveLevelWriter

func RemoveLevelWriter(lvl Level, w io.Writer) Opt

RemoveLevelWriter remove a leveled writer in Default logger. It is a Opt functor so you have to invoke it at New(,,,).

For each child loggers, uses their method [entry.RemoveLevelWriter],

func ResetLevelWriter

func ResetLevelWriter(lvl Level) Opt

ResetLevelWriter clear anu leveled writers for a specified Level in Default logger. It is a Opt functor so you have to invoke it at New(,,,).

For each child loggers, uses their method [entry.ResetLevelWriter],

func ResetLevelWriters

func ResetLevelWriters() Opt

ResetLevelWriters clear all leveled writers in Default logger. It is a Opt functor so you have to invoke it at New(,,,).

For each child loggers, uses their method [entry.ResetLevelWriters],

func ResetWriters

func ResetWriters() Opt

ResetWriters clear all stdout and stderr writers in Default logger. It is a Opt functor so you have to invoke it at New(,,,).

For each child loggers, uses their method [entry.ResetWriters],

func With

func With(args ...any) Opt

With allows an freeform arg list passed into New. Sample is:

lc1 := l.New("c1").With("a1", 1, "a2", 2.7, NewAttr("a3", "string"))

More samples can be found at New.

func WithAttrs

func WithAttrs(attrs ...Attr) Opt

WithAttrs declares some common attributes bound to the logger.

When logging, attributes of the logger and its parents will be merged together. If duplicated attr found, the parent's will be overwritten.

lc1 := l.New("c1").WithAttrs(NewAttr("lc1", true))
lc3 := lc1.New("c3").WithAttrs(NewAttr("lc3", true), NewAttr("lc1", 1))
lc3.Warn("lc3 warn msg", "local", false)

In above case, attr 'lc1' will be rewritten while lc3.Warn, it looks like:

17:47:24.765422+08:00 [WRN] lc3 warn msg          lc1=1 lc3=true local=false

You can initialize attributes with different forms, try using WithAttrs1(attrs Attrs) or With(args ...any) for instead.

func WithAttrs1

func WithAttrs1(attrs Attrs) Opt

WithAttrs1 allows an Attrs passed into New. Sample is:

lc1 := l.New("c1").WithAttrs1(NewAttrs("a1", 1, "a2", 2.7, NewAttr("a3", "string")))

NewAttrs receives a freeform args list.

You can use With(...) to simplify WithAttrs1+NewAttrs1 calling.

func WithColorMode

func WithColorMode(b ...bool) Opt

func WithErrorWriter added in v0.5.11

func WithErrorWriter(wr io.Writer) Opt

func WithJSONMode

func WithJSONMode(b ...bool) Opt

func WithLevel

func WithLevel(lvl Level) Opt

func WithTimeFormat

func WithTimeFormat(layout ...string) Opt

func WithUTCMode

func WithUTCMode(b ...bool) Opt

func WithWriter

func WithWriter(wr io.Writer) Opt

WithWriter sets a std writer to Default logger, the original std writers will be cleared. It is a Opt functor so you have to invoke it at New(,,,).

For each child loggers, uses their method [entry.WithWriter],

type PrintCtx

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

PrintCtx when formatting logging line in text logger

func NewPrintCtx

func NewPrintCtx(buf []byte) *PrintCtx

NewPrintCtx creates and initializes a new Buffer using buf as its initial contents. The new Buffer takes ownership of buf, and the caller should not use buf after this call. NewBuffer is intended to prepare a Buffer to read existing data. It can also be used to set the initial size of the internal buffer for writing. To do that, buf should have the desired capacity but a length of zero.

In most cases, new(Buffer) (or just declaring a Buffer variable) is sufficient to initialize a Buffer.

func NewPrintCtxString

func NewPrintCtxString(s string) *PrintCtx

NewPrintCtxString creates and initializes a new Buffer using string s as its initial contents. It is intended to prepare a buffer to read an existing string.

In most cases, new(Buffer) (or just declaring a Buffer variable) is sufficient to initialize a Buffer.

func (*PrintCtx) AddBool

func (s *PrintCtx) AddBool(name string, value bool)

func (*PrintCtx) AddComplex128

func (s *PrintCtx) AddComplex128(name string, value complex128)

func (*PrintCtx) AddComplex64

func (s *PrintCtx) AddComplex64(name string, value complex64)

func (*PrintCtx) AddFloat32

func (s *PrintCtx) AddFloat32(name string, value float32)

func (*PrintCtx) AddFloat64

func (s *PrintCtx) AddFloat64(name string, value float64)

func (*PrintCtx) AddInt

func (s *PrintCtx) AddInt(name string, value int)

func (*PrintCtx) AddInt16

func (s *PrintCtx) AddInt16(name string, value int16)

func (*PrintCtx) AddInt32

func (s *PrintCtx) AddInt32(name string, value int32)

func (*PrintCtx) AddInt64

func (s *PrintCtx) AddInt64(name string, value int64)

func (*PrintCtx) AddInt8

func (s *PrintCtx) AddInt8(name string, value int8)

func (*PrintCtx) AddPrefixedInt

func (s *PrintCtx) AddPrefixedInt(prefix, name string, value int)

func (*PrintCtx) AddPrefixedString

func (s *PrintCtx) AddPrefixedString(prefix, name string, value string)

func (*PrintCtx) AddRune added in v0.5.7

func (s *PrintCtx) AddRune(r rune)

func (*PrintCtx) AddString

func (s *PrintCtx) AddString(name string, value string)

func (*PrintCtx) AddUint

func (s *PrintCtx) AddUint(name string, value uint)

func (*PrintCtx) AddUint16

func (s *PrintCtx) AddUint16(name string, value uint16)

func (*PrintCtx) AddUint32

func (s *PrintCtx) AddUint32(name string, value uint32)

func (*PrintCtx) AddUint64

func (s *PrintCtx) AddUint64(name string, value uint64)

func (*PrintCtx) AddUint8

func (s *PrintCtx) AddUint8(name string, value uint8)

func (*PrintCtx) AppendByte

func (s *PrintCtx) AppendByte(value byte)

func (*PrintCtx) AppendBytes

func (s *PrintCtx) AppendBytes(value []byte)

func (*PrintCtx) AppendInt

func (s *PrintCtx) AppendInt(val int)

func (*PrintCtx) AppendRune

func (s *PrintCtx) AppendRune(value rune)

func (*PrintCtx) AppendRunes

func (s *PrintCtx) AppendRunes(value []rune)

func (*PrintCtx) Available

func (s *PrintCtx) Available() int

Available returns how many bytes are unused in the buffer.

func (*PrintCtx) AvailableBuffer

func (s *PrintCtx) AvailableBuffer() []byte

AvailableBuffer returns an empty buffer with b.Available() capacity. This buffer is intended to be appended to and passed to an immediately succeeding Write call. The buffer is only valid until the next write operation on b.

func (*PrintCtx) Bytes

func (s *PrintCtx) Bytes() []byte

Bytes returns a slice of length b.Len() holding the unread portion of the buffer. The slice is valid for use only until the next buffer modification (that is, only until the next call to a method like Read, Write, Reset, or Truncate). The slice aliases the buffer content at least until the next buffer modification, so immediate changes to the slice will affect the result of future reads.

func (*PrintCtx) Cap

func (s *PrintCtx) Cap() int

Cap returns the capacity of the buffer's underlying byte slice, that is, the total space allocated for the buffer's data.

func (*PrintCtx) Grow

func (s *PrintCtx) Grow(n int)

Grow grows the buffer's capacity, if necessary, to guarantee space for another n bytes. After Grow(n), at least n bytes can be written to the buffer without another allocation. If n is negative, Grow will panic. If the buffer can't grow it will panic with ErrTooLarge.

func (*PrintCtx) Len

func (s *PrintCtx) Len() int

Len returns the number of bytes of the unread portion of the buffer; b.Len() == len(b.Bytes()).

func (*PrintCtx) Next

func (s *PrintCtx) Next(n int) []byte

Next returns a slice containing the next n bytes from the buffer, advancing the buffer as if the bytes had been returned by Read. If there are fewer than n bytes in the buffer, Next returns the entire buffer. The slice is only valid until the next call to a read or write method.

func (*PrintCtx) Read

func (s *PrintCtx) Read(p []byte) (n int, err error)

Read reads the next len(p) bytes from the buffer or until the buffer is drained. The return value n is the number of bytes read. If the buffer has no data to return, err is io.EOF (unless len(p) is zero); otherwise it is nil.

func (*PrintCtx) ReadByte

func (s *PrintCtx) ReadByte() (byte, error)

ReadByte reads and returns the next byte from the buffer. If no byte is available, it returns error io.EOF.

func (*PrintCtx) ReadBytes

func (s *PrintCtx) ReadBytes(delim byte) (line []byte, err error)

ReadBytes reads until the first occurrence of delim in the input, returning a slice containing the data up to and including the delimiter. If ReadBytes encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadBytes returns err != nil if and only if the returned data does not end in delim.

func (*PrintCtx) ReadFrom

func (s *PrintCtx) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom reads data from r until EOF and appends it to the buffer, growing the buffer as needed. The return value n is the number of bytes read. Any error except io.EOF encountered during the read is also returned. If the buffer becomes too large, ReadFrom will panic with ErrTooLarge.

func (*PrintCtx) ReadRune

func (s *PrintCtx) ReadRune() (r rune, size int, err error)

ReadRune reads and returns the next UTF-8-encoded Unicode code point from the buffer. If no bytes are available, the error returned is io.EOF. If the bytes are an erroneous UTF-8 encoding, it consumes one byte and returns U+FFFD, 1.

func (*PrintCtx) ReadString

func (s *PrintCtx) ReadString(delim byte) (line string, err error)

ReadString reads until the first occurrence of delim in the input, returning a string containing the data up to and including the delimiter. If ReadString encounters an error before finding a delimiter, it returns the data read before the error and the error itself (often io.EOF). ReadString returns err != nil if and only if the returned data does not end in delim.

func (*PrintCtx) Reset

func (s *PrintCtx) Reset()

Reset resets the buffer to be empty, but it retains the underlying storage for use by future writes. Reset is the same as Truncate(0).

func (*PrintCtx) String

func (s *PrintCtx) String() string

String returns the contents of the unread portion of the buffer as a string. If the Buffer is a nil pointer, it returns "<nil>".

To build strings more efficiently, see the strings.Builder type.

func (*PrintCtx) Truncate

func (s *PrintCtx) Truncate(n int)

Truncate discards all but the first n unread bytes from the buffer but continues to use the same allocated storage. It panics if n is negative or greater than the length of the buffer.

func (*PrintCtx) UnreadByte

func (s *PrintCtx) UnreadByte() error

UnreadByte unreads the last byte returned by the most recent successful read operation that read at least one byte. If a write has happened since the last read, if the last read returned an error, or if the read read zero bytes, UnreadByte returns an error.

func (*PrintCtx) UnreadRune

func (s *PrintCtx) UnreadRune() error

UnreadRune unreads the last rune returned by ReadRune. If the most recent read or write operation on the buffer was not a successful ReadRune, UnreadRune returns an error. (In this regard it is stricter than UnreadByte, which will unread the last byte from any read operation.)

func (*PrintCtx) Write

func (s *PrintCtx) Write(p []byte) (n int, err error)

Write appends the contents of p to the buffer, growing the buffer as needed. The return value n is the length of p; err is always nil. If the buffer becomes too large, Write will panic with ErrTooLarge.

func (*PrintCtx) WriteByte

func (s *PrintCtx) WriteByte(c byte) error

WriteByte appends the byte c to the buffer, growing the buffer as needed. The returned error is always nil, but is included to match bufio.Writer's WriteByte. If the buffer becomes too large, WriteByte will panic with ErrTooLarge.

func (*PrintCtx) WriteRune

func (s *PrintCtx) WriteRune(r rune) (n int, err error)

WriteRune appends the UTF-8 encoding of Unicode code point r to the buffer, returning its length and an error, which is always nil but is included to match bufio.Writer's WriteRune. The buffer is grown as needed; if it becomes too large, WriteRune will panic with ErrTooLarge.

func (*PrintCtx) WriteString

func (s *PrintCtx) WriteString(str string) (n int, err error)

WriteString appends the contents of s to the buffer, growing the buffer as needed. The return value n is the length of s; err is always nil. If the buffer becomes too large, WriteString will panic with ErrTooLarge.

func (*PrintCtx) WriteTo

func (s *PrintCtx) WriteTo(w io.Writer) (n int64, err error)

WriteTo writes data to w until the buffer is drained or an error occurs. The return value n is the number of bytes written; it always fits into an int, but it is int64 to match the io.WriterTo interface. Any error encountered during the write is also returned.

type Printer

type Printer interface {
	Panic(msg string, args ...any)   // error and panic
	Fatal(msg string, args ...any)   // error and os.Exit(-3)
	Error(msg string, args ...any)   // error
	Warn(msg string, args ...any)    // warning
	Info(msg string, args ...any)    // info. Attr, Attrs in args will be recognized as is
	Debug(msg string, args ...any)   // only for state.Env().InDebugging() or IsDebugBuild()
	Trace(msg string, args ...any)   // only for state.Env().InTracing()
	Verbose(msg string, args ...any) // only for -tags=verbose
	Print(msg string, args ...any)   // logging always
	Println(args ...any)             // synonym to Print, NOTE first elem of args decoded as msg here
	OK(msg string, args ...any)      // identify it is in OK mode
	Success(msg string, args ...any) // identify a successful operation done
	Fail(msg string, args ...any)    // identify a wrong occurs, default to stderr device
}

Printer supplies the printable apis

type PrinterWithContext

type PrinterWithContext interface {
	PanicContext(ctx context.Context, msg string, args ...any)   // error and panic
	FatalContext(ctx context.Context, msg string, args ...any)   // error and os.Exit(-3)
	ErrorContext(ctx context.Context, msg string, args ...any)   // error
	WarnContext(ctx context.Context, msg string, args ...any)    // warning
	InfoContext(ctx context.Context, msg string, args ...any)    // info. Attr, Attrs in args will be recognized as is
	DebugContext(ctx context.Context, msg string, args ...any)   // only for state.Env().InDebugging() or IsDebugBuild()
	TraceContext(ctx context.Context, msg string, args ...any)   // only for state.Env().InTracing()
	VerboseContext(ctx context.Context, msg string, args ...any) // only for -tags=verbose
	PrintContext(ctx context.Context, msg string, args ...any)   // logging always
	PrintlnContext(ctx context.Context, msg string, args ...any) // synonym to Print
	OKContext(ctx context.Context, msg string, args ...any)      // identify it is in OK mode
	SuccessContext(ctx context.Context, msg string, args ...any) // identify a successful operation done
	FailContext(ctx context.Context, msg string, args ...any)    // identify a wrong occurs, default to stderr device
}

PrinterWithContext supplies the printable apis with context.Context

type RegOpt

type RegOpt func(pack *regPack) // used by RegisterLevel

func RegWithColor

func RegWithColor(clr color.Color, bgColor ...color.Color) RegOpt

RegWithColor associates terminal color with the new level

func RegWithPrintToErrorDevice

func RegWithPrintToErrorDevice(b ...bool) RegOpt

RegWithPrintToErrorDevice declares the logging text should be redirected to stderr device.

For instance, you're declaring Swell Level, which should be treated as ErrorLevel, so the corresponding codes are:

const SwellLevel  = slog.Level(12) // Sometimes, you may use the value equal with slog.MaxLevel
slog.RegisterLevel(SwellLevel, "SWELL",
    slog.RegWithShortTags([6]string{"", "S", "SW", "SWL", "SWEL", "SWEEL"}),
    slog.RegWithColor(color.FgRed, color.BgBoldOrBright),
    slog.RegWithTreatedAsLevel(slog.ErrorLevel),
    slog.RegWithPrintToErrorDevice(),
)

After registered, slog.Log(ctx, SwellLevel, "xxx") will redirect the logging line to stderr device just like ErrorLevel.

func RegWithShortTags

func RegWithShortTags(shortTags [MaxLengthShortTag]string) RegOpt

RegWithShortTags associates short tag with the new level

func RegWithTreatedAsLevel

func RegWithTreatedAsLevel(treatAs Level) RegOpt

RegWithTreatedAsLevel associates the underlying level with the new level.

It means the new level acts as treatAs level.

For instance, see RegWithPrintToErrorDevice. After registered,

slog.Log(ctx, SwellLevel, "xxx")

will redirect the logging line to stderr device just like ErrorLevel.

type Slice

type Slice[T Integers | Uintegers | Floats] []T // Slice declares slice of numeric generic type

type Source

type Source struct {
	// Function is the package path-qualified function name containing the
	// source line. If non-empty, this string uniquely identifies a single
	// function in the program. This may be the empty string if not known.
	Function string `json:"function"`
	// File and Line are the file name and line number (1-based) of the source
	// line. These may be the empty string and zero, respectively, if not known.
	File string `json:"file"`
	Line int    `json:"line"`
}

Source describes the location of a line of source code.

type StringSlice

type StringSlice[T string] []T // StringSlice declares slice of string generic type

type Stringer

type Stringer interface {
	String() string
}

Stringer is a synonym to fmt.Stringer

type ToString

type ToString interface {
	ToString(args ...any) string
}

ToString interface for some object

type UintSlice

type UintSlice[T Uintegers] []T // UintSlice declares slice of unsigned integers generic type

type Uintegers

type Uintegers interface {
	uint | uint8 | uint16 | uint32 | uint64
}

Uintegers declares unsigned integers generic type

type ValueStringer

type ValueStringer interface {
	SetWriter(w io.Writer)
	WriteValue(value any)
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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