lecho

package module
v3.5.1 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2024 License: MIT Imports: 10 Imported by: 0

README

lecho 🍅

Zerolog wrapper for Echo web framework.

Installation

For Echo v4:

go get github.com/ziflex/lecho/v3

add your go.mod

replace github.com/ziflex/lecho/v3 => github.com/satoof2/lecho/v3 v3.5.0

Quick start

package main 

import (
	"os"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/ziflex/lecho/v3"
)

func main() {
    e := echo.New()
    e.Logger = lecho.New(os.Stdout)
}
Using existing zerolog instance
package main 

import (
	"os"
	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
	"github.com/ziflex/lecho/v3"
        "github.com/rs/zerolog"
)

func main() {
    log := zerolog.New(os.Stdout)
    e := echo.New()
    e.Logger = lecho.From(log)
}

Options


import (
	"os",
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
	"github.com/ziflex/lecho/v3"
)

func main() {
    e := echo.New()
    e.Logger = lecho.New(
       os.Stdout,
       lecho.WithLevel(log.DEBUG),
       lecho.WithFields(map[string]interface{}{ "name": "lecho factory"}),
       lecho.WithTimestamp(),
       lecho.WithCaller(),
       lecho.WithPrefix("we ❤️ lecho"),
       lecho.WithHook(...),
       lecho.WithHookFunc(...),
    )
}

Middleware

Logging requests and attaching request id to a context logger

import (
	"os",
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
	"github.com/ziflex/lecho/v3"
	"github.com/rs/zerolog"
)

func main() {
    e := echo.New()
    logger := lecho.New(
            os.Stdout,
            lecho.WithLevel(log.DEBUG),
            lecho.WithTimestamp(),
            lecho.WithCaller(),
         )
    e.Logger = logger
    
    e.Use(middleware.RequestID())
    e.Use(lecho.Middleware(lecho.Config{
    	Logger: logger
    }))	
    e.GET("/", func(c echo.Context) error {
        c.Logger().Print("Echo interface")
        zerolog.Ctx(c.Request().Context()).Print("Zerolog interface")
	
	return c.String(http.StatusOK, "Hello, World!")
    })
}
Nesting under a sub dictionary
e.Use(lecho.Middleware(lecho.Config{
        Logger: logger,
        NestKey: "request"
    }))
    // Output: {"level":"info","request":{"remote_ip":"5.6.7.8","method":"GET", ...}, ...}
Enricher

Enricher allows you to add additional fields to the log entry.

e.Use(lecho.Middleware(lecho.Config{
        Logger: logger,
        Enricher: func(c echo.Context, logger zerolog.Context) zerolog.Context {
            return e.Str("user_id", c.Get("user_id"))
        },
    }))
    // Output: {"level":"info","user_id":"123", ...}
Errors

Since lecho v3.4.0, the middleware does not automatically propagate errors up the chain. If you want to do that, you can set HandleError to true.

e.Use(lecho.Middleware(lecho.Config{
    Logger: logger,
    HandleError: true,
}))

Helpers

Level converters

import (
    "fmt",
    "github.com/labstack/echo"
    "github.com/labstack/echo/middleware"
    "github.com/labstack/gommon/log"
    "github.com/ziflex/lecho/v3"
)

func main() {
	var z zerolog.Level
	var e log.Lvl
	
    z, e = lecho.MatchEchoLevel(log.WARN)
    
    fmt.Println(z, e)
    
    e, z = lecho.MatchZeroLevel(zerolog.INFO)

    fmt.Println(z, e)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Ctx

func Ctx(ctx context.Context) *zerolog.Logger

Ctx returns a logger from the provided context. If no logger is found in the context, a new one is created.

func MatchEchoLevel

func MatchEchoLevel(level log.Lvl) (zerolog.Level, log.Lvl)

MatchEchoLevel returns a zerolog level and echo level for a given echo level

func MatchZeroLevel

func MatchZeroLevel(level zerolog.Level) (log.Lvl, zerolog.Level)

MatchZeroLevel returns an echo level and zerolog level for a given zerolog level

func Middleware

func Middleware(config Config) echo.MiddlewareFunc

Middleware returns a middleware which logs HTTP requests.

Types

type Config

type Config struct {
	// Logger is a custom instance of the logger to use.
	Logger *Logger
	// Skipper defines a function to skip middleware.
	Skipper middleware.Skipper
	// BeforeNext is a function that is executed before the next handler is called.
	BeforeNext middleware.BeforeFunc
	// Enricher is a function that can be used to enrich the logger with additional information.
	Enricher Enricher
	// RequestIDHeader is the header name to use for the request ID in a log record.
	RequestIDHeader string
	// RequestIDKey is the key name to use for the request ID in a log record.
	RequestIDKey string
	// NestKey is the key name to use for the nested logger in a log record.
	NestKey string
	// HandleError indicates whether to propagate errors up the middleware chain, so the global error handler can decide appropriate status code.
	HandleError bool
}

Config is the configuration for the middleware.

type Context

type Context struct {
	echo.Context
	// contains filtered or unexported fields
}

Context is a wrapper around echo.Context that provides a logger.

func NewContext

func NewContext(ctx echo.Context, logger *Logger) *Context

NewContext returns a new Context.

func (*Context) Logger

func (c *Context) Logger() echo.Logger

type Enricher

type Enricher func(c echo.Context, logger zerolog.Context) zerolog.Context

Enricher is a function that can be used to enrich the logger with additional information.

type InfoWriter

type InfoWriter struct {
	Logger *zerolog.Logger
}

func (InfoWriter) Write

func (w InfoWriter) Write(p []byte) (n int, err error)

type Logger

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

Logger is a wrapper around `zerolog.Logger` that provides an implementation of `echo.Logger` interface

func From

func From(log zerolog.Logger, setters ...Setter) *Logger

From returns a new Logger instance using existing zerolog log.

func New

func New(out io.Writer, setters ...Setter) *Logger

New returns a new Logger instance

func (Logger) Debug

func (l Logger) Debug(i ...interface{})

func (Logger) Debugf

func (l Logger) Debugf(format string, i ...interface{})

func (Logger) Debugj

func (l Logger) Debugj(j log.JSON)

func (Logger) Error

func (l Logger) Error(i ...interface{})

func (Logger) Errorf

func (l Logger) Errorf(format string, i ...interface{})

func (Logger) Errorj

func (l Logger) Errorj(j log.JSON)

func (Logger) Fatal

func (l Logger) Fatal(i ...interface{})

func (Logger) Fatalf

func (l Logger) Fatalf(format string, i ...interface{})

func (Logger) Fatalj

func (l Logger) Fatalj(j log.JSON)

func (Logger) Info

func (l Logger) Info(i ...interface{})

func (Logger) Infof

func (l Logger) Infof(format string, i ...interface{})

func (Logger) Infoj

func (l Logger) Infoj(j log.JSON)

func (Logger) Level

func (l Logger) Level() log.Lvl

func (Logger) Output

func (l Logger) Output() io.Writer

func (Logger) Panic

func (l Logger) Panic(i ...interface{})

func (Logger) Panicf

func (l Logger) Panicf(format string, i ...interface{})

func (Logger) Panicj

func (l Logger) Panicj(j log.JSON)

func (Logger) Prefix

func (l Logger) Prefix() string

func (Logger) Print

func (l Logger) Print(i ...interface{})

func (Logger) Printf

func (l Logger) Printf(format string, i ...interface{})

func (Logger) Printj

func (l Logger) Printj(j log.JSON)

func (Logger) SetHeader

func (l Logger) SetHeader(h string)

func (*Logger) SetLevel

func (l *Logger) SetLevel(level log.Lvl)

func (*Logger) SetOutput

func (l *Logger) SetOutput(newOut io.Writer)

func (*Logger) SetPrefix

func (l *Logger) SetPrefix(newPrefix string)

func (*Logger) Unwrap

func (l *Logger) Unwrap() zerolog.Logger

func (Logger) Warn

func (l Logger) Warn(i ...interface{})

func (Logger) Warnf

func (l Logger) Warnf(format string, i ...interface{})

func (Logger) Warnj

func (l Logger) Warnj(j log.JSON)

func (Logger) WithContext

func (l Logger) WithContext(ctx context.Context) context.Context

WithContext returns a new context with the provided logger.

type Options

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

type Setter

type Setter func(opts *Options)

func WithCaller

func WithCaller() Setter

func WithCallerWithSkipFrameCount

func WithCallerWithSkipFrameCount(skipFrameCount int) Setter

func WithField

func WithField(name string, value interface{}) Setter

func WithFields

func WithFields(fields map[string]interface{}) Setter

func WithHook

func WithHook(hook zerolog.Hook) Setter

func WithHookFunc

func WithHookFunc(hook zerolog.HookFunc) Setter

func WithLevel

func WithLevel(level log.Lvl) Setter

func WithPrefix

func WithPrefix(prefix string) Setter

func WithTimestamp

func WithTimestamp() Setter

Jump to

Keyboard shortcuts

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