logger

package module
v0.3.5 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2021 License: MIT Imports: 6 Imported by: 0

README

logger

actions travis

Package logger is a wrapper of structured Zap Logger with extended features.

Features

  • Config logger via env.
  • Name key is optional, add custom prefix message.
  • Add log duration functions (Infod, Debugd, Warnd, Autod).
  • Add default logger instance in package log.
  • Share common logger across repositories.
  • Easy to start with many simple ways to create a basic logger.
  • Easy to switch between logger and sugared logger with Wrap and Unwrap method.

Quick start

Install
go get -d github.com/danztran/logger
Options
# log levels: debug (default), info, warn, error, fatal, panic
# set default log level
LOG_LEVEL="debug"
# set log level for named logger (with uppercase),
# for example: LOG_LEVEL_MAIN, LOG_LEVEL_DB
LOG_LEVEL_MAIN="debug"

# log color: false (default), true
# colorize on level field
LOG_COLOR="true"

# log encoding: console (default), json
#   console: simple content (easy to read)
#   json: structured json logs (easy to search)
LOG_ENCODING="console"

# timestamp format: rfc3339 (default), rfc3339nano, iso8601, s, ms, ns, disabled
LOG_TIMESTAMP="rfc3339"
Example
package main

import (
	"time"

	logger "github.com/danztran/logger"
)

var (
	// there are many ways to create a logger
	// log, err = logger.Named("main")
	// log, err = logger.New()
	// log = logger.MustNamed("main")
	log = logger.MustNew()

	// or just import and use default logger
	// import "github.com/danztran/logger/log"
)

func main() {
	// simple log with info level
	log.Info("start")                   // INFO "start"
	defer log.Infod()("execution time") // INFO "execution time: 2.016s"

	doSomething()
}

func doSomething() {
	defer log.Debugd()("do A took") // DEBUG "do A took: 2.0011446s"

	// Autod log with warn level if duration is longer than expected,
	// otherwise log with debug level.

	// log with warn level because duration (2s) is longer than expected (1s)
	defer log.Autod(1 * time.Second)("do B") // WARN "do B: 2.015s"

	// log with debug level because duration (2s) is shorter than expected (3s)
	defer log.Autod(3 * time.Second)("do B") // DEBUG "do B: 2.012s"

	// make new logger with prefix message
	userID := 123
	log := log.Withf("[user:%d]", userID)

	// Warnd log warn if duration took longer than expected,
	// otherwise nothing will be logged.

	// log as warn because duration (2s) is longer than expected (1s)
	defer log.Warnd(1 * time.Second)("do C") // WARN "[user:123] do C: 2.011s"

	// not logging because duration (2s) is shorter than expected (3s)
	defer log.Warnd(3 * time.Second)("do C")

	time.Sleep(2 * time.Second)
}
$ LOG_COLOR=true go run example/main.go
2021-10-26T18:00:30.792Z    info    example/main.go:22      start
2021-10-26T18:00:32.794Z    warn    example/main.go:54      [user:123] do C: 2.0010509s
2021-10-26T18:00:32.794Z    debug   example/main.go:54      do B: 2.0011264s
2021-10-26T18:00:32.794Z    warn    example/main.go:54      do B: 2.0011339s
2021-10-26T18:00:32.794Z    debug   example/main.go:54      do A took: 2.0011446s
2021-10-26T18:00:32.794Z    info    example/main.go:26      execution time: 2.0011492s

$ LOG_TIMESTAMP=ms LOG_ENCODING=json go run example/main.go
{"level":"info","ts":1635257396952,"caller":"example/main.go:22","msg":"start"}
{"level":"warn","ts":1635257398953,"caller":"example/main.go:54","msg":"[user:123] do C: 2.0010486s"}
{"level":"debug","ts":1635257398953,"caller":"example/main.go:54","msg":"do B: 2.0011176s"}
{"level":"warn","ts":1635257398953,"caller":"example/main.go:54","msg":"do B: 2.0011231s"}
{"level":"debug","ts":1635257398953,"caller":"example/main.go:54","msg":"do A took: 2.0011263s"}
{"level":"info","ts":1635257398953,"caller":"example/main.go:26","msg":"execution time: 2.0011293s"}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var NoLogFunc = func(_ string, _ ...interface{}) {}

Functions

func NewZap

func NewZap(name string) (*zap.SugaredLogger, error)

NewZap returns core logger as sugared logger with default basic config

func NewZapConfig

func NewZapConfig(name string) *zap.Config

NewZapConfig read log config from environment default value will be used if env is invalid

func UnixMilliTimeEncoder

func UnixMilliTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)

func UnixTimeEncoder

func UnixTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)

Types

type LogFunc

type LogFunc func(template string, args ...interface{})

type Logger

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

Logger wrapper the base zap SugaredLogger for some extra features

func MustNamed

func MustNamed(name string) *Logger

MustNamed is like Named but panics if the logger can not be built

func MustNew

func MustNew() *Logger

MustNew is like New but panics if the logger can not be built

func Named

func Named(name string) (*Logger, error)

Named build a simple wrapped zap logger

func New

func New() (*Logger, error)

New register a wrapped zap logger with no name

func Wrap

func Wrap(logger *zap.SugaredLogger) *Logger

Wrap wrap zap logger with pkg logger

func (*Logger) AddHook

func (c *Logger) AddHook(fn func(e zapcore.Entry) error) *Logger

AddHook add new hook to the core logger

func (*Logger) Autod

func (c *Logger) Autod(dur time.Duration) LogFunc

Autod return a function to log message with elapsed duration, log level could be debug or warn depended on duration time

func (*Logger) Debug

func (c *Logger) Debug(args ...interface{})

Debug uses fmt.Sprint to construct and log a message with prefix.

func (*Logger) Debugd

func (c *Logger) Debugd() LogFunc

Debugd is like Debugf but return a function to log message with duration.

func (*Logger) Debugf

func (c *Logger) Debugf(template string, args ...interface{})

Debugf uses fmt.Sprintf to log a templated message with prefix.

func (*Logger) Debugw

func (c *Logger) Debugw(msg string, keysAndValues ...interface{})

Debugw logs a message with some additional context with keys and values (prefer for json logs).

func (*Logger) Error

func (c *Logger) Error(args ...interface{})

Error uses fmt.Sprint to construct and log a message with prefix.

func (*Logger) Errorf

func (c *Logger) Errorf(template string, args ...interface{})

Errorf uses fmt.Sprintf to log a templated message with prefix.

func (*Logger) Errorw

func (c *Logger) Errorw(msg string, keysAndValues ...interface{})

Errorw logs a message with some additional context with keys and values (prefer for json logs).

func (*Logger) Fatal

func (c *Logger) Fatal(args ...interface{})

Fatal uses fmt.Sprint to construct and log a message with prefix.

func (*Logger) Fatalf

func (c *Logger) Fatalf(template string, args ...interface{})

Fatalf uses fmt.Sprintf to log a templated message with prefix.

func (*Logger) Fatalw

func (c *Logger) Fatalw(msg string, keysAndValues ...interface{})

Fatalw logs a message with some additional context with keys and values (prefer for json logs).

func (*Logger) Info

func (c *Logger) Info(args ...interface{})

Info uses fmt.Sprint to construct and log a message with prefix.

func (*Logger) Infod

func (c *Logger) Infod() LogFunc

Infod is like Infof but return a function to log message with duration.

func (*Logger) Infof

func (c *Logger) Infof(template string, args ...interface{})

Infof uses fmt.Sprintf to log a templated message with prefix.

func (*Logger) Infow

func (c *Logger) Infow(msg string, keysAndValues ...interface{})

Infow logs a message with some additional context with keys and values (prefer for json logs).

func (*Logger) Panic

func (c *Logger) Panic(args ...interface{})

Panic uses fmt.Sprint to construct and log a message with prefix.

func (*Logger) Panicf

func (c *Logger) Panicf(template string, args ...interface{})

Panicf uses fmt.Sprintf to log a templated message with prefix.

func (*Logger) Panicw

func (c *Logger) Panicw(msg string, keysAndValues ...interface{})

Panicw logs a message with some additional context with keys and values (prefer for json logs).

func (*Logger) Skip

func (c *Logger) Skip(skip int) *Logger

Skip return new instances that increases the number of callers skipped by caller annotation

func (*Logger) Sync

func (c *Logger) Sync() error

Sync flushes any buffered log entries.

func (*Logger) Unwrap

func (c *Logger) Unwrap() *zap.SugaredLogger

Unwrap returns core logger instance, so you can use it directly. you can also re-wrap this logger with Wrap function.

func (*Logger) Warn

func (c *Logger) Warn(args ...interface{})

Warn uses fmt.Sprint to construct and log a message with prefix.

func (*Logger) Warnd

func (c *Logger) Warnd(dur time.Duration) LogFunc

Warnd is like Warnf but return a function to log message with duration only if the duration is longer than expected

func (*Logger) Warnf

func (c *Logger) Warnf(template string, args ...interface{})

Warnf uses fmt.Sprintf to log a templated message with prefix.

func (*Logger) Warnw

func (c *Logger) Warnw(msg string, keysAndValues ...interface{})

Warnw logs a message with some additional context with keys and values (prefer for json logs).

func (*Logger) With

func (c *Logger) With(args ...interface{}) *Logger

With uses fmt.Sprint to construct new logger with prefix

func (*Logger) Withf

func (c *Logger) Withf(template string, args ...interface{}) *Logger

Withf makes new instance and uses fmt.Sprintf to make prefix for later logs

func (*Logger) Withw

func (c *Logger) Withw(keysAndValues ...interface{}) *Logger

Withw makes new instance included additional context keys and values for later logs (prefer for json logs).

Directories

Path Synopsis
package log is the expose default logger instance
package log is the expose default logger instance

Jump to

Keyboard shortcuts

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