log

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 13, 2023 License: MIT Imports: 9 Imported by: 0

README

log

A simple package that wraps zap logger with lumberjack. This package provides a simpler way to init and use zap logger.

Installation

go get -u github.com/olee12/log

Example
type User struct {
	FirstName string
	LastName  string
	Age       int
	Address   Address
	Phone     string
}

type Address struct {
	Street   string
	PostCode string
}

func init() {
	rand.Seed(time.Now().UnixNano())
}

var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func RandStringRunes(n int) string {
	b := make([]rune, n)
	for i := range b {
		b[i] = letterRunes[rand.Intn(len(letterRunes))]
	}
	return string(b)
}

func RandomUser() User {
	return User{
		FirstName: RandStringRunes(5),
		LastName:  RandStringRunes(5),
		Age:       rand.Intn(30) + 10,
		Address: Address{
			Street:   RandStringRunes(20),
			PostCode: RandStringRunes(6),
		},
		Phone: RandStringRunes(10),
	}
}

func main() {
	packageLevelLoggerExample()
	childLoggerExample(100000)
}

func packageLevelLoggerExample() {
	packageDebugLogger()
	packageErrorLogger()
	packageInfoLogger()
	packageWarnLogger()
}

func childLoggerExample(N int) {
	log.Configure(*log.DefaultRotateLoggerConfig)
	logLevels := []log.Level{log.DebugLevel, log.InfoLevel, log.WarnLevel, log.ErrorLevel, log.PanicLevel, log.FatalLevel, log.DPanicLevel}
	ticker := time.NewTicker(2 * time.Second)

	// change the log level every concurrently
	go func() {
		for range ticker.C {
			log.SetLevel(logLevels[rand.Intn(len(logLevels))])
		}
	}()

	for i := 0; i < N; i++ {
		logger := log.WithField("request_id", RandStringRunes(15))
		joiner := make(chan struct{}, 4)
		go func() {
			tryDebugLogger(logger)
			joiner <- struct{}{}
		}()

		go func() {
			tryInfoLogger(logger)
			joiner <- struct{}{}
		}()

		go func() {
			tryWarnLogger(logger)
			joiner <- struct{}{}
		}()

		go func() {
			tryErrorLogger(logger)
			joiner <- struct{}{}
		}()

		// join
		for a := 0; a < 4; a++ {
			<-joiner
		}

	}
	ticker.Stop()
}

func tryInfoLogger(logger *log.LogEntry) {
	logger.InfoWith("[with] message with some user info", log.Fields{"user1": RandomUser(), "user2": RandomUser()})
	logger.InfoWith("[with] only message", log.Fields{})
	logger.Info("[] simple log")
	logger.Infov("[v] with user", zap.Any("user", RandomUser()))
	logger.Infow("[w] with user", "user", RandomUser())
	logger.Infof("[f]user: %v", RandomUser())
}

func tryDebugLogger(logger *log.LogEntry) {
	logger.DebugWith("[with]message with some user info", log.Fields{"user1": RandomUser(), "user2": RandomUser()})
	logger.DebugWith("[with]only message", log.Fields{})
	logger.Debug("[] simple log")
	logger.Debugv("[v] with user", zap.Any("user", RandomUser()))
	logger.Debugw("[w] with user", "user", RandomUser())
	logger.Debugf("[f] user: %v", RandomUser())
}

func tryErrorLogger(logger *log.LogEntry) {
	logger.ErrorWith("[with] message with some user info", log.Fields{"user1": RandomUser(), "user2": RandomUser()})
	logger.ErrorWith("[with] only message", log.Fields{})
	logger.Error("[] simple log")
	logger.Errorv("[v] with user", zap.Any("user", RandomUser()))
	logger.Errorw("[w] with user", "user", RandomUser())
	logger.Errorf("[f] user: %v", RandomUser())
}

func tryWarnLogger(logger *log.LogEntry) {
	logger.WarnWith("[with] message with some user info", log.Fields{"user1": RandomUser(), "user2": RandomUser()})
	logger.WarnWith("[with] only message", log.Fields{})
	logger.Warn("[] simple log")
	logger.Warnv("[v] with user", zap.Any("user", RandomUser()))
	logger.Warnw("[w] with user", "user", RandomUser())
	logger.Warnf("[f] user: %v", RandomUser())
}

func packageInfoLogger() {
	log.InfoWith("[with] message with some user info", log.Fields{"user1": RandomUser(), "user2": RandomUser()})
	log.InfoWith("[with] only message", log.Fields{})
	log.Info("[] simple log")
	log.Infov("[v] with user", zap.Any("user", RandomUser()))
	log.Infow("[w] with user", "user", RandomUser())
	log.Infof("[f]user: %v", RandomUser())
}

func packageDebugLogger() {
	log.DebugWith("[with]message with some user info", log.Fields{"user1": RandomUser(), "user2": RandomUser()})
	log.DebugWith("[with]only message", log.Fields{})
	log.Debug("[] simple log")
	log.Debugv("[v] with user", zap.Any("user", RandomUser()))
	log.Debugw("[w] with user", "user", RandomUser())
	log.Debugf("[f] user: %v", RandomUser())
}

func packageErrorLogger() {
	log.ErrorWith("[with] message with some user info", log.Fields{"user1": RandomUser(), "user2": RandomUser()})
	log.ErrorWith("[with] only message", log.Fields{})
	log.Error("[] simple log")
	log.Errorv("[v] with user", zap.Any("user", RandomUser()))
	log.Errorw("[w] with user", "user", RandomUser())
	log.Errorf("[f] user: %v", RandomUser())
}

func packageWarnLogger() {
	log.WarnWith("[with] message with some user info", log.Fields{"user1": RandomUser(), "user2": RandomUser()})
	log.WarnWith("[with] only message", log.Fields{})
	log.Warn("[] simple log")
	log.Warnv("[v] with user", zap.Any("user", RandomUser()))
	log.Warnw("[w] with user", "user", RandomUser())
	log.Warnf("[f] user: %v", RandomUser())
}

Documentation

Index

Constants

View Source
const (
	DebugLevel  = zapcore.DebugLevel
	InfoLevel   = zapcore.InfoLevel
	WarnLevel   = zapcore.WarnLevel
	ErrorLevel  = zapcore.ErrorLevel
	DPanicLevel = zapcore.DPanicLevel
	PanicLevel  = zapcore.PanicLevel
	FatalLevel  = zapcore.FatalLevel
)
View Source
const DefaultFieldName = "-"

Variables

View Source
var DefaultRotateLoggerConfig = &Config{
	Level:              DebugLevel,
	EncodeLogsAsJson:   true,
	CallerEnabled:      true,
	CallerSkip:         1,
	ConsoleSeparator:   "",
	LevelEncoder:       zapcore.LowercaseLevelEncoder,
	Directory:          "logs",
	Filename:           filepath.Base(os.Args[0]),
	FileLoggingEnabled: true,
	MaxSize:            128,
	MaxBackups:         10,
	MaxAge:             90,
}
View Source
var DefaultZapLogger = newZapLogger(defaultConfig, os.Stdout, os.Stderr, true)

DefaultZapLogger is the default logger instance that should be used to log It's assigned a default value here for tests (which do not call log.Configure())

Functions

func AtLevel

func AtLevel(level zapcore.Level, msg string, fields ...zapcore.Field)

AtLevel logs the message at a specific log level

func Configure

func Configure(config Config) error

Configure sets up the logging framework

func ConsoleLogTimeEncoder

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

ConsoleLogTimeEncoder serializes a time.Time to an short-formatted string

func ContextWithCustomizedLogger

func ContextWithCustomizedLogger(ctx context.Context, logEntry *LogEntry) context.Context

func ContextWithLogger

func ContextWithLogger(ctx context.Context) context.Context

func DPanic

func DPanic(msg string)

func DPanicWith

func DPanicWith(msg string, fields Fields)

func DPanicf

func DPanicf(template string, args ...interface{})

func DPanicv

func DPanicv(msg string, fields ...zapcore.Field)

func DPanicw

func DPanicw(msg string, keysAndValues ...interface{})

func Debug

func Debug(msg string)

Debug Log a message at the debug level

func DebugWith

func DebugWith(msg string, fields Fields)

DebugWith Log a message with fields at the debug level

func Debugf

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

Debugf Log a format message at the debug level

func Debugv

func Debugv(msg string, fields ...zapcore.Field)

func Debugw

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

func DeclareLogger

func DeclareLogger(config Config, logv func(msg string, fields ...zapcore.Field))

func Error

func Error(msg string)

func ErrorWith

func ErrorWith(msg string, fields Fields)

func Errorf

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

func Errorv

func Errorv(msg string, fields ...zapcore.Field)

func Errorw

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

func Fatal

func Fatal(msg string)

func FatalWith

func FatalWith(msg string, fields Fields)

func Fatalf

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

func Fatalv

func Fatalv(msg string, fields ...zapcore.Field)

func Fatalw

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

func Info

func Info(msg string)

func InfoWith

func InfoWith(msg string, fields Fields)

func Infof

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

func Infov

func Infov(msg string, fields ...zapcore.Field)

func Infow

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

func Panic

func Panic(msg string)

func PanicWith

func PanicWith(msg string, fields Fields)

func Panicf

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

func Panicv

func Panicv(msg string, fields ...zapcore.Field)

func Panicw

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

func SetLevel

func SetLevel(l Level)

func ShortTimeEncoder

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

ShortTimeEncoder serializes a time.Time to an short-formatted string

func Warn

func Warn(msg string)

func WarnWith

func WarnWith(msg string, fields Fields)

func Warnf

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

func Warnv

func Warnv(msg string, fields ...zapcore.Field)

func Warnw

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

Types

type Config

type Config struct {
	// Level set log level
	Level zapcore.Level
	// EncodeLogsAsJson makes the log framework log JSON
	EncodeLogsAsJson bool
	// FileLoggingEnabled makes the framework log to a file
	FileLoggingEnabled bool
	// ConsoleLoggingEnabled makes the framework log to console
	ConsoleLoggingEnabled bool
	// CallerEnabled makes the caller log to a file
	CallerEnabled bool
	// CallerSkip increases the number of callers skipped by caller
	CallerSkip int
	// Directory to log to when file logging is enabled
	Directory string
	// Filename is the name of the log file which will be placed inside the directory
	Filename string
	// MaxSize is the maximum size in megabytes of the log file before it gets
	// rotated. It defaults to 100 megabytes.
	MaxSize int
	// MaxBackups the max number of rolled files to keep
	MaxBackups int
	// MaxAge the max age in days to keep a log file
	MaxAge int
	// ConsoleInfoStream
	ConsoleInfoStream *os.File
	// ConsoleErrorStream
	ConsoleErrorStream *os.File
	// ConsoleSeparator the separator of fields of the log record
	ConsoleSeparator string
	// LevelEncoder use lowercase or capital case encoder
	LevelEncoder zapcore.LevelEncoder
}

Config for logging

type Fields

type Fields map[string]interface{}

type Level

type Level = zapcore.Level

func GetLevel

func GetLevel() Level

type LogEntry

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

func FromContext

func FromContext(ctx context.Context) *LogEntry

func NewLogEntry

func NewLogEntry(config Config) *LogEntry

NewLogEntry create a new logentry instead of override defaultzaplogger

func With

func With(data string) *LogEntry

func WithField

func WithField(k, v string) *LogEntry

func WithFields

func WithFields(fields Fields) *LogEntry

func (*LogEntry) ContextWithLogger

func (le *LogEntry) ContextWithLogger(ctx context.Context) context.Context

func (*LogEntry) DPanic

func (le *LogEntry) DPanic(msg string)

func (*LogEntry) DPanicWith

func (le *LogEntry) DPanicWith(msg string, fields Fields)

func (*LogEntry) DPanicf

func (le *LogEntry) DPanicf(template string, args ...interface{})

func (*LogEntry) DPanicln

func (le *LogEntry) DPanicln(args ...interface{})

func (*LogEntry) DPanicv

func (le *LogEntry) DPanicv(msg string, fields ...zapcore.Field)

func (*LogEntry) DPanicw

func (le *LogEntry) DPanicw(msg string, keysAndValues ...interface{})

func (*LogEntry) Debug

func (le *LogEntry) Debug(msg string)

func (*LogEntry) DebugWith

func (le *LogEntry) DebugWith(msg string, fields Fields)

func (*LogEntry) Debugf

func (le *LogEntry) Debugf(template string, args ...interface{})

func (*LogEntry) Debugln

func (le *LogEntry) Debugln(args ...interface{})

func (*LogEntry) Debugv

func (le *LogEntry) Debugv(msg string, fields ...zapcore.Field)

func (*LogEntry) Debugw

func (le *LogEntry) Debugw(msg string, keysAndValues ...interface{})

func (*LogEntry) Error

func (le *LogEntry) Error(msg string)

func (*LogEntry) ErrorWith

func (le *LogEntry) ErrorWith(msg string, fields Fields)

func (*LogEntry) Errorf

func (le *LogEntry) Errorf(template string, args ...interface{})

func (*LogEntry) Errorln

func (le *LogEntry) Errorln(args ...interface{})

func (*LogEntry) Errorv

func (le *LogEntry) Errorv(msg string, fields ...zapcore.Field)

func (*LogEntry) Errorw

func (le *LogEntry) Errorw(msg string, keysAndValues ...interface{})

func (*LogEntry) Fatal

func (le *LogEntry) Fatal(msg string)

func (*LogEntry) FatalWith

func (le *LogEntry) FatalWith(msg string, fields Fields)

func (*LogEntry) Fatalf

func (le *LogEntry) Fatalf(template string, args ...interface{})

func (*LogEntry) Fatalln

func (le *LogEntry) Fatalln(args ...interface{})

func (*LogEntry) Fatalv

func (le *LogEntry) Fatalv(msg string, fields ...zapcore.Field)

func (*LogEntry) Fatalw

func (le *LogEntry) Fatalw(msg string, keysAndValues ...interface{})

func (*LogEntry) Info

func (le *LogEntry) Info(msg string)

func (*LogEntry) InfoWith

func (le *LogEntry) InfoWith(msg string, fields Fields)

func (*LogEntry) Infof

func (le *LogEntry) Infof(template string, args ...interface{})

func (*LogEntry) Infoln

func (le *LogEntry) Infoln(args ...interface{})

func (*LogEntry) Infov

func (le *LogEntry) Infov(msg string, fields ...zapcore.Field)

func (*LogEntry) Infow

func (le *LogEntry) Infow(msg string, keysAndValues ...interface{})

func (*LogEntry) Panic

func (le *LogEntry) Panic(msg string)

func (*LogEntry) PanicWith

func (le *LogEntry) PanicWith(msg string, fields Fields)

func (*LogEntry) Panicf

func (le *LogEntry) Panicf(template string, args ...interface{})

func (*LogEntry) Panicln

func (le *LogEntry) Panicln(args ...interface{})

func (*LogEntry) Panicv

func (le *LogEntry) Panicv(msg string, fields ...zapcore.Field)

func (*LogEntry) Panicw

func (le *LogEntry) Panicw(msg string, keysAndValues ...interface{})

func (*LogEntry) Warn

func (le *LogEntry) Warn(msg string)

func (*LogEntry) WarnWith

func (le *LogEntry) WarnWith(msg string, fields Fields)

func (*LogEntry) Warnf

func (le *LogEntry) Warnf(template string, args ...interface{})

func (*LogEntry) Warnln

func (le *LogEntry) Warnln(args ...interface{})

func (*LogEntry) Warnv

func (le *LogEntry) Warnv(msg string, fields ...zapcore.Field)

func (*LogEntry) Warnw

func (le *LogEntry) Warnw(msg string, keysAndValues ...interface{})

func (*LogEntry) WithFields

func (le *LogEntry) WithFields(f Fields) *LogEntry

Jump to

Keyboard shortcuts

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