Documentation ¶
Index ¶
- Constants
- Variables
- func AttribFromContext[T Attrib](ctx context.Context, key string) (attrib T, ok bool)
- func ContextWithAttribs(ctx context.Context, attribs ...Attrib) context.Context
- func ContextWithLevelDecider(parent context.Context, decider LevelDecider) context.Context
- func ContextWithRequestID(ctx context.Context, requestID string) context.Context
- func ContextWithRequestUUID(ctx context.Context, requestID [16]byte) context.Context
- func ContextWithoutLogging(parent context.Context) context.Context
- func FormatUUID(id [16]byte) string
- func GetOrCreateRequestID(request *http.Request) string
- func GetOrCreateRequestUUID(request *http.Request) [16]byte
- func GetOrCreateRequestUUIDFromContext(ctx context.Context) [16]byte
- func GetRequestIDFromContext(ctx context.Context) string
- func GetRequestUUIDFromContext(ctx context.Context) (requestID [16]byte, ok bool)
- func HTTPMiddlewareFunc(logger *Logger, level Level, message string, onlyHeaders ...string) func(next http.Handler) http.Handler
- func HTTPMiddlewareHandler(next http.Handler, logger *Logger, level Level, message string, ...) http.Handler
- func IsActiveContext(ctx context.Context, level Level) bool
- func IsNilUUID(id [16]byte) bool
- func MustParseUUID(str string) [16]byte
- func NewUUID() [16]byte
- func ParseUUID(str string) (id [16]byte, err error)
- func RequestWithAttribs(request *http.Request, attribs ...Attrib) *http.Request
- func ValidateUUID(id [16]byte) error
- type Any
- type Attrib
- type Attribs
- func (a Attribs) AddToContext(ctx context.Context) context.Context
- func (a Attribs) AddToRequest(request *http.Request) *http.Request
- func (a Attribs) AppendUnique(b ...Attrib) Attribs
- func (a Attribs) Get(key string) Attrib
- func (a Attribs) Has(key string) bool
- func (a Attribs) Len() int
- func (a Attribs) Log(m *Message)
- type Bool
- type BoolLevelDecider
- type Bools
- type Colorizer
- type Config
- type DerivedConfig
- func (c *DerivedConfig) Debug() Level
- func (c *DerivedConfig) Error() Level
- func (c *DerivedConfig) Fatal() Level
- func (c *DerivedConfig) Info() Level
- func (c *DerivedConfig) IsActive(ctx context.Context, level Level) bool
- func (c *DerivedConfig) Levels() *Levels
- func (c *DerivedConfig) Parent() Config
- func (c *DerivedConfig) SetFilter(filters ...LevelFilter)
- func (c *DerivedConfig) SetParent(parent *Config)
- func (c *DerivedConfig) Trace() Level
- func (c *DerivedConfig) Warn() Level
- func (c *DerivedConfig) Writer() Writer
- type Error
- type Errors
- type Float
- type Floats
- type Format
- type Int
- type Ints
- type JSON
- type JSONWriter
- func (w *JSONWriter) BeginMessage(_ context.Context, logger *Logger, t time.Time, level Level, text string) Writer
- func (w *JSONWriter) CommitMessage()
- func (w *JSONWriter) FlushUnderlying()
- func (w *JSONWriter) String() string
- func (w *JSONWriter) WriteBool(val bool)
- func (w *JSONWriter) WriteError(val error)
- func (w *JSONWriter) WriteFloat(val float64)
- func (w *JSONWriter) WriteInt(val int64)
- func (w *JSONWriter) WriteJSON(val []byte)
- func (w *JSONWriter) WriteKey(key string)
- func (w *JSONWriter) WriteNil()
- func (w *JSONWriter) WriteSliceEnd()
- func (w *JSONWriter) WriteSliceKey(key string)
- func (w *JSONWriter) WriteString(val string)
- func (w *JSONWriter) WriteUUID(val [16]byte)
- func (w *JSONWriter) WriteUint(val uint64)
- type Level
- type LevelDecider
- type LevelFilter
- type LevelWriter
- func (w *LevelWriter) Func() func(format string, v ...any)
- func (w *LevelWriter) Print(v ...any)
- func (w *LevelWriter) Printf(format string, v ...any)
- func (w *LevelWriter) Println(v ...any)
- func (w *LevelWriter) StdLogger() *log.Logger
- func (w *LevelWriter) Write(data []byte) (int, error)
- func (w *LevelWriter) WriteMessage(ctx context.Context, msg string)
- type Levels
- func (l *Levels) CopyWithLeftPaddedNames() *Levels
- func (l *Levels) CopyWithRightPaddedNames() *Levels
- func (l *Levels) DebugName() string
- func (l *Levels) ErrorName() string
- func (l *Levels) FatalName() string
- func (l *Levels) HasName(level Level) bool
- func (l *Levels) InfoName() string
- func (l *Levels) LevelOfName(name string) Level
- func (l *Levels) LevelOfNameOrDefault(name string, defaultLevel Level) Level
- func (l *Levels) Name(level Level) string
- func (l *Levels) NameLenRange() (min, max int)
- func (l *Levels) TraceName() string
- func (l *Levels) WarnName() string
- type Loggable
- type LoggableFunc
- type Logger
- func (l *Logger) Attribs() Attribs
- func (l *Logger) Config() Config
- func (l *Logger) Debug(text string) *Message
- func (l *Logger) DebugCtx(ctx context.Context, text string) *Message
- func (l *Logger) DebugWriter() *LevelWriter
- func (l *Logger) Debugf(format string, args ...any) *Message
- func (l *Logger) DebugfCtx(ctx context.Context, format string, args ...any) *Message
- func (l *Logger) Error(text string) *Message
- func (l *Logger) ErrorCtx(ctx context.Context, text string) *Message
- func (l *Logger) ErrorWriter() *LevelWriter
- func (l *Logger) Errorf(format string, args ...any) *Message
- func (l *Logger) ErrorfCtx(ctx context.Context, format string, args ...any) *Message
- func (l *Logger) Fatal(text string) *Message
- func (l *Logger) FatalAndPanic(p any)
- func (l *Logger) FatalCtx(ctx context.Context, text string) *Message
- func (l *Logger) FatalWriter() *LevelWriter
- func (l *Logger) Fatalf(format string, args ...any) *Message
- func (l *Logger) FatalfCtx(ctx context.Context, format string, args ...any) *Message
- func (l *Logger) Flush()
- func (l *Logger) Info(text string) *Message
- func (l *Logger) InfoCtx(ctx context.Context, text string) *Message
- func (l *Logger) InfoWriter() *LevelWriter
- func (l *Logger) Infof(format string, args ...any) *Message
- func (l *Logger) InfofCtx(ctx context.Context, format string, args ...any) *Message
- func (l *Logger) IsActive(ctx context.Context, level Level) bool
- func (l *Logger) NewLevelWriter(level Level) *LevelWriter
- func (l *Logger) NewMessage(ctx context.Context, level Level, text string) *Message
- func (l *Logger) NewMessageAt(ctx context.Context, t time.Time, level Level, text string) *Message
- func (l *Logger) NewMessagef(ctx context.Context, level Level, format string, args ...any) *Message
- func (l *Logger) Prefix() string
- func (l *Logger) Trace(text string) *Message
- func (l *Logger) TraceCtx(ctx context.Context, text string) *Message
- func (l *Logger) TraceWriter() *LevelWriter
- func (l *Logger) Tracef(format string, args ...any) *Message
- func (l *Logger) TracefCtx(ctx context.Context, format string, args ...any) *Message
- func (l *Logger) Warn(text string) *Message
- func (l *Logger) WarnCtx(ctx context.Context, text string) *Message
- func (l *Logger) WarnWriter() *LevelWriter
- func (l *Logger) Warnf(format string, args ...any) *Message
- func (l *Logger) WarnfCtx(ctx context.Context, format string, args ...any) *Message
- func (l *Logger) With() *Message
- func (l *Logger) WithAttribs(perMessageAttribs ...Attrib) *Logger
- func (l *Logger) WithCtx(ctx context.Context) *Logger
- func (l *Logger) WithLevelFilter(filter LevelFilter) *Logger
- func (l *Logger) WithPrefix(prefix string) *Logger
- type Message
- func (m *Message) Any(key string, val any) *Message
- func (m *Message) AsJSON(key string, val any) *Message
- func (m *Message) Bool(key string, val bool) *Message
- func (m *Message) BoolPtr(key string, val *bool) *Message
- func (m *Message) Bools(key string, vals []bool) *Message
- func (m *Message) Bytes(key string, val []byte) *Message
- func (m *Message) CallStack(key string) *Message
- func (m *Message) CallStackSkip(key string, skip int) *Message
- func (m *Message) Ctx(ctx context.Context) *Message
- func (m *Message) Duration(key string, val time.Duration) *Message
- func (m *Message) DurationPtr(key string, val *time.Duration) *Message
- func (m *Message) Err(val error) *Message
- func (m *Message) Error(key string, val error) *Message
- func (m *Message) Errors(key string, vals []error) *Message
- func (m *Message) Exec(logFunc func(*Message)) *Message
- func (m *Message) Float(key string, val float64) *Message
- func (m *Message) Float32(key string, val float32) *Message
- func (m *Message) Float32Ptr(key string, val *float32) *Message
- func (m *Message) Float32s(key string, vals []float32) *Message
- func (m *Message) FloatPtr(key string, val *float64) *Message
- func (m *Message) Floats(key string, vals []float64) *Message
- func (m *Message) Int(key string, val int) *Message
- func (m *Message) Int16(key string, val int16) *Message
- func (m *Message) Int16Ptr(key string, val *int16) *Message
- func (m *Message) Int16s(key string, vals []int16) *Message
- func (m *Message) Int32(key string, val int32) *Message
- func (m *Message) Int32Ptr(key string, val *int32) *Message
- func (m *Message) Int32s(key string, vals []int32) *Message
- func (m *Message) Int64(key string, val int64) *Message
- func (m *Message) Int64Ptr(key string, val *int64) *Message
- func (m *Message) Int64s(key string, vals []int64) *Message
- func (m *Message) Int8(key string, val int8) *Message
- func (m *Message) Int8Ptr(key string, val *int8) *Message
- func (m *Message) Int8s(key string, vals []int8) *Message
- func (m *Message) IntPtr(key string, val *int) *Message
- func (m *Message) Ints(key string, vals []int) *Message
- func (m *Message) IsActive() bool
- func (m *Message) JSON(key string, val []byte) *Message
- func (m *Message) Log()
- func (m *Message) LogAndPanic()
- func (m *Message) Loggable(loggable Loggable) *Message
- func (m *Message) Nil(key string) *Message
- func (m *Message) Print(key string, vals ...any) *Message
- func (m *Message) Request(request *http.Request, onlyHeaders ...string) *Message
- func (m *Message) Str(key, val string) *Message
- func (m *Message) StrBytes(key string, val []byte) *Message
- func (m *Message) StrPtr(key string, val *string) *Message
- func (m *Message) Stringer(key string, val fmt.Stringer) *Message
- func (m *Message) Strs(key string, vals []string) *Message
- func (m *Message) StructFields(strct any) *Message
- func (m *Message) SubContext(ctx context.Context) context.Context
- func (m *Message) SubLogger() *Logger
- func (m *Message) SubLoggerContext(ctx context.Context) (subLogger *Logger, subContext context.Context)
- func (m *Message) TaggedStructFields(strct any, tag string) *Message
- func (m *Message) Time(key string, val time.Time) *Message
- func (m *Message) TimePtr(key string, val *time.Time) *Message
- func (m *Message) UUID(key string, val [16]byte) *Message
- func (m *Message) UUIDPtr(key string, val *[16]byte) *Message
- func (m *Message) UUIDs(key string, vals [][16]byte) *Message
- func (m *Message) Uint(key string, val uint) *Message
- func (m *Message) Uint16(key string, val uint16) *Message
- func (m *Message) Uint16Ptr(key string, val *uint16) *Message
- func (m *Message) Uint16s(key string, vals []uint16) *Message
- func (m *Message) Uint32(key string, val uint32) *Message
- func (m *Message) Uint32Ptr(key string, val *uint32) *Message
- func (m *Message) Uint32s(key string, vals []uint32) *Message
- func (m *Message) Uint64(key string, val uint64) *Message
- func (m *Message) Uint64Ptr(key string, val *uint64) *Message
- func (m *Message) Uint64s(key string, vals []uint64) *Message
- func (m *Message) Uint8(key string, val uint8) *Message
- func (m *Message) Uint8Ptr(key string, val *uint8) *Message
- func (m *Message) Uint8s(key string, vals []uint8) *Message
- func (m *Message) UintPtr(key string, val *uint) *Message
- func (m *Message) Uints(key string, vals []uint) *Message
- type MultiWriter
- func (m MultiWriter) BeginMessage(ctx context.Context, logger *Logger, t time.Time, level Level, text string) Writer
- func (m MultiWriter) CommitMessage()
- func (m MultiWriter) FlushUnderlying()
- func (m MultiWriter) String() string
- func (m MultiWriter) WriteBool(val bool)
- func (m MultiWriter) WriteError(val error)
- func (m MultiWriter) WriteFloat(val float64)
- func (m MultiWriter) WriteInt(val int64)
- func (m MultiWriter) WriteJSON(val []byte)
- func (m MultiWriter) WriteKey(key string)
- func (m MultiWriter) WriteNil()
- func (m MultiWriter) WriteSliceEnd()
- func (m MultiWriter) WriteSliceKey(key string)
- func (m MultiWriter) WriteString(val string)
- func (m MultiWriter) WriteUUID(val [16]byte)
- func (m MultiWriter) WriteUint(val uint64)
- type Nil
- type Registry
- func (r *Registry) AddPackageConfig(pkgName string, config *DerivedConfig) (pkgPath string)
- func (r *Registry) ConfigOrNilByPackageName(pkgName string) *DerivedConfig
- func (r *Registry) ConfigOrNilByPackagePath(pkgPath string) *DerivedConfig
- func (r *Registry) PackagesSortedByName() (paths, names []string)
- type String
- type Strings
- type StyledColorizer
- func (c *StyledColorizer) ColorizeError(str string) string
- func (c *StyledColorizer) ColorizeFalse(str string) string
- func (c *StyledColorizer) ColorizeFloat(str string) string
- func (c *StyledColorizer) ColorizeInt(str string) string
- func (c *StyledColorizer) ColorizeKey(str string) string
- func (c *StyledColorizer) ColorizeLevel(levels *Levels, level Level) string
- func (c *StyledColorizer) ColorizeMsg(str string) string
- func (c *StyledColorizer) ColorizeNil(str string) string
- func (c *StyledColorizer) ColorizeString(str string) string
- func (c *StyledColorizer) ColorizeTimestamp(str string) string
- func (c *StyledColorizer) ColorizeTrue(str string) string
- func (c *StyledColorizer) ColorizeUUID(str string) string
- func (c *StyledColorizer) ColorizeUint(str string) string
- type TextWriter
- func (w *TextWriter) BeginMessage(_ context.Context, logger *Logger, t time.Time, level Level, text string) Writer
- func (w *TextWriter) CommitMessage()
- func (w *TextWriter) FlushUnderlying()
- func (w *TextWriter) String() string
- func (w *TextWriter) WriteBool(val bool)
- func (w *TextWriter) WriteError(val error)
- func (w *TextWriter) WriteFloat(val float64)
- func (w *TextWriter) WriteInt(val int64)
- func (w *TextWriter) WriteJSON(val []byte)
- func (w *TextWriter) WriteKey(key string)
- func (w *TextWriter) WriteNil()
- func (w *TextWriter) WriteSliceEnd()
- func (w *TextWriter) WriteSliceKey(key string)
- func (w *TextWriter) WriteString(val string)
- func (w *TextWriter) WriteUUID(val [16]byte)
- func (w *TextWriter) WriteUint(val uint64)
- type UUID
- type UUIDs
- type Uint
- type Uints
- type Writer
Examples ¶
Constants ¶
const HTTPNoHeaders = "HTTPNoHeaders"
const NoColorizer noColorizer = 0
NoColorizer is a no-op Colorizer returning all strings unchanged
const NopWriter nopWriter = 0
NopWriter is a Writer that does nothing (no operation)
Variables ¶
var DefaultLevels = Levels{ Trace: -20, Debug: -10, Info: 0, Warn: 10, Error: 20, Fatal: 30, Names: map[Level]string{ -20: "TRACE", -10: "DEBUG", 0: "INFO", 10: "WARN", 20: "ERROR", 30: "FATAL", }, }
ErrorHandler will be called when an error occured while writing the logs. The default handler prints to stderr.
var FilterHTTPHeaders = map[string]struct{}{
"Authorization": {},
"Cookie": {},
}
FilterHTTPHeaders holds names of HTTP headers that should not be logged for requests. Defaults are "Authorization" and "Cookie".
var TrimCallStackPathPrefix = filePathPrefix()
TrimCallStackPathPrefix will be trimmed from the beginning of every call-stack file-path. Defaults to $GOPATH/src/ of the build environment or will be empty if go build gets called with -trimpath.
Functions ¶
func AttribFromContext ¶
AttribFromContext returns an attrib with a given key and type from a context or false for ok if no such attribute was added to the context.
func ContextWithAttribs ¶
ContextWithAttribs returns a context with the passed attribs added to it, overwriting any attribs with the same keys already added to the context.
The added attribs can be retrieved from the context with AttribsFromContext.
func ContextWithLevelDecider ¶
func ContextWithLevelDecider(parent context.Context, decider LevelDecider) context.Context
ContextWithLevelDecider returns a new context with the passed LevelDecider added to the parent. Logger methods with a context argument and known level will check if the passed context has a LevelDecider and call its IsActive method to decide if the following message should be logged. See also IsActiveContext.
LevelFilter implements LevelDecider and can be added directly to a context. Disable all levels below the default info configuration for a context:
ctx = golog.ContextWithLevelDecider(ctx, log.Levels.Info.FilterOutBelow())
func ContextWithRequestID ¶
ContextWithRequestID adds the passed requestID as string attribute with the key "requestID" to the context.
func ContextWithRequestUUID ¶
ContextWithRequestUUID adds the passed requestID as UUID attribute with the key "requestID" to the context.
func ContextWithoutLogging ¶
ContextWithoutLogging returns a new context with logging disabled for all levels.
func FormatUUID ¶
FormatUUID formats a UUID as 36 character standard string looking like "85692e8d-49bf-4150-a169-6c2adb93463c".
func GetOrCreateRequestID ¶
GetOrCreateRequestID gets a string from a http.Request or creates one as formatted random UUID. The X-Request-ID or X-Correlation-ID HTTP request header values will be returned if available, else a random v4 UUID will be returned formatted as string.
func GetOrCreateRequestUUID ¶
GetOrCreateRequestUUID gets a UUID from a http.Request or creates one. The X-Request-ID or X-Correlation-ID HTTP request headers will be parsed as UUID in the format "994d5800-afca-401f-9c2f-d9e3e106e9ef". If the request has no properly formatted ID, then a random v4 UUID will be returned.
func GetOrCreateRequestUUIDFromContext ¶
GetOrCreateRequestUUIDFromContext returns a UUID that was added to the context as UUID attribute with the key "requestID" If the context has no requestID attribute then a new random v4 UUID will be returned.
func GetRequestIDFromContext ¶
GetRequestIDFromContext returns a string that was added to the context as attribute with the key "requestID". If the context has no requestID attribute then and empty string will be returned.
func GetRequestUUIDFromContext ¶
GetRequestUUIDFromContext returns a UUID that was added to the context as UUID attribute with the key "requestID". If the context has no requestID attribute then false will be returned for ok.
func HTTPMiddlewareFunc ¶
func HTTPMiddlewareFunc(logger *Logger, level Level, message string, onlyHeaders ...string) func(next http.Handler) http.Handler
HTTPMiddlewareFunc returns a HTTP middleware function that passes through a UUID requestID. The requestID will be added as UUID Attrib to the http.Request before calling the next handler. If available the X-Request-ID or X-Correlation-ID HTTP request header will be used as requestID. It has to be a valid UUID in the format "994d5800-afca-401f-9c2f-d9e3e106e9ef". If the request has no requestID, then a random v4 UUID will be used. The requestID will also be set at the http.ResponseWriter as X-Request-ID header before calling the next handler, which has a chance to change it. If onlyHeaders are passed then only those headers are logged if available, or pass HTTPNoHeaders to disable header logging. To disable logging of the request at all and just pass through the requestID pass LevelInvalid as log level. Compatible with github.com/gorilla/mux.MiddlewareFunc. See also HTTPMiddlewareHandler.
func HTTPMiddlewareHandler ¶
func HTTPMiddlewareHandler(next http.Handler, logger *Logger, level Level, message string, onlyHeaders ...string) http.Handler
HTTPMiddlewareHandler returns a HTTP middleware handler that passes through a UUID requestID. The requestID will be added as UUID Attrib to the http.Request before calling the next handler. If available the X-Request-ID or X-Correlation-ID HTTP request header will be used as requestID. It has to be a valid UUID in the format "994d5800-afca-401f-9c2f-d9e3e106e9ef". If the request has no requestID, then a random v4 UUID will be used. The requestID will also be set at the http.ResponseWriter as X-Request-ID header before calling the next handler, which has a chance to change it. If onlyHeaders are passed then only those headers are logged if available, or pass HTTPNoHeaders to disable header logging. To disable logging of the request at all and just pass through the requestID pass LevelInvalid as log level. See also HTTPMiddlewareFunc.
func IsActiveContext ¶
IsActiveContext returns true by default except when a LevelDecider was added to the context using ContextWithLevelDecider, then the result of its IsActive method will be returned. It's valid to pass a nil context which will return true.
func MustParseUUID ¶
MustParseUUID parses a UUID string in the standard 36 character format like "85692e8d-49bf-4150-a169-6c2adb93463c" and panics on any error.
func ParseUUID ¶
ParseUUID parses a UUID string in the standard 36 character format like "85692e8d-49bf-4150-a169-6c2adb93463c".
func RequestWithAttribs ¶
RequestWithAttribs returns an http.Request with the Attribs added to its context, overwriting any attribs with the same keys already added to the request context.
func ValidateUUID ¶
ValidateUUID checks for valid version and variant of a binary UUID value.
Types ¶
type Any ¶
func (Any) GetValString ¶
type Attrib ¶
type Attrib interface { Loggable fmt.Stringer // GetKey returns the attribute key GetKey() string // GetVal returns the attribute value GetVal() any // GetValString returns the attribute value // formatted as string GetValString() string }
Attrib extends the Loggable interface and allows attributes to log themselves and be referenced by a key.
type Attribs ¶
type Attribs []Attrib
Attribs is a Attrib slice with methods to manage and log them. Usually only one Attrib with a given key is present in the slice, but this is not enforced. A slice is used instead of a map to preserve the order of attributes and to maximize allocation performance.
Attribs implements the Loggable interface by logging the attributes in the slice in the given order.
func AttribsFromContext ¶
AttribsFromContext returns the Attribs that were added to a context or nil.
func (Attribs) AddToContext ¶
AddToContext returns a context with the Attribs added to it, overwriting any attribs with the same keys already added to the context.
The added attribs can be retrieved from the context with AttribsFromContext.
func (Attribs) AddToRequest ¶
AddToRequest returns an http.Request with the Attribs added to its context, overwriting any attribs with the same keys already added to the request context.
func (Attribs) AppendUnique ¶
AppendUnique merges a and b so that keys are unique using attribs from a in case of identical keyed attribs in b.
The slices left and right will never be modified, in case of a merge the result is always a new slice.
func (Attribs) Get ¶
Get returns the first Attrib with the passed key or nil if not Attrib was found.
type Bool ¶
func (Bool) GetValString ¶
type BoolLevelDecider ¶
type BoolLevelDecider bool
BoolLevelDecider implements LevelDecider by always returning the underlying bool value from its IsActive method independent of the arguments.
type Bools ¶
func (Bools) GetValString ¶
type Colorizer ¶
type Colorizer interface { ColorizeMsg(string) string ColorizeTimestamp(string) string ColorizeLevel(*Levels, Level) string ColorizeKey(string) string ColorizeNil(string) string ColorizeTrue(string) string ColorizeFalse(string) string ColorizeInt(string) string ColorizeUint(string) string ColorizeFloat(string) string ColorizeString(string) string ColorizeError(string) string ColorizeUUID(string) string }
Colorizer enables styling strings for color terminals
type Config ¶
type DerivedConfig ¶
type DerivedConfig struct {
// contains filtered or unexported fields
}
DerivedConfig
func NewDerivedConfig ¶
func NewDerivedConfig(parent *Config, filters ...LevelFilter) *DerivedConfig
func (*DerivedConfig) Debug ¶
func (c *DerivedConfig) Debug() Level
func (*DerivedConfig) Error ¶
func (c *DerivedConfig) Error() Level
func (*DerivedConfig) Fatal ¶
func (c *DerivedConfig) Fatal() Level
func (*DerivedConfig) Info ¶
func (c *DerivedConfig) Info() Level
func (*DerivedConfig) IsActive ¶
func (c *DerivedConfig) IsActive(ctx context.Context, level Level) bool
func (*DerivedConfig) Levels ¶
func (c *DerivedConfig) Levels() *Levels
func (*DerivedConfig) Parent ¶
func (c *DerivedConfig) Parent() Config
func (*DerivedConfig) SetFilter ¶
func (c *DerivedConfig) SetFilter(filters ...LevelFilter)
func (*DerivedConfig) SetParent ¶
func (c *DerivedConfig) SetParent(parent *Config)
func (*DerivedConfig) Trace ¶
func (c *DerivedConfig) Trace() Level
func (*DerivedConfig) Warn ¶
func (c *DerivedConfig) Warn() Level
func (*DerivedConfig) Writer ¶
func (c *DerivedConfig) Writer() Writer
type Error ¶
func (Error) GetValString ¶
type Errors ¶
func (Errors) GetValString ¶
type Float ¶
func (Float) GetValString ¶
type Floats ¶
func (Floats) GetValString ¶
type Int ¶
func (Int) GetValString ¶
type Ints ¶
func (Ints) GetValString ¶
type JSONWriter ¶
type JSONWriter struct {
// contains filtered or unexported fields
}
Example ¶
format := &Format{ TimestampFormat: "2006-01-02 15:04:05", TimestampKey: "time", LevelKey: "level", MessageKey: "message", } formatter := NewJSONWriter(os.Stdout, format) config := NewConfig(&DefaultLevels, AllLevelsActive, formatter) log := NewLogger(config) // Use fixed time for reproducable example output at, _ := time.Parse("2006-01-02 15:04:05", "2006-01-02 15:04:05") log.NewMessageAt(context.Background(), at, config.Info(), "My log message"). Int("int", 66). Str("str", "Hello\tWorld!\n"). Log() log.NewMessageAt(context.Background(), at, config.Error(), "This is an error").Log()
Output: {"time":"2006-01-02 15:04:05","level":"INFO","message":"My log message","int":66,"str":"Hello\tWorld!\n"}, {"time":"2006-01-02 15:04:05","level":"ERROR","message":"This is an error"},
func NewJSONWriter ¶
func NewJSONWriter(writer io.Writer, format *Format) *JSONWriter
func (*JSONWriter) BeginMessage ¶
func (*JSONWriter) CommitMessage ¶
func (w *JSONWriter) CommitMessage()
func (*JSONWriter) FlushUnderlying ¶
func (w *JSONWriter) FlushUnderlying()
func (*JSONWriter) String ¶
func (w *JSONWriter) String() string
func (*JSONWriter) WriteBool ¶
func (w *JSONWriter) WriteBool(val bool)
func (*JSONWriter) WriteError ¶
func (w *JSONWriter) WriteError(val error)
func (*JSONWriter) WriteFloat ¶
func (w *JSONWriter) WriteFloat(val float64)
func (*JSONWriter) WriteInt ¶
func (w *JSONWriter) WriteInt(val int64)
func (*JSONWriter) WriteJSON ¶
func (w *JSONWriter) WriteJSON(val []byte)
func (*JSONWriter) WriteKey ¶
func (w *JSONWriter) WriteKey(key string)
func (*JSONWriter) WriteNil ¶
func (w *JSONWriter) WriteNil()
func (*JSONWriter) WriteSliceEnd ¶
func (w *JSONWriter) WriteSliceEnd()
func (*JSONWriter) WriteSliceKey ¶
func (w *JSONWriter) WriteSliceKey(key string)
func (*JSONWriter) WriteString ¶
func (w *JSONWriter) WriteString(val string)
func (*JSONWriter) WriteUUID ¶
func (w *JSONWriter) WriteUUID(val [16]byte)
func (*JSONWriter) WriteUint ¶
func (w *JSONWriter) WriteUint(val uint64)
type Level ¶
type Level int8
var GlobalPanicLevel Level = LevelInvalid
GlobalPanicLevel causes any log message with that level or higher to panic the message without formatted values after the complete log message has been written including values. The default value LevelInvalid disables this behaviour. Useful to catch any otherwise ignored warning or error messages in automated tests. Don't use in production.
func (Level) FilterOut ¶
func (l Level) FilterOut() LevelFilter
func (Level) FilterOutAbove ¶
func (l Level) FilterOutAbove() LevelFilter
func (Level) FilterOutAllOther ¶
func (l Level) FilterOutAllOther() LevelFilter
func (Level) FilterOutBelow ¶
func (l Level) FilterOutBelow() LevelFilter
type LevelDecider ¶
type LevelDecider interface { // IsActive returns if a Level is active together with a given context. // It's valid to pass a nil context. IsActive(context.Context, Level) bool }
LevelDecider is implemented to decide if a Level is active together with a given context.
type LevelFilter ¶
type LevelFilter uint64
LevelFilter is a bit mask filter for levels 0..63, where a set bit filters out and zero allows a log level.
const ( // AllLevelsActive allows all log levels. AllLevelsActive LevelFilter = 0 // AllLevelsInactive disabled all log levels. AllLevelsInactive LevelFilter = 0xFFFFFFFFFFFFFFFF )
func LevelFilterCombine ¶
func LevelFilterCombine(filters ...LevelFilter) LevelFilter
func LevelFilterOut ¶
func LevelFilterOut(level Level) LevelFilter
func LevelFilterOutAbove ¶
func LevelFilterOutAbove(level Level) LevelFilter
func LevelFilterOutAllOther ¶
func LevelFilterOutAllOther(level Level) LevelFilter
func LevelFilterOutBelow ¶
func LevelFilterOutBelow(level Level) LevelFilter
func (*LevelFilter) ActiveLevelNames ¶
func (f *LevelFilter) ActiveLevelNames(levels *Levels) []string
func (*LevelFilter) InactiveLevelNames ¶
func (f *LevelFilter) InactiveLevelNames(levels *Levels) []string
func (LevelFilter) IsActive ¶
func (f LevelFilter) IsActive(_ context.Context, level Level) bool
IsActive returns if the passed level is active or filtered out. The context argument is ignored and only there to implement the LevelDecider interface.
func (*LevelFilter) SetActive ¶
func (f *LevelFilter) SetActive(level Level, active bool)
type LevelWriter ¶
type LevelWriter struct {
// contains filtered or unexported fields
}
LevelWriter writes unstructured messages to a Logger with a fixed Level. It can be used as a shim/wrapper for third party packages that need a standard log.Logger, an io.Writer, or an an interface implementation with a Printf method.
func (*LevelWriter) Func ¶
func (w *LevelWriter) Func() func(format string, v ...any)
Func returns a function with the log.Printf call signature.
func (*LevelWriter) Print ¶
func (w *LevelWriter) Print(v ...any)
func (*LevelWriter) Printf ¶
func (w *LevelWriter) Printf(format string, v ...any)
func (*LevelWriter) Println ¶
func (w *LevelWriter) Println(v ...any)
func (*LevelWriter) StdLogger ¶
func (w *LevelWriter) StdLogger() *log.Logger
StdLogger returns a new log.Logger that writes to the LevelWriter. See https://golang.org/pkg/log/
func (*LevelWriter) Write ¶
func (w *LevelWriter) Write(data []byte) (int, error)
Write implements io.Writer
func (*LevelWriter) WriteMessage ¶
func (w *LevelWriter) WriteMessage(ctx context.Context, msg string)
WriteMessage writes a string message.
type Levels ¶
type Levels struct { Trace Level Debug Level Info Level Warn Level Error Level Fatal Level Names map[Level]string }
func (*Levels) CopyWithLeftPaddedNames ¶
func (*Levels) CopyWithRightPaddedNames ¶
func (*Levels) LevelOfName ¶
LevelOfName returns the level with a give name. If name is formatted as an integer and within [LevelMin..LevelMax] then a Level with that integer value will be returned. This is the inverse operation to what Levels.Name(unnamedLevel) returns. If there is no level with name or valid integer value then LevelInvalid will be returned.
func (*Levels) LevelOfNameOrDefault ¶
LevelOfNameOrDefault returns the level with a given name, or defaultLevel if the name is not in Levels.Names.
func (*Levels) Name ¶
Name returns the name of a level if available or the integer value of the level as string.
func (*Levels) NameLenRange ¶
type Loggable ¶
type Loggable interface { // Log the implementing type to a message Log(*Message) }
Loggable can be implemented to allow a type to log itself
type LoggableFunc ¶
type LoggableFunc func(*Message)
LoggableFunc implements Loggable with a function
func (LoggableFunc) Log ¶
func (f LoggableFunc) Log(m *Message)
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
func NewLogger ¶
NewLogger returns a Logger with the given config and per message attributes. If config is nil, then a nil Logger will be returned. A nil Logger is still valid to use but will not log anything. The passed perMessageAttribs will be repeated for every new log message.
func NewLoggerWithPrefix ¶
NewLogger returns a Logger with the given config, prefix, and per message attributes. If config is nil, then a nil Logger will be returned. A nil Logger is still valid to use but will not log anything. Every log message will begin with the passed prefix. The passed perMessageAttribs will be repeated for every new log message.
func (*Logger) Attribs ¶
Attribs returns the attributes that will be repeated for every message of the logger. See Logger.WithAttribs
func (*Logger) DebugWriter ¶
func (l *Logger) DebugWriter() *LevelWriter
func (*Logger) ErrorWriter ¶
func (l *Logger) ErrorWriter() *LevelWriter
func (*Logger) Errorf ¶
Errorf uses fmt.Errorf underneath to support Go 1.13 wrapped error formatting with %w
func (*Logger) ErrorfCtx ¶
ErrorfCtx uses fmt.Errorf underneath to support Go 1.13 wrapped error formatting with %w
func (*Logger) FatalAndPanic ¶
FatalAndPanic is a shortcut for Fatal(fmt.Sprint(p)).LogAndPanic()
func (*Logger) FatalWriter ¶
func (l *Logger) FatalWriter() *LevelWriter
func (*Logger) InfoWriter ¶
func (l *Logger) InfoWriter() *LevelWriter
func (*Logger) NewLevelWriter ¶
func (l *Logger) NewLevelWriter(level Level) *LevelWriter
func (*Logger) NewMessage ¶
NewMessage starts a new message
func (*Logger) NewMessageAt ¶
NewMessageAt starts a new message logged with the time t
func (*Logger) NewMessagef ¶
NewMessagef starts a new message formatted using fmt.Sprintf
func (*Logger) Prefix ¶
Prefix returns the prefix string that will be added in front over every log message of the logger. See Logger.WithPrefix
func (*Logger) TraceWriter ¶
func (l *Logger) TraceWriter() *LevelWriter
func (*Logger) WarnWriter ¶
func (l *Logger) WarnWriter() *LevelWriter
func (*Logger) With ¶
With returns a new Message that can be used to record the per message attribs for a sub-logger.
Example:
log := log.With().UUID("requestID", requestID).SubLogger()
func (*Logger) WithAttribs ¶
WithAttribs returns a new Logger with the passed perMessageAttribs merged with the existing perMessageAttribs. See Logger.Attribs and MergeAttribs
func (*Logger) WithCtx ¶
WithCtx returns a new sub Logger with the Attribs from the context add to if as per message values. Returns the logger unchanged if there were no Attribs added to the context.
func (*Logger) WithLevelFilter ¶
func (l *Logger) WithLevelFilter(filter LevelFilter) *Logger
WithLevelFilter returns a clone of the logger using the passed filter or returns nil if the logger was nil.
func (*Logger) WithPrefix ¶
WithPrefix returns a clone of the logger using the passed prefix or returns nil if the logger was nil. See Logger.Prefix
type Message ¶
type Message struct {
// contains filtered or unexported fields
}
func (*Message) Any ¶
Any logs val with the best matching typed log method or uses Print if none was found.
func (*Message) CallStack ¶
CallStack logs the current call stack as an error value with the passed key.
func (*Message) CallStackSkip ¶
CallStack logs the current call stack as an error value with the passed key, with skip number of top frames omitted.
func (*Message) Ctx ¶
Ctx logs any attribs that were added to the context and that are not already in the logger's attribs.
func (*Message) DurationPtr ¶
func (*Message) Log ¶
func (m *Message) Log()
Log writes the complete log message and returns the Message to a sync.Pool.
func (*Message) LogAndPanic ¶
func (m *Message) LogAndPanic()
LogAndPanic writes the complete log message and panics with the message text.
func (*Message) Print ¶
Print logs vals as string with the "%v" format of the fmt package. If only one value is passed for vals, then it will be logged as single string, else a slice of strings will be logged for vals.
func (*Message) Request ¶
Request logs a http.Request including values added to the request context. The following request values are logged: remote, method, uri, and contentLength only if available and greater than zero. If onlyHeaders are passed, then only those headers are logged if available, else all headers not in the package level FilterHTTPHeaders map will be logged. To disable header logging, pass an impossible header name.
func (*Message) StrBytes ¶
StrBytes logs the passed bytes as string if they are valid UTF-8, else the bytes are encoded using base64.RawURLEncoding.
func (*Message) StructFields ¶
StructFields calls Any(fieldName, fieldValue) for every exported struct field
func (*Message) SubContext ¶
SubContext returns a new context with recorded per message attribs added to the passed ctx argument.
func (*Message) SubLoggerContext ¶
func (m *Message) SubLoggerContext(ctx context.Context) (subLogger *Logger, subContext context.Context)
SubLoggerContext returns a new sub-logger with recorded per message attribs in addition to any attribs from the passed ctx, and a context with those attribs added to it.
func (*Message) TaggedStructFields ¶
TaggedStructFields calls Any(fieldTag, fieldValue) for every exported struct field that has the passed tag with the tag value not being empty or "-". Tag values are only considered until the first comma character, so `tag:"hello_world,omitempty"` will result in the fieldTag "hello_world". Fields with the following tags will be ignored: `tag:"-"`, `tag:""` `tag:",xxx"`.
func (*Message) Time ¶
Time logs a time.Time by calling its String method, or logs nil if val.IsZero().
func (*Message) TimePtr ¶
TimePtr logs a time.Time by calling its String method, or logs nil if val is nil or val.IsZero().
func (*Message) UUID ¶
UUID logs a UUID or nil in case of a "Nil UUID" containing only zero bytes. See IsNilUUID.
func (*Message) UUIDPtr ¶
UUIDPtr logs a UUID or nil in case of a nil pointer or a "Nil UUID" containing only zero bytes. See IsNilUUID.
type MultiWriter ¶
type MultiWriter []Writer
func (MultiWriter) BeginMessage ¶
func (MultiWriter) CommitMessage ¶
func (m MultiWriter) CommitMessage()
func (MultiWriter) FlushUnderlying ¶
func (m MultiWriter) FlushUnderlying()
func (MultiWriter) String ¶
func (m MultiWriter) String() string
func (MultiWriter) WriteBool ¶
func (m MultiWriter) WriteBool(val bool)
func (MultiWriter) WriteError ¶
func (m MultiWriter) WriteError(val error)
func (MultiWriter) WriteFloat ¶
func (m MultiWriter) WriteFloat(val float64)
func (MultiWriter) WriteInt ¶
func (m MultiWriter) WriteInt(val int64)
func (MultiWriter) WriteJSON ¶
func (m MultiWriter) WriteJSON(val []byte)
func (MultiWriter) WriteKey ¶
func (m MultiWriter) WriteKey(key string)
func (MultiWriter) WriteNil ¶
func (m MultiWriter) WriteNil()
func (MultiWriter) WriteSliceEnd ¶
func (m MultiWriter) WriteSliceEnd()
func (MultiWriter) WriteSliceKey ¶
func (m MultiWriter) WriteSliceKey(key string)
func (MultiWriter) WriteString ¶
func (m MultiWriter) WriteString(val string)
func (MultiWriter) WriteUUID ¶
func (m MultiWriter) WriteUUID(val [16]byte)
func (MultiWriter) WriteUint ¶
func (m MultiWriter) WriteUint(val uint64)
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
func (*Registry) AddPackageConfig ¶
func (r *Registry) AddPackageConfig(pkgName string, config *DerivedConfig) (pkgPath string)
func (*Registry) ConfigOrNilByPackageName ¶
func (r *Registry) ConfigOrNilByPackageName(pkgName string) *DerivedConfig
func (*Registry) ConfigOrNilByPackagePath ¶
func (r *Registry) ConfigOrNilByPackagePath(pkgPath string) *DerivedConfig
func (*Registry) PackagesSortedByName ¶
type String ¶
func (String) GetValString ¶
type Strings ¶
func (Strings) GetValString ¶
type StyledColorizer ¶
type StyledColorizer struct { MsgStyle termenv.Style OtherLevelStyle termenv.Style FatalLevelStyle termenv.Style ErrorLevelStyle termenv.Style WarnLevelStyle termenv.Style InfoLevelStyle termenv.Style DebugLevelStyle termenv.Style TraceLevelStyle termenv.Style TimespampStyle termenv.Style KeyStyle termenv.Style NilStyle termenv.Style TrueStyle termenv.Style FalseStyle termenv.Style IntStyle termenv.Style UintStyle termenv.Style FloatStyle termenv.Style StringStyle termenv.Style ErrorStyle termenv.Style UUIDStyle termenv.Style }
func (*StyledColorizer) ColorizeError ¶
func (c *StyledColorizer) ColorizeError(str string) string
func (*StyledColorizer) ColorizeFalse ¶
func (c *StyledColorizer) ColorizeFalse(str string) string
func (*StyledColorizer) ColorizeFloat ¶
func (c *StyledColorizer) ColorizeFloat(str string) string
func (*StyledColorizer) ColorizeInt ¶
func (c *StyledColorizer) ColorizeInt(str string) string
func (*StyledColorizer) ColorizeKey ¶
func (c *StyledColorizer) ColorizeKey(str string) string
func (*StyledColorizer) ColorizeLevel ¶
func (c *StyledColorizer) ColorizeLevel(levels *Levels, level Level) string
func (*StyledColorizer) ColorizeMsg ¶
func (c *StyledColorizer) ColorizeMsg(str string) string
func (*StyledColorizer) ColorizeNil ¶
func (c *StyledColorizer) ColorizeNil(str string) string
func (*StyledColorizer) ColorizeString ¶
func (c *StyledColorizer) ColorizeString(str string) string
func (*StyledColorizer) ColorizeTimestamp ¶
func (c *StyledColorizer) ColorizeTimestamp(str string) string
func (*StyledColorizer) ColorizeTrue ¶
func (c *StyledColorizer) ColorizeTrue(str string) string
func (*StyledColorizer) ColorizeUUID ¶
func (c *StyledColorizer) ColorizeUUID(str string) string
func (*StyledColorizer) ColorizeUint ¶
func (c *StyledColorizer) ColorizeUint(str string) string
type TextWriter ¶
type TextWriter struct {
// contains filtered or unexported fields
}
Example ¶
format := &Format{ TimestampFormat: "2006-01-02 15:04:05", TimestampKey: "time", LevelKey: "level", MessageKey: "message", } formatter := NewTextWriter(os.Stdout, format, NoColorizer) config := NewConfig(&DefaultLevels, AllLevelsActive, formatter) log := NewLogger(config) // Use fixed time for reproducable example output at, _ := time.Parse("2006-01-02 15:04:05", "2006-01-02 15:04:05") log.NewMessageAt(context.Background(), at, config.Info(), "My log message"). Int("int", 66). Str("str", "Hello\tWorld!\n"). Log() log.NewMessageAt(context.Background(), at, config.Error(), "Something went wrong!"). Err(errors.New("Multi\nLine\n\"Error\"")). Int("numberOfTheBeast", 666). Log()
Output: 2006-01-02 15:04:05 |INFO | My log message int=66 str="Hello\tWorld!\n" 2006-01-02 15:04:05 |ERROR| Something went wrong! error=` Multi Line "Error" ` numberOfTheBeast=666
func NewTextWriter ¶
func NewTextWriter(writer io.Writer, format *Format, colorizer Colorizer) *TextWriter
func (*TextWriter) BeginMessage ¶
func (*TextWriter) CommitMessage ¶
func (w *TextWriter) CommitMessage()
func (*TextWriter) FlushUnderlying ¶
func (w *TextWriter) FlushUnderlying()
func (*TextWriter) String ¶
func (w *TextWriter) String() string
func (*TextWriter) WriteBool ¶
func (w *TextWriter) WriteBool(val bool)
func (*TextWriter) WriteError ¶
func (w *TextWriter) WriteError(val error)
func (*TextWriter) WriteFloat ¶
func (w *TextWriter) WriteFloat(val float64)
func (*TextWriter) WriteInt ¶
func (w *TextWriter) WriteInt(val int64)
func (*TextWriter) WriteJSON ¶
func (w *TextWriter) WriteJSON(val []byte)
func (*TextWriter) WriteKey ¶
func (w *TextWriter) WriteKey(key string)
func (*TextWriter) WriteNil ¶
func (w *TextWriter) WriteNil()
func (*TextWriter) WriteSliceEnd ¶
func (w *TextWriter) WriteSliceEnd()
func (*TextWriter) WriteSliceKey ¶
func (w *TextWriter) WriteSliceKey(key string)
func (*TextWriter) WriteString ¶
func (w *TextWriter) WriteString(val string)
func (*TextWriter) WriteUUID ¶
func (w *TextWriter) WriteUUID(val [16]byte)
func (*TextWriter) WriteUint ¶
func (w *TextWriter) WriteUint(val uint64)
type UUID ¶
func (UUID) GetValString ¶
type UUIDs ¶
func (UUIDs) GetValString ¶
type Uint ¶
func (Uint) GetValString ¶
type Uints ¶
func (Uints) GetValString ¶
type Writer ¶
type Writer interface { // BeginMessage clones the Writer with its configuration for // writing a new message that must be finished with CommitMessage. // This method is only called for log levels that are active at the logger, // so implementations don't have to check the passed logger to decide // if they should log the passed level. // The logger is passed to give access to other data that might be needed // for message formatting like the prefix or level names. BeginMessage(ctx context.Context, logger *Logger, t time.Time, level Level, text string) Writer WriteKey(string) WriteSliceKey(string) WriteSliceEnd() WriteNil() WriteBool(bool) WriteInt(int64) WriteUint(uint64) WriteFloat(float64) WriteString(string) WriteError(error) WriteUUID([16]byte) WriteJSON([]byte) // CommitMessage flushes the current log message // to the underlying writer and frees any resources // to make the Writer ready for a new message. CommitMessage() // FlushUnderlying flushes underlying log writing // streams to make sure all messages have been // saved or transmitted. // This method is intended for special circumstances like // before exiting the application, it's not necessary // to call it for every message in addtion to CommitMessage. FlushUnderlying() // String is here only for debugging String() string }
Writer implementations write log messages in a certain message format to some underlying data stream. CommitMessage must be called before the Writer can be re-used for a new message.
Source Files ¶
- attrib.go
- attribs.go
- attribsrecorder.go
- callstack.go
- colorizer.go
- config.go
- context.go
- derivedconfig.go
- errorhandler.go
- filteredwriter.go
- format.go
- httpmiddleware.go
- jsonwriter.go
- level.go
- levelfilter.go
- levels.go
- levelwriter.go
- loggable.go
- logger.go
- message.go
- multiwriter.go
- nopwriter.go
- registry.go
- styledcolorizer.go
- textwriter.go
- uuid.go
- writer.go