phuslu / log

Fastest structured logging
MIT License
672 stars 44 forks source link

[Question] How can I implement this library with other libraries like Gorm v2? #22

Closed sujit-baniya closed 3 years ago

sujit-baniya commented 3 years ago

Currently Gorm v2 is using it's default logger. I want to use this library for Gorm v2.

How can I implement this library?

Here's the doc they are suggesting to implement but can't figure out how I could implement this log

phuslu commented 3 years ago

I add a PoC for it, you could copy and modify it.

https://github.com/phuslu/log-contrib/blob/master/gorm/logger.go

sujit-baniya commented 3 years ago

@phuslu Awesome Thank you!

sujit-baniya commented 3 years ago

@phuslu This part is not logging at all

if rows == -1 {
            l.Log.Info().Caller(1).Err(err).Dur("elapsed", elapsed).Str("sql", sql).Msg("")
        } else {
            l.Log.Info().Caller(1).Err(err).Dur("elapsed", elapsed).Str("sql", sql).Int64("rows", rows).Msg("")
        }
phuslu commented 3 years ago

try change

case l.Log.Level == log.InfoLevel:

to

default:
sujit-baniya commented 3 years ago

Ah sorry my mistake, it was logging in file but not showing on console.

But weird thing is I've enabled Console Writer with InfoLevel. Still not writing on Console

sujit-baniya commented 3 years ago

I've prepared logger as this:

    writer := &log.MultiWriter{}
    path := MakeDir(filepath.Join(cfg.Server.Path, cfg.Log.InfoLevel.Path))
    writer.InfoWriter = &log.FileWriter{Filename: filepath.Join(path, "INFO.log"), EnsureFolder: true, TimeFormat: cfg.Log.InfoLevel.TimeFormat}

    path = MakeDir(filepath.Join(cfg.Server.Path, cfg.Log.WarnLevel.Path))
    writer.WarnWriter = &log.FileWriter{Filename: filepath.Join(cfg.Server.Path, cfg.Log.WarnLevel.Path, "WARN.log"), EnsureFolder: true, TimeFormat: cfg.Log.WarnLevel.TimeFormat}

    path = MakeDir(filepath.Join(cfg.Server.Path, cfg.Log.ErrorLevel.Path))
    writer.ErrorWriter = &log.FileWriter{Filename: filepath.Join(cfg.Server.Path, cfg.Log.ErrorLevel.Path, "ERROR.log"), EnsureFolder: true, TimeFormat: cfg.Log.ErrorLevel.TimeFormat}
    if cfg.Log.ConsoleLog.Show {
        writer.ConsoleWriter = &log.IOWriter{Writer: os.Stderr}
        writer.ConsoleLevel = log.InfoLevel
    }
    log.DefaultLogger = log.Logger{
        TimeField:  cfg.Log.TimeField,
        TimeFormat: cfg.Log.TimeFormat,
        Writer:     writer,
    }

And calling the logger for gorm like this:

gormLogger := gorm2.Logger{
        Log:    log.DefaultLogger,
    }
    newLogger := gormLogger.LogMode(logger.Info)
sujit-baniya commented 3 years ago

I'm able to fix it. Thanks for support