2021-09-07 09:53:18 +02:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
|
|
"gopkg.in/natefinch/lumberjack.v2"
|
|
|
|
"io"
|
2022-03-10 14:14:00 +01:00
|
|
|
"path"
|
2021-09-07 09:53:18 +02:00
|
|
|
"path/filepath"
|
2022-03-10 14:14:00 +01:00
|
|
|
"runtime"
|
|
|
|
"strconv"
|
2021-09-07 09:53:18 +02:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// InitLog parses and sets log-level input
|
|
|
|
func InitLog(logLevel string, logPath string) error {
|
|
|
|
level, err := log.ParseLevel(logLevel)
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Failed parsing log-level %s: %s", logLevel, err)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
if logPath != "" && logPath != "console" {
|
|
|
|
lumberjackLogger := &lumberjack.Logger{
|
|
|
|
// Log file absolute path, os agnostic
|
|
|
|
Filename: filepath.ToSlash(logPath),
|
|
|
|
MaxSize: 5, // MB
|
|
|
|
MaxBackups: 10,
|
|
|
|
MaxAge: 30, // days
|
|
|
|
Compress: true,
|
|
|
|
}
|
|
|
|
log.SetOutput(io.Writer(lumberjackLogger))
|
|
|
|
}
|
|
|
|
|
|
|
|
logFormatter := new(log.TextFormatter)
|
|
|
|
logFormatter.TimestampFormat = time.RFC3339 // or RFC3339
|
|
|
|
logFormatter.FullTimestamp = true
|
2022-03-10 14:14:00 +01:00
|
|
|
logFormatter.CallerPrettyfier = func(frame *runtime.Frame) (function string, file string) {
|
|
|
|
fileName := path.Base(frame.File) + ":" + strconv.Itoa(frame.Line)
|
|
|
|
//return frame.Function, fileName
|
|
|
|
return "", fileName
|
|
|
|
}
|
|
|
|
|
2022-11-08 10:56:13 +01:00
|
|
|
if level > log.WarnLevel {
|
2022-03-10 14:14:00 +01:00
|
|
|
log.SetReportCaller(true)
|
|
|
|
}
|
2021-09-07 09:53:18 +02:00
|
|
|
|
|
|
|
log.SetFormatter(logFormatter)
|
|
|
|
log.SetLevel(level)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|