1 Star 0 Fork 0

江苏岚江智能科技有限公司/ljmicro

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
loki.go 1.46 KB
一键复制 编辑 原始数据 按行查看 历史
吴文凯 提交于 2023-03-13 16:50 +08:00 . update
package loger
import (
"errors"
"fmt"
"gitee.com/jiangsu-lanjiang-intelligent/ljmicro/pkg/conf"
"github.com/grafana/loki-client-go/loki"
"github.com/grafana/loki-client-go/pkg/labelutil"
"github.com/prometheus/common/model"
"github.com/sirupsen/logrus"
"strings"
"time"
)
type LokiWriter struct {
*loki.Client
}
func (rcv *LokiWriter) Fire(entry *logrus.Entry) error {
if entry == nil {
return fmt.Errorf("log entry is nil")
}
ls := model.LabelSet{
"level": model.LabelValue(entry.Level.String()),
}
for k, v := range entry.Data {
ls[model.LabelName(k)] = model.LabelValue(fmt.Sprintf("%v", v))
}
return rcv.Handle(ls, time.Now(), entry.Message)
}
func (rcv *LokiWriter) Levels() []logrus.Level {
return logrus.AllLevels
}
func InitializeLoki() error {
lokiAddr := conf.GetString("loki.addr")
if lokiAddr == "" {
fmt.Println("loki addr is empty skip initialize log.loki")
return nil
}
if !(strings.HasPrefix(lokiAddr, "http://") ||
strings.HasPrefix(lokiAddr, "https://")) {
lokiAddr = "http://" + lokiAddr
}
lokiConf, err := loki.NewDefaultConfig(lokiAddr + "/loki/api/v1/push")
if err != nil {
return errors.New("new log.loki config error: " + err.Error())
}
lokiConf.ExternalLabels = labelutil.LabelSet{LabelSet: model.LabelSet{}}
c, err := loki.New(lokiConf)
if err != nil {
return errors.New("initialize log.loki error: " + err.Error())
}
logrus.AddHook(&LokiWriter{c})
fmt.Println("initialize log.loki success")
return nil
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/jiangsu-lanjiang-intelligent/ljmicro.git
git@gitee.com:jiangsu-lanjiang-intelligent/ljmicro.git
jiangsu-lanjiang-intelligent
ljmicro
ljmicro
9f39f3984435

搜索帮助