rainbowlog

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2024 License: MIT Imports: 15 Imported by: 8

README

RainbowLog

Simple, configurable,structured Logging for Go.

RainbowLog's API is designed to provide both a great developer experience and stunning performance. Its unique chaining API allows rainbowlog to write JSON log events by avoiding allocations and reflection.

To keep the code base and the API simple, rainbowlog focuses on efficient structured logging only. Pretty logging on the console is made possible using the provided (but inefficient) rainbowlog.ConsolePacker.

pretty.png

Installation

go get -u github.com/rambollwong/rainbowlog

Getting Started

Use global logger
Use global logger by default options
package main

import (
	"github.com/rambollwong/rainbowlog/log"
)

func main() {
	log.UseDefault()

	log.Logger.Info().Msg("Hello world!").Done()
}

// Output: {"_TIME_":"2024-02-19 19:50:09.008","_LEVEL_":"INFO","_CALLER_":"/path/to/main.go:10","message":"Hello world!"}

Note: By default log writes to os.Stderr

Use global logger by rainbow default options
package main

import (
	"errors"

	"github.com/rambollwong/rainbowlog/log"
)

func main() {
	log.UseDefault()

	log.Logger.Info().Msg("Hello world!").Done()
	log.Logger.Debug().WithLabels("MODEL1").Msg("Something debugging...").Done()
	log.Logger.Warn().WithLabels("MODEL2", "SERVICE1").Msg("Something warning!").Int("IntegerValue", 888).Done()
	log.Logger.Error().Msg("failed to do something").Err(errors.New("something wrong")).Done()
	log.Logger.Fatal().Msg("fatal to do something").Done()
}

Output:

pretty.png

Use global logger by config file

RainbowLog supports setting logger options based on configuration files. If you want to use a configuration file, you need to ensure that the configuration file contains Rainbow Log configuration items. Rainbow Log supports configuration files in three formats: .yaml|.json|.toml. For specific configuration templates, see the corresponding files in the config package.

Assume that we have prepared a configuration file rainbowlog.yaml and placed it in the same directory as the execution file, then:

package main

import (
	"errors"

	"github.com/rambollwong/rainbowlog/log"
)

func main() {
	log.UseDefaultConfigFile()

	log.Logger.Info().Msg("Hello world!").Done()
	log.Logger.Debug().WithLabels("MODEL1").Msg("Something debugging...").Done()
	log.Logger.Warn().WithLabels("MODEL2", "SERVICE1").Msg("Something warning!").Int("IntegerValue", 888).Done()
	log.Logger.Error().Msg("failed to do something").Err(errors.New("something wrong")).Done()
	log.Logger.Fatal().Msg("fatal to do something").Done()
}

If you want to use a .json or .toml type configuration file, you only need to modify the log.DefaultConfigFileName, for example:

log.DefaultConfigFileName = "rainbowlog.json"

Or

log.DefaultConfigFileName = "rainbowlog.toml"

If you also want to specify the directory where the configuration file is located, you only need to modify log.DefaultConfigFilePath:

log.DefaultConfigFilePath = "/path/of/config/files"

Note: Modifying log.DefaultConfigFileName and log.DefaultConfigFilePath needs to be executed before log.UseDefaultConfigFile(), otherwise it will not take effect.

Use global logger by custom options

If you want to use custom options for Global logger, we have reserved the log.UseCustomOptions(opts ...Option) API for implementation. Supported Option is detailed in option.go.

Custom logger

If you don’t want to use Global logger, you can initialize a Logger instance through the New method. The New method receives the Option parameters. Supported Option is detailed in option.go.

package main

import (
	"errors"
	"path/filepath"

	"github.com/rambollwong/rainbowlog"
)

func main() {
	DefaultConfigFileName := "rainbowlog.yaml"
	DefaultConfigFilePath := "/path/of/config/files"

	logger := rainbowlog.New(
		rainbowlog.WithDefault(),
		rainbowlog.WithConfigFile(filepath.Join(DefaultConfigFilePath, DefaultConfigFileName)),
	)

	logger.Info().Msg("Hello world!").Done()
	logger.Debug().WithLabels("MODEL1").Msg("Something debugging...").Done()
	logger.Warn().WithLabels("MODEL2", "SERVICE1").Msg("Something warning!").Int("IntegerValue", 888).Done()
	logger.Error().Msg("failed to do something").Err(errors.New("something wrong")).Done()
	logger.Fatal().Msg("fatal to do something").Done()
}
SubLogger

SubLogger support allows you to create a logger instance that inherits from the parent logger and can reset some Option when needed. For example, a scenario where a LABEL different from the parent Logger is used in a submodule.

package main

import (
	"os"

	"github.com/rambollwong/rainbowlog"
	"github.com/rambollwong/rainbowlog/level"
)

func main() {
	logger := rainbowlog.New(
		rainbowlog.WithDefault(),
		rainbowlog.AppendsEncoderWriters(rainbowlog.JsonEnc, os.Stderr),
		rainbowlog.WithCallerMarshalFunc(nil),
		rainbowlog.WithLevel(level.Info),
		rainbowlog.WithLabels("ROOT"),
	)

	logger.Debug().Msg("Hello world!").Done()
	logger.Info().Msg("Hello world!").Done()

	subLogger := logger.SubLogger(
		rainbowlog.WithLevel(level.Debug),
		rainbowlog.WithLabels("SUBMODULE"),
	)

	subLogger.Debug().Msg("Hello world!").Done()
	subLogger.Info().Msg("Hello world!").Done()
}

// Output:
// {"_TIME_":"2024-02-21 11:28:02.150","_LEVEL_":"INFO","_LABEL_":"ROOT","message": "Hello world!"}
// {"_TIME_":"2024-02-21 11:28:02.150","_LEVEL_":"DEBUG","_LABEL_":"SUBMODULE","message":"Hello world!"}
// {"_TIME_":"2024-02-21 11:28:02.150","_LEVEL_":"INFO","_LABEL_":"SUBMODULE","message":"Hello world!"}

Modify time output format

The default time format of RainbowLog is 2006-01-02 15:04:05.000, you can modify this format through WithTimeFormat(timeFormat string) Option, the format can be a string that conforms to golang time formatting rules, it can also be UNIX or UNIXMS or UNIXMICRO or UNIXNANO, They respectively represent the return value of Unix() or UnixMilli() or UnixMicro() or UnixNano() which outputs time.Time.

package main

import (
	"os"

	"github.com/rambollwong/rainbowlog"
)

func main() {
	logger := rainbowlog.New(
		rainbowlog.WithDefault(),
		rainbowlog.AppendsEncoderWriters(rainbowlog.JsonEnc, os.Stderr),
		rainbowlog.WithTimeFormat(rainbowlog.TimeFormatUnix),
	)

	logger.Info().Msg("Hello world!").Done()
}

// Output:{"_TIME_":1708346689,"_LEVEL_":"INFO","_CALLER_":"main.go:16","message":"Hello world!"}
Hooks
package main

import (
	"fmt"
	"os"

	"github.com/rambollwong/rainbowlog"
	"github.com/rambollwong/rainbowlog/level"
)

func main() {
	var hook rainbowlog.HookFunc = func(r rainbowlog.Record, level level.Level, message string) {
		fmt.Printf("hook: %s, %s\n", level.String(), message)
	}
	logger := rainbowlog.New(
		rainbowlog.WithDefault(),
		rainbowlog.AppendsEncoderWriters(rainbowlog.JsonEnc, os.Stderr),
		rainbowlog.WithCallerMarshalFunc(nil),
		rainbowlog.AppendsHooks(hook),
		rainbowlog.WithLevel(level.Info),
	)

	logger.Debug().Msg("Hello world!").Done()
	logger.Info().Msg("Hello world!").Done()
}

// Output: 
// hook: info, Hello world!
// {"_TIME_":"2024-02-21 11:42:17.592","_LEVEL_":"INFO","message":"Hello world!"}
More

Of course, we also provide more features and functions, looking forward to your exploration and discovery!

Documentation

Index

Examples

Constants

View Source
const (
	// TimeFormatUnix defines a time format that makes time fields to be
	// serialized as Unix timestamp integers.
	TimeFormatUnix = "UNIX"

	// TimeFormatUnixMs defines a time format that makes time fields to be
	// serialized as Unix timestamp integers in milliseconds.
	TimeFormatUnixMs = "UNIXMS"

	// TimeFormatUnixMicro defines a time format that makes time fields to be
	// serialized as Unix timestamp integers in microseconds.
	TimeFormatUnixMicro = "UNIXMICRO"

	// TimeFormatUnixNano defines a time format that makes time fields to be
	// serialized as Unix timestamp integers in nanoseconds.
	TimeFormatUnixNano = "UNIXNANO"
)
View Source
const (
	ColorBold          = 1
	ColorUnderline     = 4
	ColorStrikeThrough = 9
	ColorUnderlineBold = 21
)
View Source
const (
	ColorBlack = iota + 30
	ColorRed
	ColorGreen
	ColorYellow
	ColorBlue
	ColorMagenta
	ColorCyan
	ColorPale
)
View Source
const (
	ColorBgBlack = iota + 40
	ColorBgRed
	ColorBgGreen
	ColorBgYellow
	ColorBgBlue
	ColorBgMagenta
	ColorBgCyan
	ColorBgPale
)
View Source
const (
	ColorHlBlack = iota + 90
	ColorHlRed
	ColorHlGreen
	ColorHlYellow
	ColorHlBlue
	ColorHlMagenta
	ColorHlCyan
	ColorHlPale
)
View Source
const (
	ColorHlBgBlack = iota + 100
	ColorHlBgRed
	ColorHlBgGreen
	ColorHlBgYellow
	ColorHlBgBlue
	ColorHlBgMagenta
	ColorHlBgCyan
	ColorHlBgPale
)
View Source
const (
	DefaultLevel        = level.Debug
	DefaultLabel        = ""
	DefaultConsolePrint = false
	DefaultConsoleColor = true
)

Variables

View Source
var (
	// MsgFieldName is the field name for core message.
	MsgFieldName = "message"
	// ErrFieldName is the field name for err.
	ErrFieldName = "error"
	// ErrStackFieldName is the field name for err stack.
	ErrStackFieldName = "stack"

	MetaTimeFieldName   = "_TIME_"
	MetaCallerFieldName = "_CALLER_"
	MetaLevelFieldName  = "_LEVEL_"
	MetaLabelFieldName  = "_LABEL_"

	GlobalDurationValueUseInt = false

	DefaultStack = false

	// ErrorHandler will be called whenever some error threw when logger working.
	// If not set, the error will be printed on the stderr.
	// This handler must be thread safe and non-blocking.
	ErrorHandler = func(err error) {
		fmt.Fprintf(os.Stderr, "rainbowlog: error found: %v\n", err)
	}

	GlobalTimeFormat = "2006-01-02 15:04:05.000"

	GlobalLevelFieldMarshalFunc LevelFieldMarshalFunc = func(l level.Level) string {
		return strings.ToUpper(l.String())
	}

	// CallerSkipFrameCount is the number of stack frames to skip to find the caller.
	CallerSkipFrameCount = 0

	// GlobalCallerMarshalFunc allows customization of global caller marshaling.
	GlobalCallerMarshalFunc CallerMarshalFunc = func(file string, line int) string {
		return file + ":" + strconv.Itoa(line)
	}

	// GlobalErrorMarshalFunc allows customization of global error marshaling.
	GlobalErrorMarshalFunc ErrorMarshalFunc = func(err error) string {
		if err == nil {
			return ""
		}
		return err.Error()
	}

	// GlobalErrorStackMarshalFunc extract the stack from err if any.
	GlobalErrorStackMarshalFunc ErrorStackMarshalFunc = func(err error) any {
		return nil
	}

	TimestampFunc = func() time.Time {
		return time.Now()
	}

	GlobalEncoderParseFunc EncoderParseFunc = func(encoder string) Encoder {
		switch strings.ToLower(encoder) {
		case "json":
			return JsonEnc
		case "txt", "text":
			return TextEnc
		default:
			panic("unsupported encoder: " + encoder)
		}
	}
)
View Source
var NewTextEncoder = func(metaKeys ...string) Encoder {
	return encoder.TextEncoder{MetaKeys: metaKeys}
}

Functions

func SyncWriter

func SyncWriter(w io.Writer) io.Writer

SyncWriter wraps writer so that each call to Write is synchronized with a mutex. This syncer can be used to wrap the call to writer's Write method if it is not thread safe. Note that you do not need this wrapper for os.File Write operations on POSIX and Windows systems as they are already thread-safe.

Types

type CallerMarshalFunc

type CallerMarshalFunc func(file string, line int) string

type ConsolePacker

type ConsolePacker struct {
	RecordPackerForWriter
	// contains filtered or unexported fields
}

func (*ConsolePacker) Any added in v0.0.4

func (j *ConsolePacker) Any(key string, i any)

func (*ConsolePacker) Bytes added in v0.0.4

func (j *ConsolePacker) Bytes(key string, val []byte)

func (*ConsolePacker) Done

func (j *ConsolePacker) Done()

func (*ConsolePacker) Dur added in v0.0.4

func (j *ConsolePacker) Dur(key string, unit, val time.Duration)

func (*ConsolePacker) Durs added in v0.0.4

func (j *ConsolePacker) Durs(key string, unit time.Duration, vals ...time.Duration)

func (*ConsolePacker) Err

func (j *ConsolePacker) Err(err error)

func (*ConsolePacker) Float32 added in v0.0.4

func (j *ConsolePacker) Float32(key string, val float32)

func (*ConsolePacker) Float32s added in v0.0.4

func (j *ConsolePacker) Float32s(key string, vals ...float32)

func (*ConsolePacker) Float64 added in v0.0.4

func (j *ConsolePacker) Float64(key string, val float64)

func (*ConsolePacker) Float64s added in v0.0.4

func (j *ConsolePacker) Float64s(key string, vals ...float64)

func (*ConsolePacker) Hex added in v0.0.4

func (j *ConsolePacker) Hex(key string, val []byte)

func (*ConsolePacker) IPAddr added in v0.0.4

func (j *ConsolePacker) IPAddr(key string, ip net.IP)

func (*ConsolePacker) IPPrefix added in v0.0.4

func (j *ConsolePacker) IPPrefix(key string, pfx net.IPNet)

func (*ConsolePacker) Int added in v0.0.4

func (j *ConsolePacker) Int(key string, val int)

func (*ConsolePacker) Int16 added in v0.0.4

func (j *ConsolePacker) Int16(key string, val int16)

func (*ConsolePacker) Int16s added in v0.0.4

func (j *ConsolePacker) Int16s(key string, vals ...int16)

func (*ConsolePacker) Int32 added in v0.0.4

func (j *ConsolePacker) Int32(key string, val int32)

func (*ConsolePacker) Int32s added in v0.0.4

func (j *ConsolePacker) Int32s(key string, vals ...int32)

func (*ConsolePacker) Int64 added in v0.0.4

func (j *ConsolePacker) Int64(key string, val int64)

func (*ConsolePacker) Int64s added in v0.0.4

func (j *ConsolePacker) Int64s(key string, vals ...int64)

func (*ConsolePacker) Int8 added in v0.0.4

func (j *ConsolePacker) Int8(key string, val int8)

func (*ConsolePacker) Int8s added in v0.0.4

func (j *ConsolePacker) Int8s(key string, vals ...int8)

func (*ConsolePacker) Ints added in v0.0.4

func (j *ConsolePacker) Ints(key string, vals ...int)

func (*ConsolePacker) MACAddr added in v0.0.4

func (j *ConsolePacker) MACAddr(key string, ha net.HardwareAddr)

func (*ConsolePacker) Msg

func (j *ConsolePacker) Msg(msg string)

func (*ConsolePacker) Str added in v0.0.4

func (j *ConsolePacker) Str(key, val string)

func (*ConsolePacker) Stringer added in v0.0.4

func (j *ConsolePacker) Stringer(key string, val fmt.Stringer)

func (*ConsolePacker) Stringers added in v0.0.4

func (j *ConsolePacker) Stringers(key string, vals ...fmt.Stringer)

func (*ConsolePacker) Strs added in v0.0.4

func (j *ConsolePacker) Strs(key string, vals ...string)

func (*ConsolePacker) Time added in v0.0.4

func (j *ConsolePacker) Time(key, fmt string, val time.Time)

func (*ConsolePacker) Times added in v0.0.4

func (j *ConsolePacker) Times(key, fmt string, vals ...time.Time)

func (*ConsolePacker) Uint added in v0.0.4

func (j *ConsolePacker) Uint(key string, val uint)

func (*ConsolePacker) Uint16 added in v0.0.4

func (j *ConsolePacker) Uint16(key string, val uint16)

func (*ConsolePacker) Uint16s added in v0.0.4

func (j *ConsolePacker) Uint16s(key string, vals ...uint16)

func (*ConsolePacker) Uint32 added in v0.0.4

func (j *ConsolePacker) Uint32(key string, val uint32)

func (*ConsolePacker) Uint32s added in v0.0.4

func (j *ConsolePacker) Uint32s(key string, vals ...uint32)

func (*ConsolePacker) Uint64 added in v0.0.4

func (j *ConsolePacker) Uint64(key string, val uint64)

func (*ConsolePacker) Uint64s added in v0.0.4

func (j *ConsolePacker) Uint64s(key string, vals ...uint64)

func (*ConsolePacker) Uint8 added in v0.0.4

func (j *ConsolePacker) Uint8(key string, val uint8)

func (*ConsolePacker) Uint8s added in v0.0.4

func (j *ConsolePacker) Uint8s(key string, vals ...uint8)

func (*ConsolePacker) Uints added in v0.0.4

func (j *ConsolePacker) Uints(key string, vals ...uint)

type Encoder

type Encoder interface {
	BeginMarker(dst []byte) []byte
	BlankSpace(dst []byte) []byte
	Bool(dst []byte, val bool) []byte
	Bytes(dst []byte, s []byte) []byte
	Comma(dst []byte) []byte
	Delim(dst []byte) []byte
	Duration(dst []byte, unit time.Duration, useInt bool, d time.Duration) []byte
	EndMarker(dst []byte) []byte
	Float32(dst []byte, val float32) []byte
	Float64(dst []byte, val float64) []byte
	Hex(dst []byte, s []byte) []byte
	IPAddr(dst []byte, ip net.IP) []byte
	IPPrefix(dst []byte, pfx net.IPNet) []byte
	Int(dst []byte, val int) []byte
	Int16(dst []byte, val int16) []byte
	Int32(dst []byte, val int32) []byte
	Int64(dst []byte, val int64) []byte
	Int8(dst []byte, val int8) []byte
	Interface(dst []byte, i interface{}) []byte
	Key(dst []byte, key string) []byte
	LineBreak(dst []byte) []byte
	MACAddr(dst []byte, ha net.HardwareAddr) []byte
	Nil(dst []byte) []byte
	ObjectData(dst []byte, o []byte) []byte
	String(dst []byte, s string) []byte
	Time(dst []byte, format string, t time.Time) []byte
	Uint(dst []byte, val uint) []byte
	Uint16(dst []byte, val uint16) []byte
	Uint32(dst []byte, val uint32) []byte
	Uint64(dst []byte, val uint64) []byte
	Uint8(dst []byte, val uint8) []byte
	MetaEnd(dst []byte) []byte
	// contains filtered or unexported methods
}
var JsonEnc Encoder = encoder.JsonEncoder{}
var TextEnc Encoder = encoder.TextEncoder{
	MetaKeys: defaultMetaKeys().Keys(),
}

type EncoderParseFunc

type EncoderParseFunc func(encoder string) Encoder

type ErrorMarshalFunc

type ErrorMarshalFunc func(err error) string

type ErrorStackMarshalFunc

type ErrorStackMarshalFunc func(err error) any

type Hook

type Hook interface {
	// RunHook runs the hook with the event.
	RunHook(r Record, level level.Level, message string)
}

Hook defines an interface to a Record hook.

type HookFunc

type HookFunc func(r Record, level level.Level, message string)

HookFunc is an adaptor to allow the use of an ordinary function as a Hook.

func (HookFunc) RunHook

func (hf HookFunc) RunHook(r Record, level level.Level, message string)

RunHook implements the Hook interface.

type LevelFieldMarshalFunc

type LevelFieldMarshalFunc func(level.Level) string

type LevelHook

type LevelHook struct {
	NoneLevelHook, TraceHook, DebugHook, InfoHook, WarnHook, ErrorHook, FatalHook, PanicHook Hook
}

LevelHook applies a different hook for each level.

func NewLevelHook

func NewLevelHook() LevelHook

func (LevelHook) RunHook

func (lh LevelHook) RunHook(r Record, lv level.Level, message string)

RunHook implements the Hook interface.

type LevelWriter

type LevelWriter interface {
	io.Writer
	WriteLevel(level level.Level, bz []byte) (n int, err error)
}

LevelWriter defines as interface a writer may implement in order to receive level information with payload.

func LevelWriterAdapter

func LevelWriterAdapter(writer io.Writer) LevelWriter

func MultiLevelWriter

func MultiLevelWriter(writers ...io.Writer) LevelWriter

MultiLevelWriter creates a writer that duplicates its writes to all the provided writers, similar to the Unix tee(1) command. If some writers implement LevelWriter, their WriteLevel method will be used instead of Write.

type LogRecord added in v0.0.4

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

LogRecord represents a log Record. It is finalized by the Done method. Done method also writes the encoded bytes to the writer.

func (*LogRecord) Any added in v0.0.4

func (r *LogRecord) Any(key string, i any) Record

func (*LogRecord) Bytes added in v0.0.4

func (r *LogRecord) Bytes(key string, val []byte) Record

func (*LogRecord) Discard added in v0.0.4

func (r *LogRecord) Discard() Record

Discard disables the Record that it won't be printed.

func (*LogRecord) Done added in v0.0.4

func (r *LogRecord) Done()

Done finish appending data and writing Record.

NOTICE: once this method is called, the *Record should be disposed. Calling Done twice can have unexpected result.

func (*LogRecord) Dur added in v0.0.4

func (r *LogRecord) Dur(key string, unit, val time.Duration) Record

func (*LogRecord) Durs added in v0.0.4

func (r *LogRecord) Durs(key string, unit time.Duration, vals ...time.Duration) Record

func (*LogRecord) Err added in v0.0.4

func (r *LogRecord) Err(err error) Record

Err sets the given err to the error field when err is not nil。 NOTICE: This method should only be called once。 Calling multiple times may cause unpredictable results。

func (*LogRecord) Float32 added in v0.0.4

func (r *LogRecord) Float32(key string, val float32) Record

func (*LogRecord) Float32s added in v0.0.4

func (r *LogRecord) Float32s(key string, vals ...float32) Record

func (*LogRecord) Float64 added in v0.0.4

func (r *LogRecord) Float64(key string, val float64) Record

func (*LogRecord) Float64s added in v0.0.4

func (r *LogRecord) Float64s(key string, vals ...float64) Record

func (*LogRecord) Hex added in v0.0.4

func (r *LogRecord) Hex(key string, val []byte) Record

func (*LogRecord) IPAddr added in v0.0.4

func (r *LogRecord) IPAddr(key string, ip net.IP) Record

func (*LogRecord) IPPrefix added in v0.0.4

func (r *LogRecord) IPPrefix(key string, pfx net.IPNet) Record

func (*LogRecord) Int added in v0.0.4

func (r *LogRecord) Int(key string, val int) Record

func (*LogRecord) Int16 added in v0.0.4

func (r *LogRecord) Int16(key string, val int16) Record

func (*LogRecord) Int16s added in v0.0.4

func (r *LogRecord) Int16s(key string, vals ...int16) Record

func (*LogRecord) Int32 added in v0.0.4

func (r *LogRecord) Int32(key string, val int32) Record

func (*LogRecord) Int32s added in v0.0.4

func (r *LogRecord) Int32s(key string, vals ...int32) Record

func (*LogRecord) Int64 added in v0.0.4

func (r *LogRecord) Int64(key string, val int64) Record

func (*LogRecord) Int64s added in v0.0.4

func (r *LogRecord) Int64s(key string, vals ...int64) Record

func (*LogRecord) Int8 added in v0.0.4

func (r *LogRecord) Int8(key string, val int8) Record

func (*LogRecord) Int8s added in v0.0.4

func (r *LogRecord) Int8s(key string, vals ...int8) Record

func (*LogRecord) Ints added in v0.0.4

func (r *LogRecord) Ints(key string, vals ...int) Record

func (*LogRecord) MACAddr added in v0.0.4

func (r *LogRecord) MACAddr(key string, ha net.HardwareAddr) Record

func (*LogRecord) Msg added in v0.0.4

func (r *LogRecord) Msg(msg string) Record

Msg adds the msg as the message field if not empty. NOTICE: This method should only be called once。 Calling multiple times may cause unpredictable results。

func (*LogRecord) Msgf added in v0.0.4

func (r *LogRecord) Msgf(format string, v ...interface{}) Record

Msgf adds the formatted msg as the message field if not empty.

func (*LogRecord) Reset added in v0.0.4

func (r *LogRecord) Reset()

Reset the Record instance. This should be called before the Record is used again.

func (*LogRecord) Str added in v0.0.4

func (r *LogRecord) Str(key, val string) Record

func (*LogRecord) Stringer added in v0.0.4

func (r *LogRecord) Stringer(key string, val fmt.Stringer) Record

func (*LogRecord) Stringers added in v0.0.4

func (r *LogRecord) Stringers(key string, vals ...fmt.Stringer) Record

func (*LogRecord) Strs added in v0.0.4

func (r *LogRecord) Strs(key string, vals ...string) Record

func (*LogRecord) Time added in v0.0.4

func (r *LogRecord) Time(key, format string, val time.Time) Record

func (*LogRecord) Times added in v0.0.4

func (r *LogRecord) Times(key, format string, vals ...time.Time) Record

func (*LogRecord) Uint added in v0.0.4

func (r *LogRecord) Uint(key string, val uint) Record

func (*LogRecord) Uint16 added in v0.0.4

func (r *LogRecord) Uint16(key string, val uint16) Record

func (*LogRecord) Uint16s added in v0.0.4

func (r *LogRecord) Uint16s(key string, vals ...uint16) Record

func (*LogRecord) Uint32 added in v0.0.4

func (r *LogRecord) Uint32(key string, val uint32) Record

func (*LogRecord) Uint32s added in v0.0.4

func (r *LogRecord) Uint32s(key string, vals ...uint32) Record

func (*LogRecord) Uint64 added in v0.0.4

func (r *LogRecord) Uint64(key string, val uint64) Record

func (*LogRecord) Uint64s added in v0.0.4

func (r *LogRecord) Uint64s(key string, vals ...uint64) Record

func (*LogRecord) Uint8 added in v0.0.4

func (r *LogRecord) Uint8(key string, val uint8) Record

func (*LogRecord) Uint8s added in v0.0.4

func (r *LogRecord) Uint8s(key string, vals ...uint8) Record

func (*LogRecord) Uints added in v0.0.4

func (r *LogRecord) Uints(key string, vals ...uint) Record

func (*LogRecord) UseIntDur added in v0.0.4

func (r *LogRecord) UseIntDur() Record

UseIntDur enables the calculation of Duration to retain only integer digits.

func (*LogRecord) WithCallerSkip added in v0.0.4

func (r *LogRecord) WithCallerSkip(skip int) Record

WithCallerSkip adds skip frames when calling caller.

func (*LogRecord) WithDoneFunc added in v0.0.4

func (r *LogRecord) WithDoneFunc(f func(msg string)) Record

func (*LogRecord) WithLabels added in v0.0.4

func (r *LogRecord) WithLabels(label ...string) Record

WithLabels sets the labels for the Logger using one or more strings. The labels are joined using the "|" separator.

func (*LogRecord) WithLevel added in v0.0.4

func (r *LogRecord) WithLevel(lv level.Level) Record

WithLevel sets the level as the META_LEVEL field.

type Logger

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

Logger is the rainbow-log structure. This is the main entrance of rainbow log.

func New

func New(opts ...Option) *Logger

New creates a new *Logger with options optional.

Example
package main

import (
	"os"

	"github.com/rambollwong/rainbowlog"
)

func main() {
	log := rainbowlog.New(
		rainbowlog.AppendsEncoderWriters(rainbowlog.JsonEnc, os.Stdout),
		rainbowlog.WithMetaKeys(rainbowlog.MetaLevelFieldName, rainbowlog.MsgFieldName),
	)
	log.Info().Msg("Hello world!").Done()

	log2 := rainbowlog.New(
		rainbowlog.AppendsEncoderWriters(rainbowlog.TextEnc, os.Stdout),
		rainbowlog.WithMetaKeys(rainbowlog.MetaLevelFieldName, rainbowlog.MsgFieldName))
	log2.Debug().Msg("Hello world!").Done()

}
Output:

{"_LEVEL_":"INFO","message":"Hello world!"}
DEBUG > Hello world!

func (*Logger) Debug

func (l *Logger) Debug() Record

Debug create a new Record with debug level setting.

func (*Logger) Error

func (l *Logger) Error() Record

Error create a new Record with error level setting.

func (*Logger) Fatal

func (l *Logger) Fatal() Record

Fatal create a new Record with fatal level setting.

func (*Logger) Info

func (l *Logger) Info() Record

Info create a new Record with info level setting.

Example
package main

import (
	"os"

	"github.com/rambollwong/rainbowlog"
)

func main() {
	log := rainbowlog.New(
		rainbowlog.AppendsEncoderWriters(rainbowlog.JsonEnc, os.Stdout),
		rainbowlog.WithMetaKeys(rainbowlog.MetaLevelFieldName),
	)
	log.Info().Msg("Hello world!").Done()

}
Output:

{"_LEVEL_":"INFO","message":"Hello world!"}

func (*Logger) Level

func (l *Logger) Level(le level.Level) Record

Level create a new Record with the logger level given.

func (*Logger) Panic

func (l *Logger) Panic() Record

Panic create a new Record with panic level setting.

func (*Logger) Record

func (l *Logger) Record() Record

Record create a new Record with basic.

Example
package main

import (
	"os"

	"github.com/rambollwong/rainbowlog"
	"github.com/rambollwong/rainbowlog/level"
)

func main() {
	log := rainbowlog.New(
		rainbowlog.AppendsEncoderWriters(rainbowlog.JsonEnc, os.Stdout),
		rainbowlog.WithMetaKeys(rainbowlog.MetaLevelFieldName),
	)
	log.Record().WithLevel(level.Info).Msg("Hello world!").Done()
	log.Record().WithLevel(level.Debug).Msg("Hello world!").Done()

}
Output:

{"_LEVEL_":"INFO","message":"Hello world!"}
{"_LEVEL_":"DEBUG","message":"Hello world!"}

func (*Logger) SubLogger

func (l *Logger) SubLogger(opts ...Option) *Logger

SubLogger creates a new *Logger that inherit from parent logger. Optional options for sub logger also be supported.

Example
package main

import (
	"os"

	"github.com/rambollwong/rainbowlog"
)

func main() {
	log := rainbowlog.New(rainbowlog.AppendsEncoderWriters(rainbowlog.JsonEnc, os.Stdout))

	subLog := log.SubLogger(
		rainbowlog.WithMetaKeys(rainbowlog.MetaLabelFieldName),
		rainbowlog.WithLabels("NewLabel"),
	)
	subLog.Info().Msg("Hello world!").Done()
}
Output:

{"_LABEL_":"NewLabel","message":"Hello world!"}

func (*Logger) Warn

func (l *Logger) Warn() Record

Warn create a new Record with warn level setting.

type NewRecordFunc

type NewRecordFunc func() Record

type NilRecord added in v0.0.4

type NilRecord struct {
}

func (*NilRecord) Any added in v0.0.4

func (n *NilRecord) Any(key string, i any) Record

func (*NilRecord) Bytes added in v0.0.4

func (n *NilRecord) Bytes(key string, val []byte) Record

func (*NilRecord) Discard added in v0.0.4

func (n *NilRecord) Discard() Record

func (*NilRecord) Done added in v0.0.4

func (n *NilRecord) Done()

func (*NilRecord) Dur added in v0.0.4

func (n *NilRecord) Dur(key string, unit time.Duration, val time.Duration) Record

func (*NilRecord) Durs added in v0.0.4

func (n *NilRecord) Durs(key string, unit time.Duration, vals ...time.Duration) Record

func (*NilRecord) Err added in v0.0.4

func (n *NilRecord) Err(err error) Record

func (*NilRecord) Float32 added in v0.0.4

func (n *NilRecord) Float32(key string, val float32) Record

func (*NilRecord) Float32s added in v0.0.4

func (n *NilRecord) Float32s(key string, vals ...float32) Record

func (*NilRecord) Float64 added in v0.0.4

func (n *NilRecord) Float64(key string, val float64) Record

func (*NilRecord) Float64s added in v0.0.4

func (n *NilRecord) Float64s(key string, vals ...float64) Record

func (*NilRecord) Hex added in v0.0.4

func (n *NilRecord) Hex(key string, val []byte) Record

func (*NilRecord) IPAddr added in v0.0.4

func (n *NilRecord) IPAddr(key string, ip net.IP) Record

func (*NilRecord) IPPrefix added in v0.0.4

func (n *NilRecord) IPPrefix(key string, pfx net.IPNet) Record

func (*NilRecord) Int added in v0.0.4

func (n *NilRecord) Int(key string, val int) Record

func (*NilRecord) Int16 added in v0.0.4

func (n *NilRecord) Int16(key string, val int16) Record

func (*NilRecord) Int16s added in v0.0.4

func (n *NilRecord) Int16s(key string, vals ...int16) Record

func (*NilRecord) Int32 added in v0.0.4

func (n *NilRecord) Int32(key string, val int32) Record

func (*NilRecord) Int32s added in v0.0.4

func (n *NilRecord) Int32s(key string, vals ...int32) Record

func (*NilRecord) Int64 added in v0.0.4

func (n *NilRecord) Int64(key string, val int64) Record

func (*NilRecord) Int64s added in v0.0.4

func (n *NilRecord) Int64s(key string, vals ...int64) Record

func (*NilRecord) Int8 added in v0.0.4

func (n *NilRecord) Int8(key string, val int8) Record

func (*NilRecord) Int8s added in v0.0.4

func (n *NilRecord) Int8s(key string, vals ...int8) Record

func (*NilRecord) Ints added in v0.0.4

func (n *NilRecord) Ints(key string, vals ...int) Record

func (*NilRecord) MACAddr added in v0.0.4

func (n *NilRecord) MACAddr(key string, ha net.HardwareAddr) Record

func (*NilRecord) Msg added in v0.0.4

func (n *NilRecord) Msg(msg string) Record

func (*NilRecord) Msgf added in v0.0.4

func (n *NilRecord) Msgf(format string, v ...interface{}) Record

func (*NilRecord) Reset added in v0.0.4

func (n *NilRecord) Reset()

func (*NilRecord) Str added in v0.0.4

func (n *NilRecord) Str(key string, val string) Record

func (*NilRecord) Stringer added in v0.0.4

func (n *NilRecord) Stringer(key string, val fmt.Stringer) Record

func (*NilRecord) Stringers added in v0.0.4

func (n *NilRecord) Stringers(key string, vals ...fmt.Stringer) Record

func (*NilRecord) Strs added in v0.0.4

func (n *NilRecord) Strs(key string, vals ...string) Record

func (*NilRecord) Time added in v0.0.4

func (n *NilRecord) Time(key string, format string, val time.Time) Record

func (*NilRecord) Times added in v0.0.4

func (n *NilRecord) Times(key string, format string, vals ...time.Time) Record

func (*NilRecord) Uint added in v0.0.4

func (n *NilRecord) Uint(key string, val uint) Record

func (*NilRecord) Uint16 added in v0.0.4

func (n *NilRecord) Uint16(key string, val uint16) Record

func (*NilRecord) Uint16s added in v0.0.4

func (n *NilRecord) Uint16s(key string, vals ...uint16) Record

func (*NilRecord) Uint32 added in v0.0.4

func (n *NilRecord) Uint32(key string, val uint32) Record

func (*NilRecord) Uint32s added in v0.0.4

func (n *NilRecord) Uint32s(key string, vals ...uint32) Record

func (*NilRecord) Uint64 added in v0.0.4

func (n *NilRecord) Uint64(key string, val uint64) Record

func (*NilRecord) Uint64s added in v0.0.4

func (n *NilRecord) Uint64s(key string, vals ...uint64) Record

func (*NilRecord) Uint8 added in v0.0.4

func (n *NilRecord) Uint8(key string, val uint8) Record

func (*NilRecord) Uint8s added in v0.0.4

func (n *NilRecord) Uint8s(key string, vals ...uint8) Record

func (*NilRecord) Uints added in v0.0.4

func (n *NilRecord) Uints(key string, vals ...uint) Record

func (*NilRecord) UseIntDur added in v0.0.4

func (n *NilRecord) UseIntDur() Record

func (*NilRecord) WithCallerSkip added in v0.0.4

func (n *NilRecord) WithCallerSkip(skip int) Record

func (*NilRecord) WithDoneFunc added in v0.0.4

func (n *NilRecord) WithDoneFunc(f func(msg string)) Record

func (*NilRecord) WithLabels added in v0.0.4

func (n *NilRecord) WithLabels(label ...string) Record

func (*NilRecord) WithLevel added in v0.0.4

func (n *NilRecord) WithLevel(lv level.Level) Record

type Option

type Option func(logger *Logger)

Option defines logger options for custom using.

func AppendsEncoderWriters

func AppendsEncoderWriters(encoder Encoder, writers ...io.Writer) Option

AppendsEncoderWriters appends writers who use a same encoder to logger.

func AppendsHooks

func AppendsHooks(hooks ...Hook) Option

AppendsHooks appends hooks to logger.

func WithCallerMarshalFunc

func WithCallerMarshalFunc(callerMarshalFunc CallerMarshalFunc) Option

WithCallerMarshalFunc sets the CallerMarshalFunc for logger. If MetaCallerFieldName has been set by WithMetaKeys option (if WithMetaKeys is not appended, MetaCallerFieldName is set by default), CallerMarshalFunc will be invoked when printing logs.

func WithConfig

func WithConfig(config config.LoggerConfig) Option

WithConfig sets the Logger's properties according to the provided configuration parameters. If the Enable field in the configuration is false, the logger level will be set Disabled. Normally, the WithDefault() option should be set before calling this option.

func WithConfigFile

func WithConfigFile(configFile string) Option

WithConfigFile loads the log configuration from the specified configuration file, sets the properties of the Logger according to the configuration parameters. If an error occurs while loading the configuration file, trigger a panic.

func WithConsolePrint

func WithConsolePrint(enable bool) Option

WithConsolePrint sets whether enable printing to console.

func WithDefault

func WithDefault() Option

WithDefault sets default configurations to logger. If you use this option, please put it at the top of all options, otherwise it may overwrite the modified configuration as the default.

func WithErrorMarshalFunc

func WithErrorMarshalFunc(errorMarshalFunc ErrorMarshalFunc) Option

WithErrorMarshalFunc sets the ErrorMarshalFunc for logger. If Record.Err() has been invoked, ErrorMarshalFunc will be invoked when printing logs. The marshal result string will be used as the value of error key field.

func WithErrorStackMarshalFunc

func WithErrorStackMarshalFunc(errorStackMarshalFunc ErrorStackMarshalFunc) Option

WithErrorStackMarshalFunc sets the ErrorStackMarshalFunc for logger.

func WithLabels added in v0.0.2

func WithLabels(labels ...string) Option

WithLabels sets the labels for the Logger using one or more strings. The labels are joined using the "|" separator and assigned to the Logger's label property.

func WithLevel

func WithLevel(lv level.Level) Option

WithLevel sets logger level.

func WithLevelFieldMarshalFunc

func WithLevelFieldMarshalFunc(levelFieldMarshalFunc LevelFieldMarshalFunc) Option

WithLevelFieldMarshalFunc sets the LevelFieldMarshalFunc for logger. LevelFieldMarshalFunc will be invoked when printing logs, then the result string will be used as the value of level key field.

func WithMetaKeyColors

func WithMetaKeyColors(key string, colors ...int) Option

WithMetaKeyColors sets an ANSI code of color for printing the meta key.

NOTICE: MetaKeyColors only useful for console printing if rainbow console enabled. Colors defined in globals.go

func WithMetaKeys

func WithMetaKeys(keys ...string) Option

WithMetaKeys sets meta key field names for each Record. Meta keys data will be placed at the front of the Record.

func WithRainbowConsole

func WithRainbowConsole(enable bool) Option

WithRainbowConsole sets whether enable rainbow printing on console. This option is useful only when ConsolePrint enabled.

func WithStack

func WithStack(enable bool) Option

WithStack enables recording stack or not.

func WithTimeFormat

func WithTimeFormat(timeFormat string) Option

WithTimeFormat sets the format of time for logger printing.

type Record

type Record interface {
	WithLabels(label ...string) Record
	WithLevel(lv level.Level) Record
	WithDoneFunc(f func(msg string)) Record
	WithCallerSkip(skip int) Record
	UseIntDur() Record
	Reset()
	Discard() Record
	Done()
	Msg(msg string) Record
	Msgf(format string, v ...interface{}) Record
	Err(err error) Record
	Str(key string, val string) Record
	Strs(key string, vals ...string) Record
	Stringer(key string, val fmt.Stringer) Record
	Stringers(key string, vals ...fmt.Stringer) Record
	Bytes(key string, val []byte) Record
	Hex(key string, val []byte) Record
	Int(key string, val int) Record
	Ints(key string, vals ...int) Record
	Int8(key string, val int8) Record
	Int8s(key string, vals ...int8) Record
	Int16(key string, val int16) Record
	Int16s(key string, vals ...int16) Record
	Int32(key string, val int32) Record
	Int32s(key string, vals ...int32) Record
	Int64(key string, val int64) Record
	Int64s(key string, vals ...int64) Record
	Uint(key string, val uint) Record
	Uints(key string, vals ...uint) Record
	Uint8(key string, val uint8) Record
	Uint8s(key string, vals ...uint8) Record
	Uint16(key string, val uint16) Record
	Uint16s(key string, vals ...uint16) Record
	Uint32(key string, val uint32) Record
	Uint32s(key string, vals ...uint32) Record
	Uint64(key string, val uint64) Record
	Uint64s(key string, vals ...uint64) Record
	Float32(key string, val float32) Record
	Float32s(key string, vals ...float32) Record
	Float64(key string, val float64) Record
	Float64s(key string, vals ...float64) Record
	Time(key string, format string, val time.Time) Record
	Times(key string, format string, vals ...time.Time) Record
	Dur(key string, unit time.Duration, val time.Duration) Record
	Durs(key string, unit time.Duration, vals ...time.Duration) Record
	Any(key string, i any) Record
	IPAddr(key string, ip net.IP) Record
	IPPrefix(key string, pfx net.IPNet) Record
	MACAddr(key string, ha net.HardwareAddr) Record
}

type RecordPackerForWriter

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

func (*RecordPackerForWriter) Any added in v0.0.2

func (j *RecordPackerForWriter) Any(key string, i any)

func (*RecordPackerForWriter) Bytes

func (j *RecordPackerForWriter) Bytes(key string, val []byte)

func (*RecordPackerForWriter) CallerSkip

func (j *RecordPackerForWriter) CallerSkip(skip int)

func (*RecordPackerForWriter) Done

func (j *RecordPackerForWriter) Done()

func (*RecordPackerForWriter) Dur

func (j *RecordPackerForWriter) Dur(key string, unit, val time.Duration)

func (*RecordPackerForWriter) Durs

func (j *RecordPackerForWriter) Durs(key string, unit time.Duration, vals ...time.Duration)

func (*RecordPackerForWriter) Err

func (j *RecordPackerForWriter) Err(err error)

func (*RecordPackerForWriter) Float32

func (j *RecordPackerForWriter) Float32(key string, val float32)

func (*RecordPackerForWriter) Float32s

func (j *RecordPackerForWriter) Float32s(key string, vals ...float32)

func (*RecordPackerForWriter) Float64

func (j *RecordPackerForWriter) Float64(key string, val float64)

func (*RecordPackerForWriter) Float64s

func (j *RecordPackerForWriter) Float64s(key string, vals ...float64)

func (*RecordPackerForWriter) Hex

func (j *RecordPackerForWriter) Hex(key string, val []byte)

func (*RecordPackerForWriter) IPAddr

func (j *RecordPackerForWriter) IPAddr(key string, ip net.IP)

func (*RecordPackerForWriter) IPPrefix

func (j *RecordPackerForWriter) IPPrefix(key string, pfx net.IPNet)

func (*RecordPackerForWriter) Int

func (j *RecordPackerForWriter) Int(key string, val int)

func (*RecordPackerForWriter) Int16

func (j *RecordPackerForWriter) Int16(key string, val int16)

func (*RecordPackerForWriter) Int16s

func (j *RecordPackerForWriter) Int16s(key string, vals ...int16)

func (*RecordPackerForWriter) Int32

func (j *RecordPackerForWriter) Int32(key string, val int32)

func (*RecordPackerForWriter) Int32s

func (j *RecordPackerForWriter) Int32s(key string, vals ...int32)

func (*RecordPackerForWriter) Int64

func (j *RecordPackerForWriter) Int64(key string, val int64)

func (*RecordPackerForWriter) Int64s

func (j *RecordPackerForWriter) Int64s(key string, vals ...int64)

func (*RecordPackerForWriter) Int8

func (j *RecordPackerForWriter) Int8(key string, val int8)

func (*RecordPackerForWriter) Int8s

func (j *RecordPackerForWriter) Int8s(key string, vals ...int8)

func (*RecordPackerForWriter) Ints

func (j *RecordPackerForWriter) Ints(key string, vals ...int)

func (*RecordPackerForWriter) MACAddr

func (j *RecordPackerForWriter) MACAddr(key string, ha net.HardwareAddr)

func (*RecordPackerForWriter) Msg

func (j *RecordPackerForWriter) Msg(msg string)

func (*RecordPackerForWriter) Reset

func (j *RecordPackerForWriter) Reset()

func (*RecordPackerForWriter) Str

func (j *RecordPackerForWriter) Str(key, val string)

func (*RecordPackerForWriter) Stringer

func (j *RecordPackerForWriter) Stringer(key string, val fmt.Stringer)

func (*RecordPackerForWriter) Stringers

func (j *RecordPackerForWriter) Stringers(key string, vals ...fmt.Stringer)

func (*RecordPackerForWriter) Strs

func (j *RecordPackerForWriter) Strs(key string, vals ...string)

func (*RecordPackerForWriter) Time

func (j *RecordPackerForWriter) Time(key, fmt string, val time.Time)

func (*RecordPackerForWriter) Times

func (j *RecordPackerForWriter) Times(key, fmt string, vals ...time.Time)

func (*RecordPackerForWriter) Uint

func (j *RecordPackerForWriter) Uint(key string, val uint)

func (*RecordPackerForWriter) Uint16

func (j *RecordPackerForWriter) Uint16(key string, val uint16)

func (*RecordPackerForWriter) Uint16s

func (j *RecordPackerForWriter) Uint16s(key string, vals ...uint16)

func (*RecordPackerForWriter) Uint32

func (j *RecordPackerForWriter) Uint32(key string, val uint32)

func (*RecordPackerForWriter) Uint32s

func (j *RecordPackerForWriter) Uint32s(key string, vals ...uint32)

func (*RecordPackerForWriter) Uint64

func (j *RecordPackerForWriter) Uint64(key string, val uint64)

func (*RecordPackerForWriter) Uint64s

func (j *RecordPackerForWriter) Uint64s(key string, vals ...uint64)

func (*RecordPackerForWriter) Uint8

func (j *RecordPackerForWriter) Uint8(key string, val uint8)

func (*RecordPackerForWriter) Uint8s

func (j *RecordPackerForWriter) Uint8s(key string, vals ...uint8)

func (*RecordPackerForWriter) Uints

func (j *RecordPackerForWriter) Uints(key string, vals ...uint)

type WriterEncoderPair

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

WriterEncoderPair wraps a writer and an encoder.

Directories

Path Synopsis
internal
Package log provides the definition and initialization operation of a global rainbow logger.
Package log provides the definition and initialization operation of a global rainbow logger.

Jump to

Keyboard shortcuts

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