logadapter

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2023 License: MIT Imports: 18 Imported by: 2

README

go-logadapter

License GolangVersion Release Go Reference

go-logadapter provide a flexible and powerful way to handle logging in applications, and can help in debugging, monitoring, and maintaining the application's performance and behavior

In Go, the logging package provides a simple logging interface for sending log messages to various outputs, such as the console or a file. However, it can be useful to have more advanced logging features, such as the ability to write logs to multiple destinations, format log messages differently based on severity or context, or filter logs based on certain criteria. To accomplish these more advanced logging features, we can use go-logadapter.

It's a piece of code that sits between the application and the logging package and modifies, enhances the way log messages are handled. It's customized to suit for Echo web framework , gorm and still updating.

Advantages of go-logadapter

  • Writing logs to multiple destinations, such as a file, console.
  • Formatting log messages such as JSON, pretty JSON, text.
  • Filtering logs based on certain criteria, such as log level, module, type, or request_id.
  • Suit specific application needs such as echo , gorm
  • Can help in debugging an application by providing detailed information about the application's behavior, performance, and errors.

Requirements

  • Go 1.18+

Getting Started

$ go get -u github.com/vuduongtp/go-logadapter

Import to go

import "github.com/vuduongtp/go-logadapter"

Basic Example

View full example here

Create new simple logger
logger := logadapter.NewLogger()
logger.Debug("test")
{"level":"info","msg":"Logger instance has been successfully initialized","time":"2023-03-05T20:47:28.369102+07:00"}
{"level":"debug","msg":"test","time":"2023-03-05T20:47:28.369163+07:00"}
Create new logger with config
config := &logadapter.Config{
    LogLevel:        logadapter.DebugLevel,
    LogFormat:       logadapter.JSONFormat,
    TimestampFormat: time.RFC3339Nano,
    IsUseLogFile:    true,
}
logger := logadapter.NewLoggerWithConfig(config)
logger.Debug("test")
Set logadapter to gorm logger
config := &logadapter.Config{
    LogLevel:     logadapter.DebugLevel,
    LogFormat:    logadapter.JSONFormat,
    IsUseLogFile: true,
}
logger := logadapter.NewLoggerWithConfig(config)

// * set log adapter for gorm logging
gormConfig := new(gorm.Config)
gormConfig.PrepareStmt = true
gormLogAdapter := logadapter.NewGormLogAdapter(logger)
gormLogAdapter.SlowThreshold = time.Second
gormLogAdapter.SourceField = logadapter.DefaultGormSourceField
gormConfig.Logger = gormLogAdapter 
Set logadapter to Echo
config := &logadapter.Config{
    LogLevel:     logadapter.DebugLevel,
    LogFormat:    logadapter.JSONFormat,
    IsUseLogFile: true,
}
logger := logadapter.NewLoggerWithConfig(config)

e := echo.New()
// * set log adapter for echo instance
e.Logger = logadapter.NewEchoLogAdapter(logger)

// * use log adapter middleware for echo web framework
e.Use(logadapter.NewEchoLoggerMiddleware())

// * log with echo context for log request_id
echoContext := e.AcquireContext() // example echo context, should be replaced with echo.Request().Context()
logadapter.LogWithEchoContext(echoContext, "this is message", logadapter.LogTypeDebug, map[string]interface{}{
    "field_name": "this is log field",
}) // log message with extend field
logadapter.LogWithEchoContext(echoContext, "this is message 2", logadapter.LogTypeError) // log message error
logadapter.LogWithEchoContext(echoContext, "this is message 3")                          // log message debug

If you really want to help us, simply Fork the project and apply for Pull Request. Thanks.

Documentation

Index

Constants

View Source
const (
	LogTypeAPI      = "api"
	LogTypeRequest  = "request"
	LogTypeResponse = "response"
	LogTypeError    = "error"
	LogTypeDebug    = "debug"
	LogTypeSQL      = "sql"
	LogTypeTrace    = "trace"
)

custom logtype

View Source
const (
	DefaultTimestampFormat = "2006-01-02T15:04:05.00000Z07:00"
	DefaultGormSourceField = "source"
)

custom constants

Variables

This section is empty.

Functions

func GetCorrelationID

func GetCorrelationID(ctx context.Context) string

GetCorrelationID return correlation id

func GetLogFile

func GetLogFile() string

GetLogFile get file log

func LogWithEchoContext

func LogWithEchoContext(c echo.Context, content ...interface{})

LogWithEchoContext log content with echo context content[0] : message -> interface{} content[1] : log type -> string content[2] : log field -> map[string]interface{}

func NewEchoLoggerMiddleware

func NewEchoLoggerMiddleware() echo.MiddlewareFunc

NewEchoLoggerMiddleware returns a middleware that logs HTTP requests.

Types

type Config

type Config struct {
	IsUseLogFile    bool        // set true if write to file
	FileConfig      *FileConfig // ignore if IsUseLogFile = false, set null if use default log file config
	LogLevel        Level
	LogFormat       LogFormat
	TimestampFormat string // if empty, use default timestamp format
}

Config config instance log

type EchoLogAdapter

type EchoLogAdapter struct {
	*Logger
}

EchoLogAdapter extend logrus.Logger

func NewEchoLogAdapter

func NewEchoLogAdapter(logger *Logger) *EchoLogAdapter

NewEchoLogAdapter return singleton logger

func (*EchoLogAdapter) Debug

func (l *EchoLogAdapter) Debug(i ...interface{})

Debug output message of debug level

func (*EchoLogAdapter) Debugf

func (l *EchoLogAdapter) Debugf(format string, args ...interface{})

Debugf output format message of debug level

func (*EchoLogAdapter) Debugj

func (l *EchoLogAdapter) Debugj(j log.JSON)

Debugj output message of debug level

func (*EchoLogAdapter) Error

func (l *EchoLogAdapter) Error(i ...interface{})

Error output message of error level

func (*EchoLogAdapter) Errorf

func (l *EchoLogAdapter) Errorf(format string, args ...interface{})

Errorf output format message of error level

func (*EchoLogAdapter) Errorj

func (l *EchoLogAdapter) Errorj(j log.JSON)

Errorj output json of error level

func (*EchoLogAdapter) Fatal

func (l *EchoLogAdapter) Fatal(i ...interface{})

Fatal output message of fatal level

func (*EchoLogAdapter) Fatalf

func (l *EchoLogAdapter) Fatalf(format string, args ...interface{})

Fatalf output format message of fatal level

func (*EchoLogAdapter) Fatalj

func (l *EchoLogAdapter) Fatalj(j log.JSON)

Fatalj output json of fatal level

func (*EchoLogAdapter) Formatter

func (l *EchoLogAdapter) Formatter() logrus.Formatter

Formatter return logger formatter

func (*EchoLogAdapter) Info

func (l *EchoLogAdapter) Info(i ...interface{})

Info output message of info level

func (*EchoLogAdapter) Infof

func (l *EchoLogAdapter) Infof(format string, args ...interface{})

Infof output format message of info level

func (*EchoLogAdapter) Infoj

func (l *EchoLogAdapter) Infoj(j log.JSON)

Infoj output json of info level

func (*EchoLogAdapter) Level

func (l *EchoLogAdapter) Level() log.Lvl

Level return logger level

func (*EchoLogAdapter) Output

func (l *EchoLogAdapter) Output() io.Writer

Output return logger io.Writer

func (*EchoLogAdapter) Panic

func (l *EchoLogAdapter) Panic(i ...interface{})

Panic output message of panic level

func (*EchoLogAdapter) Panicf

func (l *EchoLogAdapter) Panicf(format string, args ...interface{})

Panicf output format message of panic level

func (*EchoLogAdapter) Panicj

func (l *EchoLogAdapter) Panicj(j log.JSON)

Panicj output json of panic level

func (*EchoLogAdapter) Prefix

func (l *EchoLogAdapter) Prefix() string

Prefix return logger prefix This function do nothing

func (*EchoLogAdapter) Print

func (l *EchoLogAdapter) Print(i ...interface{})

Print output message of print level

func (*EchoLogAdapter) Printf

func (l *EchoLogAdapter) Printf(format string, args ...interface{})

Printf output format message of print level

func (*EchoLogAdapter) Printj

func (l *EchoLogAdapter) Printj(j log.JSON)

Printj output json of print level

func (*EchoLogAdapter) SetFormatter

func (l *EchoLogAdapter) SetFormatter(formatter logrus.Formatter)

SetFormatter logger formatter Only support logrus formatter

func (*EchoLogAdapter) SetHeader

func (l *EchoLogAdapter) SetHeader(h string)

SetHeader logger header Managed by Logrus itself This function do nothing

func (*EchoLogAdapter) SetLevel

func (l *EchoLogAdapter) SetLevel(v log.Lvl)

SetLevel logger level

func (*EchoLogAdapter) SetOutput

func (l *EchoLogAdapter) SetOutput(w io.Writer)

SetOutput logger io.Writer

func (*EchoLogAdapter) SetPrefix

func (l *EchoLogAdapter) SetPrefix(p string)

SetPrefix logger prefix This function do nothing

func (*EchoLogAdapter) Warn

func (l *EchoLogAdapter) Warn(i ...interface{})

Warn output message of warn level

func (*EchoLogAdapter) Warnf

func (l *EchoLogAdapter) Warnf(format string, args ...interface{})

Warnf output format message of warn level

func (*EchoLogAdapter) Warnj

func (l *EchoLogAdapter) Warnj(j log.JSON)

Warnj output json of warn level

type FileConfig

type FileConfig struct {
	Filename       string
	MaxSize        int // megabytes
	MaxBackups     int // number of log files
	MaxAge         int // days
	IsCompress     bool
	IsUseLocalTime bool
}

FileConfig config for write log to file

type GormLogAdapter

type GormLogAdapter struct {
	*Logger
	SlowThreshold         time.Duration
	SourceField           string
	SkipErrRecordNotFound bool
	Debug                 bool
}

GormLogAdapter model

func NewGormLogAdapter

func NewGormLogAdapter(log *Logger) *GormLogAdapter

NewGormLogAdapter gorm logrus GormLogAdapter

func (*GormLogAdapter) Error

func (l *GormLogAdapter) Error(ctx context.Context, s string, args ...interface{})

Error function

func (*GormLogAdapter) Info

func (l *GormLogAdapter) Info(ctx context.Context, s string, args ...interface{})

Info function

func (*GormLogAdapter) LogMode

LogMode function

func (*GormLogAdapter) Trace

func (l *GormLogAdapter) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)

Trace function

func (*GormLogAdapter) Warn

func (l *GormLogAdapter) Warn(ctx context.Context, s string, args ...interface{})

Warn function

type Key

type Key string

Key is key context type

const (
	CorrelationIDKey Key = "X-User-Correlation-Id"
	RequestIDKey     Key = "X-Request-ID"
)

Exported constanst

type Level

type Level uint32

Level log level

const (
	// PanicLevel level, highest level of severity. Logs and then calls panic with the
	// message passed to Debug, Info, ...
	PanicLevel Level = iota
	// FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the
	// logging level is set to Panic.
	FatalLevel
	// ErrorLevel level. Logs. Used for errors that should definitely be noted.
	// Commonly used for hooks to send errors to an error tracking service.
	ErrorLevel
	// WarnLevel level. Non-critical entries that deserve eyes.
	WarnLevel
	// InfoLevel level. General operational entries about what's going on inside the
	// application.
	InfoLevel
	// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
	DebugLevel
	// TraceLevel level. Designates finer-grained informational events than the Debug.
	TraceLevel
)

type LogFormat

type LogFormat uint32

LogFormat log format

const (
	JSONFormat LogFormat = iota
	PrettyJSONFormat
	TextFormat
)

custom log format

type Logger added in v1.0.1

type Logger struct {
	*log.Logger
	// contains filtered or unexported fields
}

Logger instance

func NewLogger added in v1.0.1

func NewLogger() *Logger

NewLogger returns a logger instance with default configuration

func NewLoggerWithConfig added in v1.0.1

func NewLoggerWithConfig(config *Config) *Logger

NewLoggerWithConfig returns a logger instance with custom configuration

func (*Logger) SetFormatter added in v1.0.1

func (l *Logger) SetFormatter(logFormat LogFormat)

SetFormatter logger formatter

func (*Logger) SetLevel added in v1.0.1

func (l *Logger) SetLevel(level Level)

SetLevel set log level

func (*Logger) SetLogConsole added in v1.0.1

func (l *Logger) SetLogConsole()

SetLogConsole set log console

func (*Logger) SetLogFile added in v1.0.1

func (l *Logger) SetLogFile(fileConfig *FileConfig)

SetLogFile set log file

func (*Logger) SetTimestampFormat added in v1.0.2

func (l *Logger) SetTimestampFormat(timestampFormat string)

SetTimestampFormat set timestamp format

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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