Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

logger v2 #7

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.21
require (
github.com/onsi/ginkgo/v2 v2.9.5
github.com/onsi/gomega v1.27.7
github.com/sirupsen/logrus v1.9.0
github.com/stretchr/testify v1.8.1
go.uber.org/zap v1.24.0
golang.org/x/net v0.17.0
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ github.com/prometheus/procfs v0.9.0 h1:wzCHvIvM5SxWqYvwgVL7yJY8Lz3PKn49KQtpgMYJf
github.com/prometheus/procfs v0.9.0/go.mod h1:+pB4zwohETzFnmlpe6yd2lSc+0/46IYZRB/chUwxUZY=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8=
Expand Down Expand Up @@ -193,6 +195,7 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE=
golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
Expand Down
90 changes: 90 additions & 0 deletions internal/logger/logger_utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package logger

import (
"context"
"github.com/sirupsen/logrus"
"os"
"path/filepath"
)

type LogLevel string

const (
InfoLevel LogLevel = "info"
WarnLevel LogLevel = "warn"
ErrorLevel LogLevel = "error"
TraceID string = "traceID"
)

type Fields map[string]interface{}

type Logger struct {
moduleName string
logger *logrus.Entry
}

type Config struct {
ModuleToFile map[string]string
LogLevel LogLevel
LogFormat logrus.Formatter
}

var config Config

func Initialize(cfg Config) {
config = cfg
logrus.SetFormatter(config.LogFormat)
switch config.LogLevel {
case InfoLevel:
logrus.SetLevel(logrus.InfoLevel)
case WarnLevel:
logrus.SetLevel(logrus.WarnLevel)
case ErrorLevel:
logrus.SetLevel(logrus.ErrorLevel)
default:
logrus.SetLevel(logrus.InfoLevel)
}

for _, file := range config.ModuleToFile {
path := filepath.Dir(file)
if err := os.MkdirAll(path, os.ModePerm); err != nil {
logrus.WithError(err).Fatal("cannot create log directory")
}
file, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
logrus.WithError(err).Fatal("cannot open log file")
}

logrus.SetOutput(file)
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The logger output is set to the last file in the loop, which likely causes all logs to be written to the same file.

- logrus.SetOutput(file)
+ logger.SetOutput(file)  // Ensure each logger instance has its correct output file.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
func Initialize(cfg Config) {
config = cfg
logrus.SetFormatter(config.LogFormat)
switch config.LogLevel {
case InfoLevel:
logrus.SetLevel(logrus.InfoLevel)
case WarnLevel:
logrus.SetLevel(logrus.WarnLevel)
case ErrorLevel:
logrus.SetLevel(logrus.ErrorLevel)
default:
logrus.SetLevel(logrus.InfoLevel)
}
for _, file := range config.ModuleToFile {
path := filepath.Dir(file)
if err := os.MkdirAll(path, os.ModePerm); err != nil {
logrus.WithError(err).Fatal("cannot create log directory")
}
file, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
logrus.WithError(err).Fatal("cannot open log file")
}
logrus.SetOutput(file)
}
}
func Initialize(cfg Config) {
config = cfg
logrus.SetFormatter(config.LogFormat)
switch config.LogLevel {
case InfoLevel:
logrus.SetLevel(logrus.InfoLevel)
case WarnLevel:
logrus.SetLevel(logrus.WarnLevel)
case ErrorLevel:
logrus.SetLevel(logrus.ErrorLevel)
default:
logrus.SetLevel(logrus.InfoLevel)
}
for _, file := range config.ModuleToFile {
path := filepath.Dir(file)
if err := os.MkdirAll(path, os.ModePerm); err != nil {
logrus.WithError(err).Fatal("cannot create log directory")
}
file, err := os.OpenFile(file, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
logrus.WithError(err).Fatal("cannot open log file")
}
logger.SetOutput(file) // Ensure each logger instance has its correct output file.
}
}


func New(moduleName string) *Logger {
return &Logger{
moduleName: moduleName,
logger: logrus.WithField("module", moduleName),
}
}

func NewFromContext(ctx context.Context, moduleName string) *Logger {
traceID, ok := ctx.Value(TraceID).(string)
if !ok {
traceID = "unknown"
}
return &Logger{
moduleName: moduleName,
logger: logrus.WithField("module", moduleName).WithField(TraceID, traceID),
}
}

func (l *Logger) Info(fields Fields, message string) {
l.logger.WithFields(logrus.Fields(fields)).Info(message)
}

func (l *Logger) Warn(fields Fields, message string) {
l.logger.WithFields(logrus.Fields(fields)).Warn(message)
}

func (l *Logger) Error(fields Fields, message string) {
l.logger.WithFields(logrus.Fields(fields)).Error(message)
}
40 changes: 40 additions & 0 deletions internal/logger/logger_utils_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package logger

import (
"context"
"github.com/sirupsen/logrus"
"testing"
)

func TestLogger_Schedule_Json(t *testing.T) {
config := Config{ModuleToFile: map[string]string{
"schedule": "logs/schedule.log",
"module_controller": "logs/module_controller.log",
},
LogLevel: InfoLevel,
LogFormat: &logrus.JSONFormatter{},
}

Initialize(config)

logger := New("schedule")
logger.Info(Fields{"hello": "word", "foo": "bar"}, "message")
logger.Error(Fields{"key": "value"}, "a mc error occurred")
}

func TestLogger_module_controller_text(t *testing.T) {
config := Config{ModuleToFile: map[string]string{
"schedule": "logs/schedule.log",
"module_controller": "logs/module_controller.log",
},
LogLevel: InfoLevel,
LogFormat: &logrus.TextFormatter{},
}

Initialize(config)

ctx := context.WithValue(context.Background(), TraceID, "12345")
logger := NewFromContext(ctx, "module_controller")
logger.Info(Fields{"hello": "word", "foo": "bar"}, "message")
logger.Error(Fields{"key": "value"}, "a mc error occurred")
}
Loading