flogger

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2024 License: MIT Imports: 7 Imported by: 1

README

flogger GoDoc Build Status Coverage Status Go Report Card

flogger

The flogger package provides a simple function call logging by wrapping zerolog package.

Motivation

Simplify a routine of logging function's input parameters and execution duration.

Installation

go get -u github.com/axkit/flogger

Getting Started

For simple logging use global variable flogger.G

package main

import (
    "github.com/axkit/flogger"
)

func main() {
    
    zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
    log.Info().Msg("application started")

    task("John", 100, 10)
}

func task(name string, a, b int) {
    fc := flogger.G.Enter(name, a, b)
    defer fc.Exit()

    // function logic
    // write intermediate lines to the log
    fc.Debug().Int("subtask", 1).Msg("completed")
}

// Output: 
{"time":1516134303,"level":"info","message":"application started"}
{"time":1516134304,"level":"debug","func":"task","params":"[John 100 10]","message":"enter"}
{"time":1516134310,"level":"debug","func":"task","subtask":1,"message":"completed"}
{"time":1516134315,"level":"debug","func":"task","dur":500,"message":"exit"}

Usage

Let's say we have following structure:

import "github.com/axkit/flogger"

type CustomerRepo struct {
    flog flogger.Logger
    ...    
}

func NewCustomerRepo(l *zerolog.Logger) *CustomerRepo {
    return &CustomerRepo{
        flog: flogger.New(l, "repo", "customer"),
    }
}
Examples

Writes 1 line: the function invocation fact.

func (repo *CustomerRepo)CustomerByID(id int) *Customer {
    repo.flog.Enter()
}
// Output
{"time":1516134304,"level":"debug","func":"CustomerByID","message":"enter"}

Writes 1 line: the function invocation fact with input parameters.

func (repo *CustomerRepo)NewCustomer(id int, name string, age int, ssn string) *Customer {
    repo.flog.Enter(id, name, age)
}
// Output
{"time":1516134304,"level":"debug","func":"NewCustomer","params":"[10 John 42]","message":"enter"}

Writes 2 lines: the function invocation fact with input parameters and function execution duration on exit.

func (repo *CustomerRepo)CustomerByID(id int) *Customer {
    defer repo.flog.Enter(id).Exit()
}
// Output
{"time":1516134304,"level":"debug","func":"CustomerByID","params":"[10]","message":"enter"}
{"time":1516134310,"level":"debug","func":"CustomerByID","dur":670,"message":"exit"}

Writes 3 lines: the function invocation fact with input parameters. Writes the function execution duration on exit. Writes intermediate line as well.

func (repo *CustomerRepo)CustomerByID(id int) *Customer {

    // fc stands for function call
    fc := repo.flog.Enter(id)
    defer fc.Exit()

    fc.Debug().Int("subtask", 1).Msg("completed)
}

Writes 1 line: the function execution duration on exit.

func (repo *CustomerRepo)CustomerByID(id int) *Customer {
    defer repo.flog.Enter().Exit()
}

Writes 1 line: the function execution duration and input params on exit.

func (repo *CustomerRepo)CustomerByID(id int) *Customer {
    defer repo.flog.EnterSilent().Exit(id)
}

Writes 0 or 1 line: the function execution duration and input params on exit conditionally. Writes nothing if OnExit() was not called.

func (repo *CustomerRepo)CustomerByID(id int) *Customer {
    fc := repo.flog.EnterSilent()
    defer fc.Exit()

    if err := sql.Query(...); err != nil {
        fc.OnExit(id)
    }
    return nil
}
Function Call Logging Customization

Exit method calls floggger.ExitHandler (declared as public variable) function to write log item on exit. As instance, we need extend exit call and save performance metrics.

flog := flogger.New(l, "repo", "customer")
flog.SetSecondExitHandler(func(fc *flogger.FuncCall){
    // call Prometheus
    // 
})

...
..

// write 1 line to the log on exit together with pushing 
// information to Prometeus. 
defer flog.EnterSilent().Exit(id, name, age)

Performance

cpu: Intel(R) Core(TM) i7-6700HQ CPU @ 2.60GHz
BenchmarkLogger_Enter1-8                  714012      1660 ns/op  360 B/op    6 allocs/op
BenchmarkLogger_Enter3-8                  557878      2063 ns/op  400 B/op    6 allocs/op
BenchmarkLogger_EnterSilentExit1-8        614272      1995 ns/op  360 B/op    6 allocs/op
BenchmarkLogger_EnterSilentExit3-8        412462      2650 ns/op  400 B/op    6 allocs/op
BenchmarkLogger_EnterExit3-8              477002      2426 ns/op  400 B/op    6 allocs/op

License

MIT

Documentation

Overview

The flogger package provides a simple function call logging by wrapping github.com/rs/zerolog package.

Index

Constants

This section is empty.

Variables

View Source
var ExitHandler = func(fc *FuncCall) {

	if fc.IsSilentEnter && len(fc.Params) == 0 {
		return
	}

	e := fc.log.Debug().Str("func", fc.Name).
		Int64("dur", int64(time.Since(fc.EnteredAt)))

	if len(fc.Params) > 0 {
		e = e.Str("params", fmt.Sprintf("%+v", fc.Params))
	}

	if fc.IsSilentEnter {
		e.Msg("enter/exit")
	} else {
		e.Msg("exit")
	}
	return
}

ExitHandler implements default behavior on exit.

If the function started with EnterSilent(), Exit() will be silent as well. If was called OnExit() between, then Exit() lost silence.

View Source
var G = FuncLogger{/* contains filtered or unexported fields */}

G holds global default logger. Use flooger.G to use features without custom FuncLogger.

Functions

This section is empty.

Types

type Field added in v0.0.5

type Field struct {
	Key   string
	Value interface{}
}

func Interface added in v0.0.5

func Interface(key string, value interface{}) Field

type FuncCall added in v0.0.2

type FuncCall struct {
	*FuncLogger
	// Name holds function name.
	Name string
	// EnteredAt time captured by Enter or EnterSilent.
	EnteredAt time.Time

	// IsSilentEnter holds true if the FunCall build by EnterSilent method.
	IsSilentEnter bool

	// Params hold values to be printed in Exit().
	Params []interface{}

	// Ignore holds true if zerolog.Level not DebugLevel or TraceLevel.
	Ignore bool
}

FuncCall holds data needed for a sigle function call tracking and logging.

func (*FuncCall) Debug added in v0.0.2

func (fc *FuncCall) Debug() *zerolog.Event

Debug return zerolog.Event for writing intermetiate log items between Enter() and Exit().

func (*FuncCall) Error added in v0.0.2

func (fc *FuncCall) Error() *zerolog.Event

Error return zerolog.Event for writing intermediate log items between Enter() and Exit().

func (*FuncCall) Exit added in v0.0.2

func (fc *FuncCall) Exit(params ...interface{})

Exit writes to the log function execution duration. If you dont want have 2 log lines in the log (for enter and exit) you can have 1 log line by calling defer flog.EnterSilent().Exit(id, name, age).

func (*FuncCall) Info added in v0.0.2

func (fc *FuncCall) Info() *zerolog.Event

Info return zerolog.Event for writing intermetiate log items between Enter() and Exit().

func (*FuncCall) OnExit added in v0.0.3

func (fc *FuncCall) OnExit(params ...interface{}) *FuncCall

OnExit informs silent function call, that parameters should be written to the log in the Exit() call.

func (*FuncCall) Trace added in v0.0.4

func (fc *FuncCall) Trace() *zerolog.Event

Trace return zerolog.Event for writing intermetiate log items between Enter() and Exit().

func (*FuncCall) Warn added in v0.0.2

func (fc *FuncCall) Warn() *zerolog.Event

Warn return zerolog.Event for writing intermetiate log items between Enter() and Exit().

type FuncLogger added in v0.0.2

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

FuncLogger wraps zerolog logger with type/name pair.

func New

func New(l *zerolog.Logger, typ, name string) FuncLogger

New builds new FuncLogger object. Parameters typ and name will be placed to the log item.

func (*FuncLogger) Enter added in v0.0.2

func (fl *FuncLogger) Enter(params ...interface{}) *FuncCall

Enter builds FuncCall object and writes message "enter" to the log. Log item gets func name and all input parameters.

func (*FuncLogger) EnterSilent added in v0.0.2

func (fl *FuncLogger) EnterSilent() *FuncCall

EnterSilent builds FuncCall object but does not write enter message to the log.

func (*FuncLogger) Logger added in v0.0.2

func (fl *FuncLogger) Logger() zerolog.Logger

Logger returns logger instance.

func (*FuncLogger) SetSecondExitHandler added in v0.0.3

func (fl *FuncLogger) SetSecondExitHandler(f func(*FuncCall)) *FuncLogger

SetSecondExitHandler assigns secondary handler to be called in Exit().

Jump to

Keyboard shortcuts

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