slog

package module
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2022 License: MIT Imports: 16 Imported by: 0

README

slog

CI

Go logging library.

Features

  • Logger interface for business-adapted log access.
  • use config to init logger.
  • zerolog implementation.

Usage

package slog_test

import (
	"time"

	"github.com/pkg/errors"

	"github.com/sraphs/slog"
)

func Example() {
	slog.TimestampFunc = func() time.Time {
		return time.Date(2001, time.February, 3, 4, 5, 6, 7, time.UTC)
	}

	slog.Init(&slog.Config{
		Level:   "info",
		Path:    "log/app.log",
		MaxSize: 100,
		MaxAge:  7,
	}).WithTimestamp().WithCaller().WithStack()

	// level log
	slog.Debug("hello world")
	slog.Info("hello world")
	slog.Warn("hello world")
	slog.Error("hello world")
	// slog.Fatal("hello world")

	// format log
	slog.Debugf("hello %s", "world")
	slog.Infof("hello %s", "world")
	slog.Warnf("hello %s", "world")
	slog.Errorf("hello %s", "world")
	// slog.Fatalf("hello %s", "world")

	// log err with stack
	err := outer()
	slog.Error(err)

	slog.Clone().WithFields("foo", "bar").Info("hello world")

	slog.Info("hello world")

	// Outputs:
	// {"level":"info","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:25"}
	// {"level":"warn","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:26"}
	// {"level":"error","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:27"}
	// {"level":"info","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:32"}
	// {"level":"warn","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:33"}
	// {"level":"error","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:34"}
	// {"level":"error","stack":[{"func":"inner","line":"58","source":"example_test.go"},{"func":"middle","line":"62","source":"example_test.go"},{"func":"outer","line":"70","source":"example_test.go"},{"func":"Example","line":"38","source":"example_test.go"},{"func":"runExample","line":"63","source":"run_example.go"},{"func":"runExamples","line":"44","source":"example.go"},{"func":"(*M).Run","line":"1721","source":"testing.go"},{"func":"main","line":"61","source":"_testmain.go"},{"func":"main","line":"250","source":"proc.go"},{"func":"goexit","line":"1571","source":"asm_amd64.s"}],"error":"seems we have an error here","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:39"}
	// {"level":"info","foo":"bar","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"run_example.go:63"}
	// {"level":"info","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:43"}
}

func inner() error {
	return errors.New("seems we have an error here")
}

func middle() error {
	err := inner()
	if err != nil {
		return err
	}
	return nil
}

func outer() error {
	err := middle()
	if err != nil {
		return err
	}
	return nil
}

Contributing

We alway welcome your contributions 👏

  1. Fork the repository
  2. Create Feat_xxx branch
  3. Commit your code
  4. Create Pull Request

CHANGELOG

See Releases

License

MIT © sraph.com

Documentation

Overview

Package log provides a global logger for log.

Example
package main

import (
	"time"

	"github.com/pkg/errors"

	"github.com/sraphs/slog"
)

func main() {
	slog.TimestampFunc = func() time.Time {
		return time.Date(2001, time.February, 3, 4, 5, 6, 7, time.UTC)
	}

	slog.Init(&slog.Config{
		Level:   "info",
		Path:    "log/app.log",
		MaxSize: 100,
		MaxAge:  7,
	}).WithTimestamp().WithCaller().WithStack()

	// level log
	slog.Debug("hello world")
	slog.Info("hello world")
	slog.Warn("hello world")
	slog.Error("hello world")
	// slog.Fatal("hello world")

	// format log
	slog.Debugf("hello %s", "world")
	slog.Infof("hello %s", "world")
	slog.Warnf("hello %s", "world")
	slog.Errorf("hello %s", "world")
	// slog.Fatalf("hello %s", "world")

	// log err with stack
	err := outer()
	slog.Error(err)

	slog.Clone().WithFields("foo", "bar").Info("hello world")

	slog.Info("hello world")

	// Outputs:
	// {"level":"info","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:25"}
	// {"level":"warn","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:26"}
	// {"level":"error","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:27"}
	// {"level":"info","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:32"}
	// {"level":"warn","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:33"}
	// {"level":"error","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:34"}
	// {"level":"error","stack":[{"func":"inner","line":"58","source":"example_test.go"},{"func":"middle","line":"62","source":"example_test.go"},{"func":"outer","line":"70","source":"example_test.go"},{"func":"Example","line":"38","source":"example_test.go"},{"func":"runExample","line":"63","source":"run_example.go"},{"func":"runExamples","line":"44","source":"example.go"},{"func":"(*M).Run","line":"1721","source":"testing.go"},{"func":"main","line":"61","source":"_testmain.go"},{"func":"main","line":"250","source":"proc.go"},{"func":"goexit","line":"1571","source":"asm_amd64.s"}],"error":"seems we have an error here","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:39"}
	// {"level":"info","foo":"bar","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"run_example.go:63"}
	// {"level":"info","msg":"hello world","ts":"2001-02-03T04:05:06Z","caller":"example_test.go:43"}
}

func inner() error {
	return errors.New("seems we have an error here")
}

func middle() error {
	err := inner()
	if err != nil {
		return err
	}
	return nil
}

func outer() error {
	err := middle()
	if err != nil {
		return err
	}
	return nil
}
Output:

Index

Examples

Constants

View Source
const (
	// LevelDebug is logger debug level.
	LevelDebug = log.LevelDebug
	// LevelInfo is logger info level.
	LevelInfo = log.LevelInfo
	// LevelWarn is logger warn level.
	LevelWarn = log.LevelWarn
	// LevelError is logger error level.
	LevelError = log.LevelError
	// LevelFatal is logger fatal level
	LevelFatal = log.LevelFatal
)

Variables

View Source
var (
	// TimestampFieldName is the field name used for the timestamp field.
	TimestampFieldName = "ts"

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

	// LevelTraceValue is the value used for the trace level field.
	LevelTraceValue = "trace"
	// LevelDebugValue is the value used for the debug level field.
	LevelDebugValue = "debug"
	// LevelInfoValue is the value used for the info level field.
	LevelInfoValue = "info"
	// LevelWarnValue is the value used for the warn level field.
	LevelWarnValue = "warn"
	// LevelErrorValue is the value used for the error level field.
	LevelErrorValue = "error"
	// LevelFatalValue is the value used for the fatal level field.
	LevelFatalValue = "fatal"
	// LevelPanicValue is the value used for the panic level field.
	LevelPanicValue = "panic"

	// LevelFieldMarshalFunc allows customization of global level field marshaling.
	LevelFieldMarshalFunc = func(l zlog.Level) string {
		return l.String()
	}

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

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

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

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

	// CallerMarshalFunc allows customization of global caller marshaling
	CallerMarshalFunc = func(file string, line int) string {
		short := file
		for i := len(file) - 1; i > 0; i-- {
			if file[i] == '/' {
				short = file[i+1:]
				break
			}
		}
		file = short
		return file + ":" + strconv.Itoa(line)
	}

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

	// ErrorStackMarshaler extract the stack from err if any.
	ErrorStackMarshaler = pkgerrors.MarshalStack

	// ErrorMarshalFunc allows customization of global error marshaling
	ErrorMarshalFunc = func(err error) interface{} {
		return err
	}

	// InterfaceMarshalFunc allows customization of interface marshaling.
	// Default: "encoding/json.Marshal"
	InterfaceMarshalFunc = json.Marshal

	// 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

	// TimestampFunc defines the function called to generate a timestamp.
	TimestampFunc = time.Now

	// DurationFieldUnit defines the unit for time.Duration type fields added
	// using the Dur method.
	DurationFieldUnit = time.Millisecond

	// DurationFieldInteger renders Dur fields as integer instead of float if
	// set to true.
	DurationFieldInteger = false

	// ErrorHandler is called whenever zerolog fails to write an event on its
	// output. If not set, an error is printed on the stderr. This handler must
	// be thread safe and non-blocking.
	ErrorHandler func(err error)
)
View Source
var (
	MultiLevelWriter = zlog.MultiLevelWriter
)

Functions

func Debug

func Debug(v ...interface{})

func Debugf

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

Debugf calls the default logger's Debugf method.

func Error

func Error(v ...interface{})

func Errorf

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

Errorf calls the default logger's Errorf method.

func Fatal

func Fatal(v ...interface{})

func Fatalf

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

Fatalf calls the default logger's Fatalf method and then os.Exit(1).

func Info

func Info(v ...interface{})

func Infof

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

Infof calls the default logger's Infof method.

func Log added in v1.0.3

func Log(lv Level, v ...interface{})

func Print added in v1.0.2

func Print(v ...interface{})

Printf is alias of Infof

func Printf added in v1.0.2

func Printf(format string, v ...interface{})

Printf is alias of Infof

func Warn

func Warn(v ...interface{})

func Warnf

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

Warnf calls the default logger's Warnf method.

func WithLogger added in v1.0.5

func WithLogger(ctx context.Context, logger FullLogger) context.Context

WithLogger creates a new context with the provided logger attached.

Types

type Config

type Config struct {

	// level is the minimum severity level at which to log. e.g. "info".
	Level string `protobuf:"bytes,1,opt,name=level,proto3" json:"level,omitempty"`
	// path to the log file. e.g. "/var/log/my_app.log"
	Path string `protobuf:"bytes,2,opt,name=path,proto3" json:"path,omitempty"`
	// max_size is the maximum size to store in the log file. unit is MB.
	MaxSize int32 `protobuf:"varint,3,opt,name=max_size,json=maxSize,proto3" json:"max_size,omitempty"`
	// max_age is the maximum age of the log file. unit is days.
	MaxAge int32 `protobuf:"varint,4,opt,name=max_age,json=maxAge,proto3" json:"max_age,omitempty"`
	// contains filtered or unexported fields
}

func (*Config) Descriptor deprecated

func (*Config) Descriptor() ([]byte, []int)

Deprecated: Use Config.ProtoReflect.Descriptor instead.

func (*Config) GetLevel

func (x *Config) GetLevel() string

func (*Config) GetMaxAge

func (x *Config) GetMaxAge() int32

func (*Config) GetMaxSize

func (x *Config) GetMaxSize() int32

func (*Config) GetPath

func (x *Config) GetPath() string

func (*Config) ProtoMessage

func (*Config) ProtoMessage()

func (*Config) ProtoReflect

func (x *Config) ProtoReflect() protoreflect.Message

func (*Config) Reset

func (x *Config) Reset()

func (*Config) String

func (x *Config) String() string

type Control

type Control interface {
	SetLevel(Level) Control
	SetOutput(io.Writer) Control
}

Control provides methods to config a logger.

func SetLevel

func SetLevel(lv Level) Control

SetLevel sets the current global log level.

func SetOutput

func SetOutput(w io.Writer) Control

SetOutput sets the global logger output.

type FormatLogger

type FormatLogger interface {
	Debugf(format string, v ...interface{})
	Infof(format string, v ...interface{})
	Printf(format string, v ...interface{}) // Printf is an alias for Infof.
	Warnf(format string, v ...interface{})
	Errorf(format string, v ...interface{})
	Fatalf(format string, v ...interface{})
}

FormatLogger is a logger interface that output logs with a format.

type FullLogger

type FullLogger interface {
	KLogger
	LevelLogger
	FormatLogger
	Control
	Clone() FullLogger
	WithTimestamp() FullLogger
	WithCaller() FullLogger
	WithCallerWithSkipFrameCount(skipFrameCount int) FullLogger
	WithStack() FullLogger
	WithFields(fields ...interface{}) FullLogger
}

FullLogger is the combination of Logger, FormatLogger, CtxLogger and Control.

func Clone

func Clone() FullLogger

func DefaultLogger

func DefaultLogger() FullLogger

GetLogger returns the current global

func FromContext added in v1.0.5

func FromContext(ctx context.Context) FullLogger

FromContext returns the logger stored in the context. If no such logger exists, a default logger is returned.

func Init

func Init(c *Config) FullLogger

func New

func New(c *Config) FullLogger

func WithCaller

func WithCaller() FullLogger

func WithCallerWithSkipFrameCount

func WithCallerWithSkipFrameCount(skipFrameCount int) FullLogger

func WithFields

func WithFields(fields ...interface{}) FullLogger

func WithStack

func WithStack() FullLogger

func WithTimestamp

func WithTimestamp() FullLogger

type Helper added in v1.0.2

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

func (*Helper) Clone added in v1.0.2

func (ll *Helper) Clone() FullLogger

func (*Helper) Debug added in v1.0.2

func (ll *Helper) Debug(v ...interface{})

func (*Helper) Debugf added in v1.0.2

func (ll *Helper) Debugf(format string, v ...interface{})

func (*Helper) Error added in v1.0.2

func (ll *Helper) Error(v ...interface{})

func (*Helper) Errorf added in v1.0.2

func (ll *Helper) Errorf(format string, v ...interface{})

func (*Helper) Fatal added in v1.0.2

func (ll *Helper) Fatal(v ...interface{})

func (*Helper) Fatalf added in v1.0.2

func (ll *Helper) Fatalf(format string, v ...interface{})

func (*Helper) Info added in v1.0.2

func (ll *Helper) Info(v ...interface{})

func (*Helper) Infof added in v1.0.2

func (ll *Helper) Infof(format string, v ...interface{})

func (*Helper) Log added in v1.0.2

func (ll *Helper) Log(lv Level, v ...interface{}) error

func (*Helper) Print added in v1.0.2

func (ll *Helper) Print(v ...interface{})

func (*Helper) Printf added in v1.0.2

func (ll *Helper) Printf(format string, v ...interface{})

func (*Helper) SetLevel added in v1.0.2

func (ll *Helper) SetLevel(lv Level) Control

func (*Helper) SetOutput added in v1.0.2

func (ll *Helper) SetOutput(w io.Writer) Control

func (*Helper) Warn added in v1.0.2

func (ll *Helper) Warn(v ...interface{})

func (*Helper) Warnf added in v1.0.2

func (ll *Helper) Warnf(format string, v ...interface{})

func (*Helper) WithCaller added in v1.0.2

func (ll *Helper) WithCaller() FullLogger

func (*Helper) WithCallerWithSkipFrameCount added in v1.0.2

func (ll *Helper) WithCallerWithSkipFrameCount(skipFrameCount int) FullLogger

func (*Helper) WithFields added in v1.0.2

func (ll *Helper) WithFields(fields ...interface{}) FullLogger

func (*Helper) WithStack added in v1.0.2

func (ll *Helper) WithStack() FullLogger

func (*Helper) WithTimestamp added in v1.0.2

func (ll *Helper) WithTimestamp() FullLogger

type KLogger

type KLogger interface {
	log.Logger
}

Kratos logger interface.

type Level

type Level = log.Level

func ParseLevel

func ParseLevel(lv string) Level

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

type LevelLogger

type LevelLogger interface {
	Debug(v ...interface{})
	Info(v ...interface{})
	Print(v ...interface{}) // Print is an alias of Info().
	Warn(v ...interface{})
	Error(v ...interface{})
	Fatal(v ...interface{})
}

LevelLogger is a logger interface that provides logging function with levels.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳