2019-04-25 04:52:08 +07:00
|
|
|
package logging
|
|
|
|
|
|
|
|
import (
|
2020-03-10 02:57:53 +07:00
|
|
|
"os"
|
|
|
|
|
2019-11-17 02:50:58 +07:00
|
|
|
logrus_stack "github.com/Gurpartap/logrus-stack"
|
2019-04-25 04:52:08 +07:00
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
)
|
|
|
|
|
2020-01-21 07:10:00 +07:00
|
|
|
// Logger return the standard logrus logger.
|
2019-04-25 04:52:08 +07:00
|
|
|
func Logger() *logrus.Logger {
|
|
|
|
return logrus.StandardLogger()
|
|
|
|
}
|
|
|
|
|
|
|
|
// SetLevel set the level of the logger.
|
|
|
|
func SetLevel(level logrus.Level) {
|
|
|
|
logrus.SetLevel(level)
|
|
|
|
}
|
2020-03-10 02:57:53 +07:00
|
|
|
|
2020-05-02 12:06:39 +07:00
|
|
|
// InitializeLogger initialize logger.
|
2020-11-25 06:46:41 +07:00
|
|
|
func InitializeLogger(format, filename string) error {
|
2020-03-10 02:57:53 +07:00
|
|
|
callerLevels := []logrus.Level{}
|
|
|
|
stackLevels := []logrus.Level{logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel}
|
|
|
|
logrus.AddHook(logrus_stack.NewHook(callerLevels, stackLevels))
|
|
|
|
|
2021-01-15 18:16:41 +07:00
|
|
|
if format == logFormatJSON {
|
2020-11-25 06:46:41 +07:00
|
|
|
logrus.SetFormatter(&logrus.JSONFormatter{})
|
|
|
|
} else {
|
|
|
|
logrus.SetFormatter(&logrus.TextFormatter{})
|
|
|
|
}
|
|
|
|
|
2020-03-10 02:57:53 +07:00
|
|
|
if filename != "" {
|
2020-11-13 06:14:45 +07:00
|
|
|
f, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
|
|
|
|
|
2020-03-10 02:57:53 +07:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-05-06 02:35:32 +07:00
|
|
|
|
2021-01-15 18:16:41 +07:00
|
|
|
if format != logFormatJSON {
|
|
|
|
logrus.SetFormatter(&logrus.TextFormatter{
|
|
|
|
DisableColors: true,
|
|
|
|
FullTimestamp: true,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-03-10 02:57:53 +07:00
|
|
|
logrus.SetOutput(f)
|
|
|
|
}
|
2020-05-06 02:35:32 +07:00
|
|
|
|
2020-03-10 02:57:53 +07:00
|
|
|
return nil
|
|
|
|
}
|