golog

package module
v1.6.5 Latest Latest
Warning

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

Go to latest
Published: Sep 21, 2024 License: MIT Imports: 25 Imported by: 1

README

Test status codecov Go Report Card GoDev GitHub release

golog

Fast structure logger for Golang

Feature

  • Zero Allocation
  • Multiple Handlers, Formatters
  • Customize

Installation

go get -u github.com/millken/golog

Getting Started

Simple Logging Example

For simple logging, import the global logger package github.com/millken/golog

package main

import (
    "github.com/millken/golog"
)

func main() {
    golog.Infof("hello %s", "world")
    golog.Info("hello world with fields", "a", 1, "b", true, "c", "string")
}

// Output: 
2022-08-07T21:48:21+08:00 WARN hello world
2022-08-07T21:48:21+08:00 INFO hello world with fields a=1 b=true c=string

Note: By default log writes to os.Stdout, The default log level for is info

Performance

Note: disabled time and colors

$ go test -benchmem -run=^$ -bench ^Benchmark
goos: darwin
goarch: arm64
pkg: github.com/millken/golog
BenchmarkGlobal-8               26714944                44.80 ns/op            0 B/op          0 allocs/op
BenchmarkGlobal_WithField-8     11012862               107.5 ns/op            96 B/op          1 allocs/op
BenchmarkLogText-8              28307115                41.69 ns/op            0 B/op          0 allocs/op
BenchmarkLogText_WithField-8    10153658               117.3 ns/op             0 B/op          0 allocs/op
BenchmarkLogJSON-8              26299471                44.87 ns/op            0 B/op          0 allocs/op
BenchmarkLogJSON_WithField-8     7647043               156.2 ns/op             0 B/op          0 allocs/op
PASS
ok      github.com/millken/golog        9.617s

Documentation

Index

Constants

View Source
const (
	// TimestampFieldName is the field name used for the timestamp field.
	TimestampFieldName = "time"

	// LevelFieldName is the field name used for the level field.
	LevelFieldName = "level"

	// ModuleFieldName is the field name used for the module field.
	ModuleFieldName = "module"
	// MessageFieldName is the field name used for the message field.
	MessageFieldName = "message"

	// ErrorFieldName is the field name used for error fields.
	ErrorFieldName = "error"

	// CallerFieldName is the field name used for caller field.
	CallerFieldName = "caller"

	// ErrorStackFieldName is the field name used for error stacks.
	ErrorStackFieldName = "stack"

	// TimeFieldFormat defines the time format of the Time field type. If set to
	// TimeFormatUnix, TimeFormatUnixMs or TimeFormatUnixMicro, the time is formatted as an UNIX
	// timestamp as integer.
	TimeFieldFormat = time.RFC3339
)
View Source
const DefaultLineEnding = '\n'

DefaultLineEnding is the default line ending used by the text encoder.

Variables

View Source
var (

	//DefaultCallerSkip is the default number of stack frames to skip when reporting caller information.
	DefaultCallerSkip int = 3

	// ErrorMarshalFunc allows customization of global error marshaling
	ErrorMarshalFunc = func(err error) interface{} {
		return err
	}
)
View Source
var (
	// Levels is a slice of all log levels.
	Levels = []Level{
		PANIC,
		FATAL,
		ERROR,
		WARNING,
		INFO,
		DEBUG,
	}
)

Functions

func Debug added in v1.1.0

func Debug(msg string, keysAndVals ...interface{})

Debug logs a message using Debug level.

func Debugf added in v1.2.0

func Debugf(format string, args ...interface{})

Debugf logs a message using Debug level.

func EnableNativeTime added in v1.6.2

func EnableNativeTime()

EnableNativeTime - enable native time

func EnabledNativeTime added in v1.6.2

func EnabledNativeTime() bool

EnabledNativeTime - check if native time is enabled

func Error added in v1.1.0

func Error(msg string, keysAndVals ...interface{})

Error logs a message using Error level.

func Errorf added in v1.2.0

func Errorf(format string, args ...interface{})

Errorf logs a message using Error level.

func Fatal added in v1.1.0

func Fatal(msg string, keysAndVals ...interface{})

Fatal logs a message using Fatal level and exits with status 1.

func Fatalf added in v1.2.0

func Fatalf(format string, args ...interface{})

Fatalf logs a message using Fatal level and exits with status 1.

func Info added in v1.1.0

func Info(msg string, keysAndVals ...interface{})

Info logs a message using Info level.

func Infof added in v1.2.0

func Infof(format string, args ...interface{})

Infof logs a message using Info level.

func LoadConfig added in v1.5.0

func LoadConfig(path string) error

LoadConfig - load config from file.

func Panic added in v1.4.0

func Panic(msg string, keysAndVals ...interface{})

Panic logs a message using Panic level and panics.

func Panicf added in v1.2.1

func Panicf(format string, args ...interface{})

Panicf logs a message using Panic level and panics.

func ResetConfigs added in v1.6.1

func ResetConfigs()

ResetConfigs - reset configs.

func SetCallerLevels added in v1.5.3

func SetCallerLevels(levels ...Level)

SetCallerLevels - set caller levels.

func SetEncoding added in v1.5.3

func SetEncoding(encoding Encoding)

SetEncoding - set log encoding.

func SetJSONEncoderConfig added in v1.5.3

func SetJSONEncoderConfig(cfg JSONEncoderConfig)

SetJSONEncoderConfig - set json encoder config.

func SetLevel added in v1.1.0

func SetLevel(level Level)

SetLevel - set log level.

func SetModuleConfig added in v1.5.2

func SetModuleConfig(module string, cfg Config)

SetModuleConfig - setting config for given module.

func SetStacktraceLevels added in v1.5.3

func SetStacktraceLevels(levels ...Level)

SetStacktraceLevels - set stacktrace levels.

func SetTextEncoderConfig added in v1.5.6

func SetTextEncoderConfig(cfg TextEncoderConfig)

SetTextEncoderConfig - set text encoder config.

func SetWriter added in v1.5.3

func SetWriter(writer io.Writer)

SetWriter - set writer.

func Warn added in v1.1.0

func Warn(msg string, keysAndVals ...interface{})

Warn logs a message using Warn level.

func Warnf added in v1.2.0

func Warnf(format string, args ...interface{})

Warnf logs a message using Warn level.

Types

type Config added in v1.5.1

type Config struct {
	// Level is the default log level.
	Level Level `json:"level" yaml:"level"`
	// Encoding is the log encoding.  text or json.
	Encoding    Encoding          `json:"encoding" yaml:"encoding"`
	TextEncoder TextEncoderConfig `json:"textEncoder" yaml:"textEncoder"`
	JSONEncoder JSONEncoderConfig `json:"jsonEncoder" yaml:"jsonEncoder"`
	//CallerLevels is the default levels for show caller info.
	CallerLevels []Level `json:"callerLevels" yaml:"callerLevels"`
	// StacktraceLevels is the default levels for show stacktrace.
	StacktraceLevels []Level       `json:"stacktraceLevels" yaml:"stacktraceLevels"`
	Handler          HandlerConfig `json:"handler" yaml:"handler"`
}

Config is a configuration for a logger.

func GetModuleConfig added in v1.5.1

func GetModuleConfig(module string) Config

GetModuleConfig - getting config for given module.

type Configs added in v1.5.1

type Configs struct {
	Default Config            `json:"default" yaml:"default"`
	Modules map[string]Config `json:"modules" yaml:"modules"`
}

Configs - configs for golog.

func GetConfigs added in v1.6.1

func GetConfigs() *Configs

type Encoder added in v1.5.1

type Encoder interface {
	Encode(*Entry) ([]byte, error)
}

Encoder is a interface for encoding log entry.

type Encoding added in v1.5.4

type Encoding string

Encoding is the encoding type.

const (

	//JSONEncoding is the json encoding.
	JSONEncoding Encoding = "json"
	//TextEncoding is the text encoding.
	TextEncoding Encoding = "text"
)

type Entry

type Entry struct {
	Module  string
	Message string
	Data    []byte
	Level   Level
	Fields  []Field
	// contains filtered or unexported fields
}

func (*Entry) Bytes

func (e *Entry) Bytes() []byte

Bytes returns the entry data as bytes.

func (*Entry) CallerSkip added in v1.5.1

func (e *Entry) CallerSkip() int

CallerSkip returns the caller skip.

func (*Entry) FieldsLength added in v1.3.0

func (e *Entry) FieldsLength() int

FieldsLength returns the number of fields.

func (*Entry) GetCaller

func (e *Entry) GetCaller() string

GetCaller gets the caller.

func (*Entry) HasFlag added in v1.5.1

func (e *Entry) HasFlag(flag Flag) bool

HasFlag returns true if the flag is set.

func (*Entry) Reset

func (e *Entry) Reset()

Reset resets the entry data.

func (*Entry) SetCaller added in v1.5.1

func (e *Entry) SetCaller(caller string)

SetCaller sets the caller.

func (*Entry) SetCallerSkip added in v1.5.1

func (e *Entry) SetCallerSkip(n int)

SetCallerSkip sets the caller skip.

func (*Entry) SetFieldsLen added in v1.5.1

func (e *Entry) SetFieldsLen(n int)

SetFieldsLen sets the number of fields.

func (*Entry) SetFlag added in v1.5.1

func (e *Entry) SetFlag(flag Flag)

SetFlag sets the flag.

func (*Entry) Write

func (e *Entry) Write(p []byte) (int, error)

Write appends the contents of p to the entry data.

func (*Entry) WriteByte

func (e *Entry) WriteByte(c byte) error

WriteByte appends the byte to the entry data.

func (*Entry) WriteString

func (e *Entry) WriteString(s string) (int, error)

WriteString appends the string to the entry data.

func (*Entry) WriteTo

func (e *Entry) WriteTo(w io.Writer) (int64, error)

WriteTo writes the entry data to w.

type Field added in v1.1.0

type Field struct {
	Key string
	Val interface{}
}

Field is a key/value pair.

type File added in v1.5.1

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

File is an implementation of io.Writer interface.

func NewFile added in v1.5.1

func NewFile(cfg FileConfig) (*File, error)

NewFile creates and returns a new File writer.

func (*File) Write added in v1.5.1

func (w *File) Write(b []byte) (n int, err error)

Write writes the contents of b to the file.

type FileConfig added in v1.5.1

type FileConfig struct {
	Path string `json:"path" yaml:"path"`
}

FileConfig is a configuration for a file writer.

type Flag added in v1.5.1

type Flag uint8
const (
	FlagNoColor Flag = 1 << iota
	FlagTime
	FlagCaller
	FlagStacktrace
	FlagName
)

type HandlerConfig added in v1.5.6

type HandlerConfig struct {
	Type       string           `json:"type" yaml:"type"`
	Writer     io.Writer        `json:"-" yaml:"-"`
	File       FileConfig       `json:"file" yaml:"file"`
	RotateFile RotateFileConfig `json:"rotateFile" yaml:"rotateFile"`
}

HandlerConfig is a configuration for a writer.

type JSONEncoder added in v1.5.1

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

JSONEncoder encodes entries as JSON.

func NewJSONEncoder added in v1.5.1

func NewJSONEncoder(cfg JSONEncoderConfig) *JSONEncoder

NewJSONEncoder returns a new JSONEncoder.

func (*JSONEncoder) Encode added in v1.5.1

func (o *JSONEncoder) Encode(e *Entry) ([]byte, error)

Encode encodes the entry and writes it to the writer.

type JSONEncoderConfig added in v1.5.1

type JSONEncoderConfig struct {
	// TimeFormat specifies the format for timestamp in output.
	TimeFormat string `json:"timeFormat" yaml:"timeFormat"`
	// DisableTimestamp disables the timestamp in output.
	DisableTimestamp bool `json:"disableTimestamp" yaml:"disableTimestamp"`
	// CallerSkipFrame is the number of stack frames to skip when reporting the calling function.
	CallerSkipFrame int `json:"callerSkipFrame" yaml:"callerSkipFrame"`
	// ShowModuleName shows the name of the logger.
	ShowModuleName bool `json:"showModuleName" yaml:"showModuleName"`
}

JSONEncoderConfig is the configuration for the JSONEncoder.

type Level

type Level uint32

Level is a log level for a logging message.

const (
	PANIC Level = 1 << iota
	FATAL
	ERROR
	WARNING
	INFO
	DEBUG
)

Log levels.

func (Level) MarshalYAML added in v1.5.1

func (l Level) MarshalYAML() ([]byte, error)

MarshalYAML implements the yaml.Marshaler interface.

func (Level) String

func (l Level) String() string

String returns the string representation of the log level.

func (*Level) UnmarshalYAML added in v1.5.1

func (l *Level) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements the yaml.Unmarshaler interface.

type Log added in v1.5.1

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

Log is an implementation of Logger interface. It encapsulates default or custom logger to provide module and level based logging.

func New added in v1.4.1

func New(module string) *Log

New creates and returns a Logger implementation based on given module name.

func NewLoggerByConfig added in v1.5.0

func NewLoggerByConfig(module string, cfg Config) (*Log, error)

NewLoggerByConfig creates and returns a Logger implementation based on given config.

func (*Log) CallerSkip added in v1.5.1

func (l *Log) CallerSkip(skip int) *Log

CallerSkip is used to set the number of caller frames to skip.

func (*Log) Debug added in v1.5.1

func (l *Log) Debug(msg string, keysAndVals ...interface{})

Debug calls error log function if DEBUG level enabled.

func (*Log) Debugf added in v1.5.1

func (l *Log) Debugf(format string, args ...interface{})

Debugf calls error log function if DEBUG level enabled.

func (*Log) Error added in v1.5.1

func (l *Log) Error(msg string, keysAndVals ...interface{})

Error calls error log function if ERROR level enabled.

func (*Log) Errorf added in v1.5.1

func (l *Log) Errorf(format string, args ...interface{})

Errorf calls error log function if ERROR level enabled.

func (*Log) Fatal added in v1.5.1

func (l *Log) Fatal(msg string, keysAndVals ...interface{})

Fatal calls underlying logger.Fatal.

func (*Log) Fatalf added in v1.5.1

func (l *Log) Fatalf(format string, args ...interface{})

Fatalf calls underlying logger.Fatal.

func (*Log) Info added in v1.5.1

func (l *Log) Info(msg string, keysAndVals ...interface{})

Info calls error log function if INFO level enabled.

func (*Log) Infof added in v1.5.1

func (l *Log) Infof(format string, args ...interface{})

Infof calls error log function if INFO level enabled.

func (*Log) Panic added in v1.5.1

func (l *Log) Panic(msg string, keysAndVals ...interface{})

Panic calls underlying logger.Panic.

func (*Log) Panicf added in v1.5.1

func (l *Log) Panicf(format string, args ...interface{})

Panicf calls underlying logger.Panic.

func (*Log) Warn added in v1.5.1

func (l *Log) Warn(msg string, keysAndVals ...interface{})

Warn calls error log function if WARNING level enabled.

func (*Log) Warnf added in v1.5.1

func (l *Log) Warnf(format string, args ...interface{})

Warnf calls error log function if WARNING level enabled.

func (*Log) WithValues added in v1.5.1

func (l *Log) WithValues(keysAndVals ...interface{}) Logger

WithValues returns a logger configured with the key-value pairs.

type Logger

type Logger interface {
	WithValues(keysAndVals ...interface{}) Logger
	Panicf(msg string, args ...interface{})
	Fatalf(msg string, args ...interface{})
	Errorf(msg string, args ...interface{})
	Warnf(msg string, args ...interface{})
	Infof(msg string, args ...interface{})
	Debugf(msg string, args ...interface{})
	Panic(msg string, keysAndVals ...interface{})
	Fatal(msg string, keysAndVals ...interface{})
	Error(msg string, keysAndVals ...interface{})
	Warn(msg string, keysAndVals ...interface{})
	Info(msg string, keysAndVals ...interface{})
	Debug(msg string, keysAndVals ...interface{})
}

Logger represents a general-purpose logger.

func WithValues added in v1.5.1

func WithValues(keysAndVals ...interface{}) Logger

WithValues returns a logger configured with the key-value pairs.

type RotateFile added in v1.5.6

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

RotateFile rotate log to file

func NewRotateFile added in v1.5.6

func NewRotateFile(cfg RotateFileConfig) (*RotateFile, error)

NewRotateFile creates a new RotateFile.

func (*RotateFile) Close added in v1.5.6

func (f *RotateFile) Close() error

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

func (*RotateFile) Filename added in v1.5.6

func (f *RotateFile) Filename() string

Filename generates the name of the logfile from the current time.

func (*RotateFile) Rotate added in v1.5.6

func (f *RotateFile) Rotate() error

Rotate close the existing log file and create a new one.

func (*RotateFile) Write added in v1.5.6

func (f *RotateFile) Write(d []byte) (int, error)

Write writes data to a file

type RotateFileConfig added in v1.5.6

type RotateFileConfig struct {
	// Filename is the file to write logs to.  Backup log files will be retained in the same directory.
	// It uses <processname>.log in os.TempDir() if empty.
	Filename string `json:"filename" yaml:"filename"`

	// MaxBackups is the maximum number of old log files to retain.
	MaxBackups int `json:"maxbackups" yaml:"maxbackups"`

	// BackupTimeFormat determines if the time used for formatting the backup file name
	BackupTimeFormat string `json:"backupTimeFormat" yaml:"backupTimeFormat"`

	// LocalTime determines if the time used for formatting the timestamps in
	// backup files is the computer's local time.  The default is to use UTC
	// time.
	LocalTime bool `json:"localtime" yaml:"localtime"`

	// Async determines if the log write should be async
	Async bool `json:"async" yaml:"async"`
}

RotateFileConfig is the configuration for RotateFile.

type TextEncoder added in v1.5.4

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

TextEncoder encodes entries to the text.

func NewTextEncoder added in v1.5.4

func NewTextEncoder(cfg TextEncoderConfig) *TextEncoder

NewTextEncoder returns a new text encoder.

func (*TextEncoder) Encode added in v1.5.4

func (o *TextEncoder) Encode(e *Entry) ([]byte, error)

Encode encodes the entry and writes it to the writer.

type TextEncoderConfig added in v1.5.4

type TextEncoderConfig struct {
	// PartsOrder is the order of the parts of the log entry.
	PartsOrder []string `json:"partsOrder" yaml:"partsOrder"`
	// TimeFormat specifies the format for timestamp in output.
	TimeFormat string `json:"timeFormat" yaml:"timeFormat"`
	// DisableTimestamp disables the timestamp in output.
	DisableTimestamp bool `json:"disableTimestamp" yaml:"disableTimestamp"`
	// DisableColor disables the color in output.
	DisableColor bool `json:"disableColor" yaml:"disableColor"`
	// CallerSkipFrame is the number of stack frames to skip when reporting the calling function.
	CallerSkipFrame int `json:"callerSkipFrame" yaml:"callerSkipFrame"`
	// ShowModuleName shows the name of the logger.
	ShowModuleName bool `json:"showModuleName" yaml:"showModuleName"`
}

TextEncoderConfig is the configuration for the text encoder.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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