You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
106 lines
2.3 KiB
Go
106 lines
2.3 KiB
Go
package logruscomponent
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"runtime"
|
|
"strings"
|
|
|
|
microLogrus "github.com/go-micro/plugins/v4/logger/logrus"
|
|
microLogger "go-micro.dev/v4/logger"
|
|
"jochum.dev/jo-micro/components"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
"github.com/urfave/cli/v2"
|
|
)
|
|
|
|
// caller returns string presentation of log caller which is formatted as
|
|
// `/path/to/file.go:line_number`. e.g. `/internal/app/api.go:25`
|
|
func caller() func(*runtime.Frame) (function string, file string) {
|
|
return func(f *runtime.Frame) (function string, file string) {
|
|
return "", fmt.Sprintf("%s:%d", f.File, f.Line)
|
|
}
|
|
}
|
|
|
|
const Name = "logrus"
|
|
|
|
type LogrusComponent struct {
|
|
initialized bool
|
|
logger *logrus.Logger
|
|
}
|
|
|
|
func New() *LogrusComponent {
|
|
return &LogrusComponent{initialized: false}
|
|
}
|
|
|
|
func MustReg(cReg *components.Registry) *LogrusComponent {
|
|
return cReg.Must(Name).(*LogrusComponent)
|
|
}
|
|
|
|
func (c *LogrusComponent) Name() string {
|
|
return Name
|
|
}
|
|
|
|
func (c *LogrusComponent) Priority() int {
|
|
return 0
|
|
}
|
|
|
|
func (c *LogrusComponent) Initialized() bool {
|
|
return c.initialized
|
|
}
|
|
|
|
func (c *LogrusComponent) Init(components *components.Registry, cli *cli.Context) error {
|
|
if c.initialized {
|
|
return nil
|
|
}
|
|
|
|
lvl, err := logrus.ParseLevel(cli.String(fmt.Sprintf("%s_log_level", strings.ToLower(components.FlagPrefix()))))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
c.logger = logrus.New()
|
|
c.logger.Out = os.Stdout
|
|
c.logger.Level = lvl
|
|
|
|
c.logger.SetReportCaller(true)
|
|
|
|
c.logger.SetFormatter(&logrus.JSONFormatter{
|
|
CallerPrettyfier: caller(),
|
|
FieldMap: logrus.FieldMap{
|
|
logrus.FieldKeyFile: "caller",
|
|
},
|
|
})
|
|
|
|
microLogger.DefaultLogger = microLogrus.NewLogger(microLogrus.WithLogger(c.logger))
|
|
|
|
c.initialized = true
|
|
return nil
|
|
}
|
|
|
|
func (c *LogrusComponent) Stop() error {
|
|
c.initialized = false
|
|
c.logger = nil
|
|
return nil
|
|
}
|
|
|
|
func (c *LogrusComponent) Flags(r *components.Registry) []cli.Flag {
|
|
return []cli.Flag{
|
|
&cli.StringFlag{
|
|
Name: fmt.Sprintf("%s_log_level", strings.ToLower(r.FlagPrefix())),
|
|
Value: "info",
|
|
Usage: "Logrus log level default 'info', {panic,fatal,error,warn,info,debug,trace} available",
|
|
EnvVars: []string{fmt.Sprintf("%s_LOG_LEVEL", strings.ToUpper(r.FlagPrefix()))},
|
|
},
|
|
}
|
|
}
|
|
|
|
func (c *LogrusComponent) Health(context context.Context) error {
|
|
return nil
|
|
}
|
|
|
|
func (c *LogrusComponent) Logger() *logrus.Logger {
|
|
return c.logger
|
|
}
|