Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package logger
import (
"path"
"runtime"
"github.com/Abramovic/logrus_influxdb"
client "github.com/influxdata/influxdb/client/v2"
"github.com/sirupsen/logrus"
)
var log *logrus.Logger
func Init(addr string, jsonFormat bool) {
log = logrus.New()
log.AddHook(ContextHook{})
if jsonFormat {
log.Formatter = &logrus.JSONFormatter{}
} else {
log.Formatter = &logrus.TextFormatter{}
return
}
influxConfig := &logrus_influxdb.Config{
Tags: []string{"myAppName", "main"}, // use the following tags
}
// Connect to InfluxDB using the standard client.
influxClient, _ := client.NewHTTPClient(client.HTTPConfig{
Addr: addr,
})
hook, err := logrus_influxdb.NewInfluxDB(influxConfig, influxClient)
if err == nil {
log.AddHook(hook)
}
}
func Log() *logrus.Logger {
return log
}
func Info(infoData ...interface{}) {
log.Info(infoData...)
}
func Debug(debugData interface{}) {
log.Debug(debugData)
}
func Error(err ...interface{}) {
if err == nil || err[0] == nil {
return
}
log.Error(err...)
}
func Warn(warnData ...interface{}) {
log.Warn(warnData...)
}
func Fatal(format string, args ...interface{}) {
log.Fatalf(format, args...)
}
func Printf(format string, args ...interface{}) {
log.Printf(format, args...)
}
func Println(args ...interface{}) {
log.Println(args...)
}
type ContextHook struct{}
func (hook ContextHook) Levels() []logrus.Level {
return logrus.AllLevels
}
func (hook ContextHook) Fire(entry *logrus.Entry) error {
if pc, file, line, ok := runtime.Caller(8); ok {
funcName := runtime.FuncForPC(pc).Name()
entry.Data["file"] = path.Base(file)
entry.Data["func"] = path.Base(funcName)
entry.Data["line"] = line
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.