fix: resolved comments

This commit is contained in:
mayur.popli
2025-03-26 10:38:44 +05:30
parent e328dd4f14
commit f8ffe0793d
2 changed files with 41 additions and 48 deletions

View File

@@ -17,7 +17,9 @@ import (
) )
type Level string type Level string
type DestinationType string type DestinationType string
type Destination struct { type Destination struct {
Type DestinationType `yaml:"type"` Type DestinationType `yaml:"type"`
Config map[string]string `yaml:"config"` Config map[string]string `yaml:"config"`
@@ -47,9 +49,9 @@ var logLevels = map[Level]zerolog.Level{
} }
type Config struct { type Config struct {
level Level `yaml:"level"` Level Level `yaml:"level"`
destinations []Destination `yaml:"destinations"` Destinations []Destination `yaml:"destinations"`
contextKeys []any `yaml:"contextKeys"` ContextKeys []any `yaml:"contextKeys"`
} }
var ( var (
@@ -64,16 +66,16 @@ var (
ErrMissingFilePath = errors.New("file path missing in destination config for file logging") ErrMissingFilePath = errors.New("file path missing in destination config for file logging")
) )
func (config *Config) Validate() error { func (config *Config) validate() error {
if _, exists := logLevels[config.level]; !exists { if _, exists := logLevels[config.Level]; !exists {
return ErrInvalidLogLevel return ErrInvalidLogLevel
} }
if len(config.destinations) == 0 { if len(config.Destinations) == 0 {
return ErrLogDestinationNil return ErrLogDestinationNil
} }
for _, dest := range config.destinations { for _, dest := range config.Destinations {
switch dest.Type { switch dest.Type {
case Stdout: case Stdout:
case File: case File:
@@ -96,11 +98,10 @@ func (config *Config) Validate() error {
} }
var defaultConfig = Config{ var defaultConfig = Config{
level: InfoLevel, Level: InfoLevel,
destinations: []Destination{ Destinations: []Destination{
{Type: Stdout}, {Type: Stdout},
}, },
contextKeys: []any{"userID", "requestID"},
} }
func init() { func init() {
@@ -110,7 +111,7 @@ func init() {
func getLogger(config Config) (zerolog.Logger, error) { func getLogger(config Config) (zerolog.Logger, error) {
var newLogger zerolog.Logger var newLogger zerolog.Logger
var writers []io.Writer var writers []io.Writer
for _, dest := range config.destinations { for _, dest := range config.Destinations {
switch dest.Type { switch dest.Type {
case Stdout: case Stdout:
writers = append(writers, os.Stdout) writers = append(writers, os.Stdout)
@@ -120,20 +121,14 @@ func getLogger(config Config) (zerolog.Logger, error) {
if err := os.MkdirAll(dir, os.ModePerm); err != nil { if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return newLogger, fmt.Errorf("failed to create log directory: %v", err) return newLogger, fmt.Errorf("failed to create log directory: %v", err)
} }
fmt.Printf("writing test log to file: %v\n", config)
lumberjackLogger := &lumberjack.Logger{ lumberjackLogger := &lumberjack.Logger{
Filename: filePath, Filename: filePath,
MaxSize: 500, // Default size in MB if not overridden
MaxBackups: 15, // Number of backups
MaxAge: 30, // Days to retain
Compress: false, Compress: false,
} }
absPath, err := filepath.Abs(filePath) absPath, err := filepath.Abs(filePath)
if err != nil { if err != nil {
return newLogger, fmt.Errorf("failed to get absolute path: %v", err) return newLogger, fmt.Errorf("failed to get absolute path: %v", err)
} }
fmt.Printf("Attempting to write logs to: %s\n", absPath)
lumberjackLogger.Filename = absPath lumberjackLogger.Filename = absPath
setConfigValue := func(key string, target *int) { setConfigValue := func(key string, target *int) {
@@ -159,30 +154,27 @@ func getLogger(config Config) (zerolog.Logger, error) {
} }
}() }()
newLogger = zerolog.New(multiwriter). newLogger = zerolog.New(multiwriter).
Level(logLevels[config.level]). Level(logLevels[config.Level]).
With(). With().
Timestamp(). Timestamp().
Caller().
Logger() Logger()
cfg = config cfg = config
return newLogger, nil return newLogger, nil
} }
func InitLogger(c Config) error { func InitLogger(c Config) error {
var initErr error var initErr error
once.Do(func() { once.Do(func() {
if err := c.Validate(); err != nil { if initErr = c.validate(); initErr != nil {
return return
} }
logger, initErr = getLogger(c) logger, initErr = getLogger(c)
if initErr != nil {
return
}
}) })
return initErr return initErr
} }
func Debug(ctx context.Context, msg string) { func Debug(ctx context.Context, msg string) {
logEvent(ctx, zerolog.DebugLevel, msg, nil) logEvent(ctx, zerolog.DebugLevel, msg, nil)
} }
@@ -246,6 +238,7 @@ func logEvent(ctx context.Context, level zerolog.Level, msg string, err error) {
addCtx(ctx, event) addCtx(ctx, event)
event.Msg(msg) event.Msg(msg)
} }
func Request(ctx context.Context, r *http.Request, body []byte) { func Request(ctx context.Context, r *http.Request, body []byte) {
event := logger.Info() event := logger.Info()
addCtx(ctx, event) addCtx(ctx, event)
@@ -257,13 +250,13 @@ func Request(ctx context.Context, r *http.Request, body []byte) {
} }
func addCtx(ctx context.Context, event *zerolog.Event) { func addCtx(ctx context.Context, event *zerolog.Event) {
for _, key := range cfg.contextKeys { for _, key := range cfg.ContextKeys {
val, ok := ctx.Value(key).(string) val, ok := ctx.Value(key).(string)
if !ok { if !ok {
continue continue
} }
keyStr := key.(string) keyStr := key.(string)
event.Str(keyStr, val) event.Any(keyStr, val)
} }
} }

View File

@@ -30,8 +30,8 @@ func setupLogger(t *testing.T, l Level) string {
} }
config := Config{ config := Config{
level: l, Level: l,
destinations: []Destination{ Destinations: []Destination{
{ {
Type: File, Type: File,
Config: map[string]string{ Config: map[string]string{
@@ -43,7 +43,7 @@ func setupLogger(t *testing.T, l Level) string {
}, },
}, },
}, },
contextKeys: []any{"userID", "requestID"}, ContextKeys: []any{"userID", "requestID"},
} }
err = InitLogger(config) err = InitLogger(config)
if err != nil { if err != nil {
@@ -403,8 +403,8 @@ func TestValidateConfig(t *testing.T) {
{ {
name: "Valid config with Stdout", name: "Valid config with Stdout",
config: Config{ config: Config{
level: InfoLevel, Level: InfoLevel,
destinations: []Destination{ Destinations: []Destination{
{Type: Stdout}, {Type: Stdout},
}, },
}, },
@@ -413,8 +413,8 @@ func TestValidateConfig(t *testing.T) {
{ {
name: "Valid config with File destination and valid path", name: "Valid config with File destination and valid path",
config: Config{ config: Config{
level: InfoLevel, Level: InfoLevel,
destinations: []Destination{ Destinations: []Destination{
{ {
Type: File, Type: File,
Config: map[string]string{ Config: map[string]string{
@@ -431,8 +431,8 @@ func TestValidateConfig(t *testing.T) {
{ {
name: "Error: Invalid log level", name: "Error: Invalid log level",
config: Config{ config: Config{
level: "invalid", Level: "invalid",
destinations: []Destination{ Destinations: []Destination{
{Type: Stdout}, {Type: Stdout},
}, },
}, },
@@ -441,16 +441,16 @@ func TestValidateConfig(t *testing.T) {
{ {
name: "Error: No destinations provided", name: "Error: No destinations provided",
config: Config{ config: Config{
level: InfoLevel, Level: InfoLevel,
destinations: []Destination{}, Destinations: []Destination{},
}, },
wantErr: ErrLogDestinationNil, wantErr: ErrLogDestinationNil,
}, },
{ {
name: "Error: Invalid destination type", name: "Error: Invalid destination type",
config: Config{ config: Config{
level: InfoLevel, Level: InfoLevel,
destinations: []Destination{ Destinations: []Destination{
{Type: "unknown"}, {Type: "unknown"},
}, },
}, },
@@ -459,8 +459,8 @@ func TestValidateConfig(t *testing.T) {
{ {
name: "Error: Missing file path for file destination", name: "Error: Missing file path for file destination",
config: Config{ config: Config{
level: InfoLevel, Level: InfoLevel,
destinations: []Destination{ Destinations: []Destination{
{ {
Type: File, Type: File,
Config: map[string]string{ Config: map[string]string{
@@ -474,8 +474,8 @@ func TestValidateConfig(t *testing.T) {
{ {
name: "Error: Invalid maxSize value in file destination", name: "Error: Invalid maxSize value in file destination",
config: Config{ config: Config{
level: InfoLevel, Level: InfoLevel,
destinations: []Destination{ Destinations: []Destination{
{ {
Type: File, Type: File,
Config: map[string]string{ Config: map[string]string{
@@ -490,8 +490,8 @@ func TestValidateConfig(t *testing.T) {
{ {
name: "Error: Invalid maxBackups value in file destination", name: "Error: Invalid maxBackups value in file destination",
config: Config{ config: Config{
level: InfoLevel, Level: InfoLevel,
destinations: []Destination{ Destinations: []Destination{
{ {
Type: File, Type: File,
Config: map[string]string{ Config: map[string]string{
@@ -506,8 +506,8 @@ func TestValidateConfig(t *testing.T) {
{ {
name: "Error: Invalid maxAge value in file destination", name: "Error: Invalid maxAge value in file destination",
config: Config{ config: Config{
level: InfoLevel, Level: InfoLevel,
destinations: []Destination{ Destinations: []Destination{
{ {
Type: File, Type: File,
Config: map[string]string{ Config: map[string]string{
@@ -523,7 +523,7 @@ func TestValidateConfig(t *testing.T) {
for _, tt := range tests { for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) { t.Run(tt.name, func(t *testing.T) {
err := tt.config.Validate() err := tt.config.validate()
if (err == nil) != (tt.wantErr == nil) { if (err == nil) != (tt.wantErr == nil) {
t.Errorf("validate() error = %v, wantErr %v", err, tt.wantErr) t.Errorf("validate() error = %v, wantErr %v", err, tt.wantErr)
} }