Documentation ¶
Index ¶
- Constants
- Variables
- func AddCodeHostingProviders(provider, repl string)
- func AddFlags(flagsToAdd ...Flags)
- func AddKnownPathMapping(pathname, repl string)
- func AddKnownPathRegexpMapping(pathnameRegexpExpr, repl string)
- func Debug(msg string, args ...any)
- func DebugContext(ctx context.Context, msg string, args ...any)
- func Error(msg string, args ...any)
- func ErrorContext(ctx context.Context, msg string, args ...any)
- func Fail(msg string, args ...any)
- func FailContext(ctx context.Context, msg string, args ...any)
- func Fatal(msg string, args ...any)
- func FatalContext(ctx context.Context, msg string, args ...any)
- func GetDefaultLoggersWriter() (wr io.Writer)
- func GetDefaultWriter() (wr io.Writer)
- func GetTtySize() (cols, rows int)
- func Info(msg string, args ...any)
- func InfoContext(ctx context.Context, msg string, args ...any)
- func IsAllBitsSet(f Flags) bool
- func IsAnsiEscaped(s string) bool
- func IsAnyBitsSet(f Flags) bool
- func IsColoredTty(w io.Writer) bool
- func IsTty(w io.Writer) bool
- func IsTtyEscaped(s string) bool
- func NewFileWriter(pathname string) *filewr
- func NewLogLogger(h Logger, lvl Level) *log.Logger
- func NewLogWriter(w io.Writer) *logwr
- func NewSlogHandler(logger Logger, config *HandlerOptions) logslog.Handler
- func OK(msg string, args ...any)
- func OKContext(ctx context.Context, msg string, args ...any)
- func Panic(msg string, args ...any)
- func PanicContext(ctx context.Context, msg string, args ...any)
- func Print(msg string, args ...any)
- func PrintContext(ctx context.Context, msg string, args ...any)
- func Println(args ...any)
- func PrintlnContext(ctx context.Context, msg string, args ...any)
- func ReadPassword() (text string, err error)
- func RegisterLevel(levelValue Level, title string, opts ...RegOpt) error
- func RemoveFlags(flagsToRemove ...Flags)
- func Reset()
- func ResetFlags()
- func ResetLevel()
- func SaveFlagsAndMod(addingFlags Flags, removingFlags ...Flags) (deferFn func())
- func SaveLevelAndSet(lvl Level) func()
- func SetDefault(l Logger)
- func SetFlags(f Flags)
- func SetLevel(lvl Level)
- func SetLevelColors(lvl Level, fg, bg color.Color)
- func SetLevelOutputWidth(width int)
- func SetMessageMinimalWidth(w int)
- func SetSkip(extraFrames int)
- func StripEscapes(str string) (strCleaned string)
- func Success(msg string, args ...any)
- func SuccessContext(ctx context.Context, msg string, args ...any)
- func Trace(msg string, args ...any)
- func TraceContext(ctx context.Context, msg string, args ...any)
- func Verbose(msg string, args ...any)
- func VerboseContext(ctx context.Context, msg string, args ...any)
- func Warn(msg string, args ...any)
- func WarnContext(ctx context.Context, msg string, args ...any)
- type ArrayMarshaller
- type Attr
- func Any(key string, val any) Attr
- func Bool(key string, val bool) Attr
- func Complex128(key string, val complex128) Attr
- func Complex64(key string, val complex64) Attr
- func Duration(key string, val time.Duration) Attr
- func Float32(key string, val float32) Attr
- func Float64(key string, val float64) Attr
- func Group(key string, args ...any) Attr
- func Int(key string, val int) Attr
- func Int16(key string, val int16) Attr
- func Int32(key string, val int32) Attr
- func Int64(key string, val int64) Attr
- func Int8(key string, val int8) Attr
- func NewAttr(key string, val any) Attr
- func NewGroupedAttr(key string, as ...Attr) Attr
- func NewGroupedAttrEasy(key string, as ...any) Attr
- func Numeric[T Numerics](key string, val T) Attr
- func String(key, val string) Attr
- func Time(key string, val time.Time) Attr
- func Uint(key string, val uint) Attr
- func Uint16(key string, val uint16) Attr
- func Uint32(key string, val uint32) Attr
- func Uint64(key string, val uint64) Attr
- func Uint8(key string, val uint8) Attr
- type Attrs
- type BasicLogger
- type BoolSlice
- type Builder
- type ComplexSlice
- type Complexes
- type Entries
- type Entry
- type Flags
- type FloatSlice
- type Floats
- type HandlerOptions
- type IntSlice
- type Integers
- type LWs
- type Level
- func (level Level) Enabled(ctx context.Context, testingLevel Level) bool
- func (level Level) MarshalJSON() ([]byte, error)
- func (level Level) MarshalText() ([]byte, error)
- func (level Level) ShortTag(length int) string
- func (level Level) String() string
- func (level *Level) UnmarshalJSON(text []byte) error
- func (level *Level) UnmarshalText(text []byte) error
- type LogLoggerAware
- type LogSlogAware
- type LogValuer
- type LogWriter
- type LogWriters
- type Logger
- type Numerics
- type ObjectMarshaller
- type ObjectSerializer
- type Opt
- func AddErrorWriter(wr io.Writer) Opt
- func AddLevelWriter(lvl Level, w io.Writer) Opt
- func AddWriter(wr io.Writer) Opt
- func RemoveLevelWriter(lvl Level, w io.Writer) Opt
- func ResetLevelWriter(lvl Level) Opt
- func ResetLevelWriters() Opt
- func ResetWriters() Opt
- func With(args ...any) Opt
- func WithAttrs(attrs ...Attr) Opt
- func WithAttrs1(attrs Attrs) Opt
- func WithColorMode(b ...bool) Opt
- func WithErrorWriter(wr io.Writer) Opt
- func WithJSONMode(b ...bool) Opt
- func WithLevel(lvl Level) Opt
- func WithTimeFormat(layout ...string) Opt
- func WithUTCMode(b ...bool) Opt
- func WithWriter(wr io.Writer) Opt
- type PrintCtx
- func (s *PrintCtx) AddBool(name string, value bool)
- func (s *PrintCtx) AddComplex128(name string, value complex128)
- func (s *PrintCtx) AddComplex64(name string, value complex64)
- func (s *PrintCtx) AddFloat32(name string, value float32)
- func (s *PrintCtx) AddFloat64(name string, value float64)
- func (s *PrintCtx) AddInt(name string, value int)
- func (s *PrintCtx) AddInt16(name string, value int16)
- func (s *PrintCtx) AddInt32(name string, value int32)
- func (s *PrintCtx) AddInt64(name string, value int64)
- func (s *PrintCtx) AddInt8(name string, value int8)
- func (s *PrintCtx) AddPrefixedInt(prefix, name string, value int)
- func (s *PrintCtx) AddPrefixedString(prefix, name string, value string)
- func (s *PrintCtx) AddRune(r rune)
- func (s *PrintCtx) AddString(name string, value string)
- func (s *PrintCtx) AddUint(name string, value uint)
- func (s *PrintCtx) AddUint16(name string, value uint16)
- func (s *PrintCtx) AddUint32(name string, value uint32)
- func (s *PrintCtx) AddUint64(name string, value uint64)
- func (s *PrintCtx) AddUint8(name string, value uint8)
- func (s *PrintCtx) AppendByte(value byte)
- func (s *PrintCtx) AppendBytes(value []byte)
- func (s *PrintCtx) AppendInt(val int)
- func (s *PrintCtx) AppendRune(value rune)
- func (s *PrintCtx) AppendRunes(value []rune)
- func (s *PrintCtx) Available() int
- func (s *PrintCtx) AvailableBuffer() []byte
- func (s *PrintCtx) Bytes() []byte
- func (s *PrintCtx) Cap() int
- func (s *PrintCtx) Grow(n int)
- func (s *PrintCtx) Len() int
- func (s *PrintCtx) Next(n int) []byte
- func (s *PrintCtx) Read(p []byte) (n int, err error)
- func (s *PrintCtx) ReadByte() (byte, error)
- func (s *PrintCtx) ReadBytes(delim byte) (line []byte, err error)
- func (s *PrintCtx) ReadFrom(r io.Reader) (n int64, err error)
- func (s *PrintCtx) ReadRune() (r rune, size int, err error)
- func (s *PrintCtx) ReadString(delim byte) (line string, err error)
- func (s *PrintCtx) Reset()
- func (s *PrintCtx) String() string
- func (s *PrintCtx) Truncate(n int)
- func (s *PrintCtx) UnreadByte() error
- func (s *PrintCtx) UnreadRune() error
- func (s *PrintCtx) Write(p []byte) (n int, err error)
- func (s *PrintCtx) WriteByte(c byte) error
- func (s *PrintCtx) WriteRune(r rune) (n int, err error)
- func (s *PrintCtx) WriteString(str string) (n int, err error)
- func (s *PrintCtx) WriteTo(w io.Writer) (n int64, err error)
- type Printer
- type PrinterWithContext
- type RegOpt
- type Slice
- type Source
- type StringSlice
- type Stringer
- type ToString
- type UintSlice
- type Uintegers
- type ValueStringer
Constants ¶
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 )
const BADKEY = "!BADKEY"
const MaxLengthShortTag = 6 // Level string length while formatting and printing
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.
const (
Version = "v0.5.23" // new Version of logg/slog
)
Variables ¶
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 DebugContext ¶
DebugContext with Default Logger.
func ErrorContext ¶
ErrorContext with Default Logger.
func FailContext ¶
FailContext with Default Logger.
func FatalContext ¶
FatalContext with Default Logger.
func GetDefaultLoggersWriter ¶
func GetDefaultWriter ¶
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 InfoContext ¶
InfoContext with Default Logger.
func IsAllBitsSet ¶
func IsAnsiEscaped ¶ added in v0.5.3
IsAnsiEscaped detects a string if it contains ansi color escaped sequences
func IsAnyBitsSet ¶
func IsColoredTty ¶
IsColoredTty detects a writer if it is a colorful tty device.
A colorful tty device can receive ANSI escaped sequences and draw its.
func IsTtyEscaped ¶
IsTtyEscaped detects a string if it contains ansi color escaped sequences
func NewFileWriter ¶
func NewFileWriter(pathname string) *filewr
func NewLogLogger ¶
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 NewSlogHandler ¶
func NewSlogHandler(logger Logger, config *HandlerOptions) logslog.Handler
NewSlogHandler makes a log/slog Handler to adapt into std slog.
func PanicContext ¶
PanicContext with Default Logger.
func PrintContext ¶
PrintContext with Default Logger.
func PrintlnContext ¶
PrintlnContext with Default Logger.
func ReadPassword ¶
ReadPassword reads the password from stdin with safe protection
func RegisterLevel ¶
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 ResetFlags ¶
func ResetFlags()
func ResetLevel ¶
func ResetLevel()
ResetLevel restore the default logger level to factory value (WarnLevel).
func SaveFlagsAndMod ¶
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 SetLevelColors ¶
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 StripEscapes ¶
StripEscapes removes any ansi color escaped sequences from a string
func SuccessContext ¶
SuccessContext with Default Logger.
func TraceContext ¶
TraceContext with Default Logger.
Types ¶
type ArrayMarshaller ¶
ArrayMarshaller to allow your slice or array object serialized by our PrintCtx
type Attr ¶
Attr for external adapters
func Complex128 ¶
func Complex128(key string, val complex128) Attr
func Group ¶
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 NewGroupedAttr ¶
func NewGroupedAttrEasy ¶
func String ¶
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.
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 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 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 ¶
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 )
type FloatSlice ¶
type FloatSlice[T Floats] []T // FloatSlice declares slice of 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 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 ParseLevel ¶
ParseLevel takes a string level and returns the Logrus log level constant.
func (Level) MarshalJSON ¶
func (Level) MarshalText ¶
MarshalText convert Level to string and []byte.
Available level names are:
- "disable"
- "fatal"
- "error"
- "warn"
- "info"
- "debug"
- ...
func (*Level) UnmarshalJSON ¶
func (*Level) UnmarshalText ¶
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 Logger ¶
type Logger interface { Entry }
Logger interface can be used for others logging kits or apps.
func New ¶
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:
- one or more element(s) with type Attr or Attrs
- one or more element(s) with type Opt
- 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 ObjectMarshaller ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 WithErrorWriter ¶ added in v0.5.11
func WithJSONMode ¶
func WithTimeFormat ¶
func WithUTCMode ¶
func WithWriter ¶
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 ¶
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 ¶
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) AddComplex128 ¶
func (s *PrintCtx) AddComplex128(name string, value complex128)
func (*PrintCtx) AddComplex64 ¶
func (*PrintCtx) AddFloat32 ¶
func (*PrintCtx) AddFloat64 ¶
func (*PrintCtx) AddPrefixedInt ¶
func (*PrintCtx) AddPrefixedString ¶
func (*PrintCtx) AppendByte ¶
func (*PrintCtx) AppendBytes ¶
func (*PrintCtx) AppendRune ¶
func (*PrintCtx) AppendRunes ¶
func (*PrintCtx) AvailableBuffer ¶
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 ¶
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 ¶
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 ¶
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 ¶
Len returns the number of bytes of the unread portion of the buffer; b.Len() == len(b.Bytes()).
func (*PrintCtx) Next ¶
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 ¶
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 ¶
ReadByte reads and returns the next byte from the buffer. If no byte is available, it returns error io.EOF.
func (*PrintCtx) ReadBytes ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
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 ¶
RegWithColor associates terminal color with the new level
func RegWithPrintToErrorDevice ¶
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 ¶
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 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 UintSlice ¶
type UintSlice[T Uintegers] []T // UintSlice declares slice of unsigned integers generic type