Skip to content

Commit

Permalink
add set timestamp format
Browse files Browse the repository at this point in the history
  • Loading branch information
vuduongtp committed Mar 5, 2023
1 parent d1d3699 commit 69d8127
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 39 deletions.
30 changes: 18 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,18 @@
[![License](https://img.shields.io/github/license/mashape/apistatus.svg)](https://github.com/vuduongtp/go-logadapter/blob/main/LICENSE)
![GolangVersion](https://img.shields.io/github/go-mod/go-version/vuduongtp/go-logadapter)
[![Release](https://img.shields.io/github/v/release/vuduongtp/go-logadapter)](https://github.com/vuduongtp/go-logadapter/releases)
[![Go Reference](https://pkg.go.dev/badge/github.com/vuduongtp/go-logadapter.svg)](https://pkg.go.dev/github.com/vuduongtp/go-logadapter)

## 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.
**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](https://github.com/labstack/echo) and [gorm](https://github.com/go-gorm/gorm) and still updating.
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](https://github.com/labstack/echo) , [gorm](https://github.com/go-gorm/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
- Suit specific application needs such as [echo](https://github.com/labstack/echo) , [gorm](https://github.com/go-gorm/gorm)
- Can help in debugging an application by providing detailed information about the application's behavior, performance, and errors.

## Requirements
Expand All @@ -29,22 +30,27 @@ $ go get -u github.com/vuduongtp/go-logadapter
import "github.com/vuduongtp/go-logadapter"
```
## Basic Example

View full example [here](https://github.com/vuduongtp/go-logadapter/blob/main/test/test.go)
### Create new simple logger
```go
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
```go
config := &logadapter.Config{
LogLevel: logadapter.DebugLevel,
LogFormat: logadapter.JSONFormat,
IsUseLogFile: true,
LogLevel: logadapter.DebugLevel,
LogFormat: logadapter.JSONFormat,
TimestampFormat: time.RFC3339Nano,
IsUseLogFile: true,
}
logger := logadapter.NewLoggerWithConfig(config)
logger.Debug("test")
```
### Create new default logger
```go
logger := logadapter.NewLogger()
logger.Debug("test")
```
### Set logadapter to gorm logger
```go
config := &logadapter.Config{
Expand Down
2 changes: 1 addition & 1 deletion echo_adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ func NewEchoLoggerMiddleware() echo.MiddlewareFunc {
}

// * set request_id to request context
ctx := WithCorrelationID(c.Request().Context(), id)
ctx := withCorrelationID(c.Request().Context(), id)
request := c.Request().WithContext(ctx)
c.SetRequest(request)

Expand Down
5 changes: 0 additions & 5 deletions gorm_adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,6 @@ import (
"gorm.io/gorm/utils"
)

// custom constant for gorm logger
const (
DefaultGormSourceField = "source"
)

// GormLogAdapter model
type GormLogAdapter struct {
*Logger
Expand Down
61 changes: 45 additions & 16 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,19 @@ const (
LogTypeTrace = "trace"
)

// custom constants
const (
DefaultTimestampFormat = "2006-01-02T15:04:05.00000Z07:00"
DefaultGormSourceField = "source"
)

// LogFormat log format
type LogFormat uint32

// custom log format
const (
JSONFormat LogFormat = iota
JSONFormatIndent
PrettyJSONFormat
TextFormat
)

Expand Down Expand Up @@ -55,10 +61,11 @@ const (

// Config config instance log
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
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
}

// FileConfig config for write log to file
Expand All @@ -74,19 +81,34 @@ type FileConfig struct {
// Logger instance
type Logger struct {
*log.Logger
logFormat LogFormat
}

// SetFormatter logger formatter
func (l *Logger) SetFormatter(logFormat LogFormat) {
switch logFormat {
case JSONFormat:
l.Logger.SetFormatter(&log.JSONFormatter{})
l.Logger.SetFormatter(&log.JSONFormatter{TimestampFormat: DefaultTimestampFormat})

case PrettyJSONFormat:
l.Logger.SetFormatter(&log.JSONFormatter{PrettyPrint: true, TimestampFormat: DefaultTimestampFormat})

default:
l.Logger.SetFormatter(&log.TextFormatter{TimestampFormat: DefaultTimestampFormat})
}
}

// SetTimestampFormat set timestamp format
func (l *Logger) SetTimestampFormat(timestampFormat string) {
switch l.logFormat {
case JSONFormat:
l.Logger.SetFormatter(&log.JSONFormatter{TimestampFormat: timestampFormat})

case JSONFormatIndent:
l.Logger.SetFormatter(&log.JSONFormatter{PrettyPrint: true})
case PrettyJSONFormat:
l.Logger.SetFormatter(&log.JSONFormatter{PrettyPrint: true, TimestampFormat: timestampFormat})

default:
l.Logger.SetFormatter(&log.TextFormatter{})
l.Logger.SetFormatter(&log.TextFormatter{TimestampFormat: timestampFormat})
}
}

Expand Down Expand Up @@ -131,9 +153,10 @@ func getDefaultFileConfig() *FileConfig {

func getDefaultConfig() *Config {
return &Config{
LogLevel: DebugLevel,
LogFormat: JSONFormat,
IsUseLogFile: false,
LogLevel: DebugLevel,
LogFormat: JSONFormat,
IsUseLogFile: false,
TimestampFormat: DefaultTimestampFormat,
}
}

Expand All @@ -142,10 +165,13 @@ func NewLoggerWithConfig(config *Config) *Logger {
if config == nil {
config = getDefaultConfig()
}

logger := log.New()
loggerInstance := &Logger{logger}
loggerInstance := &Logger{Logger: logger}
loggerInstance.logFormat = config.LogFormat
loggerInstance.SetFormatter(config.LogFormat)
if len(config.TimestampFormat) > 0 {
loggerInstance.SetTimestampFormat(config.TimestampFormat)
}
if config.IsUseLogFile == true {
loggerInstance.SetLogFile(config.FileConfig)
} else {
Expand All @@ -160,10 +186,13 @@ func NewLoggerWithConfig(config *Config) *Logger {
// NewLogger returns a logger instance with default configuration
func NewLogger() *Logger {
config := getDefaultConfig()

logger := log.New()
loggerInstance := &Logger{logger}
loggerInstance := &Logger{Logger: logger}
loggerInstance.SetFormatter(config.LogFormat)
loggerInstance.logFormat = config.LogFormat
if len(config.TimestampFormat) > 0 {
loggerInstance.SetTimestampFormat(config.TimestampFormat)
}
if config.IsUseLogFile == true {
loggerInstance.SetLogFile(config.FileConfig)
} else {
Expand Down
7 changes: 4 additions & 3 deletions test/test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ func main() {

func testCreateInstance() {
config := &logadapter.Config{
LogLevel: logadapter.DebugLevel,
LogFormat: logadapter.JSONFormat,
IsUseLogFile: true,
LogLevel: logadapter.DebugLevel,
LogFormat: logadapter.JSONFormat,
TimestampFormat: time.RFC3339Nano,
IsUseLogFile: true,
}
logger := logadapter.NewLoggerWithConfig(config)
logger.Debug("test")
Expand Down
4 changes: 2 additions & 2 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ const (
RequestIDKey Key = "X-Request-ID"
)

// WithCorrelationID sets correlation id to context
func WithCorrelationID(parent context.Context, correlationID string) context.Context {
// withCorrelationID sets correlation id to context
func withCorrelationID(parent context.Context, correlationID string) context.Context {
return context.WithValue(parent, CorrelationIDKey, correlationID)
}

Expand Down

0 comments on commit 69d8127

Please sign in to comment.