You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
81 lines
2.0 KiB
81 lines
2.0 KiB
package core |
|
|
|
import ( |
|
"api/config" |
|
"fmt" |
|
"github.com/AllCute/loki-client-go/loki" |
|
"github.com/go-kit/kit/log" |
|
"github.com/prometheus/common/model" |
|
"time" |
|
) |
|
|
|
type lokiClient struct { |
|
client *loki.Client |
|
} |
|
|
|
// 初始化Loki |
|
func initLokiClient() lokiClient { |
|
config.InitLokiConfig() |
|
// 初始化配置 |
|
cfg, err := loki.NewDefaultConfig(config.LokiConfig.GetPushURL()) |
|
// 创建连接对象 |
|
client, err := loki.NewWithLogger(cfg, log.NewNopLogger()) |
|
if err != nil { |
|
Log.zap.Panicf("Loki初始化失败: %v", err.Error()) |
|
} |
|
label := model.LabelSet{"job": "initialization"} |
|
label["source"] = model.LabelValue(config.LokiConfig.Source) |
|
label["level"] = "Debug" |
|
err = client.Handle(label, time.Now().Local(), "Loki服务连接成功") |
|
if err != nil { |
|
Log.zap.Errorf("日志推送到Loki失败: %v", err.Error()) |
|
} |
|
return lokiClient{client: client} |
|
} |
|
|
|
// 发送日志到Loki |
|
func (c lokiClient) send(level string, job string, logStr string) { |
|
label := model.LabelSet{"job": model.LabelValue(job)} |
|
label["source"] = model.LabelValue(config.LokiConfig.Source) |
|
label["level"] = model.LabelValue(level) |
|
err := c.client.Handle(label, time.Now().Local(), logStr) |
|
if err != nil { |
|
Log.zap.Errorf("日志推送到Loki失败: %v", err.Error()) |
|
} |
|
} |
|
|
|
// Debug Debug日志 |
|
func (c lokiClient) Debug(job, template string, args ...interface{}) { |
|
logStr := template |
|
if len(args) > 0 { |
|
logStr = fmt.Sprintf(template, args...) |
|
} |
|
c.send("Debug", job, logStr) |
|
} |
|
|
|
// Info Info日志 |
|
func (c lokiClient) Info(job, template string, args ...interface{}) { |
|
logStr := template |
|
if len(args) > 0 { |
|
logStr = fmt.Sprintf(template, args...) |
|
} |
|
c.send("Info", job, logStr) |
|
} |
|
|
|
// Warn Warn日志 |
|
func (c lokiClient) Warn(job, template string, args ...interface{}) { |
|
logStr := template |
|
if len(args) > 0 { |
|
logStr = fmt.Sprintf(template, args...) |
|
} |
|
c.send("Warn", job, logStr) |
|
} |
|
|
|
// Error Error日志 |
|
func (c lokiClient) Error(job, template string, args ...interface{}) { |
|
logStr := template |
|
if len(args) > 0 { |
|
logStr = fmt.Sprintf(template, args...) |
|
} |
|
c.send("Error", job, logStr) |
|
}
|
|
|