完善 otel 配置

This commit is contained in:
2026-05-08 13:53:47 +08:00
parent a0b0be2b8e
commit 042c8d1a51
7 changed files with 108 additions and 66 deletions

View File

@@ -3,6 +3,7 @@ package globals
import (
"context"
"fmt"
"log/slog"
"platform/pkg/env"
"go.opentelemetry.io/otel"
@@ -17,11 +18,17 @@ import (
var tp *trace.TracerProvider
func initOtel(ctx context.Context) error {
addr := env.OtelHost + ":" + env.OtelPort
name := "lanhu-platform"
if env.OtelNameSuffix != "" {
name += "-" + env.OtelNameSuffix
}
slog.Info("初始化 otel", "endpoint", addr, "service_suffix", name)
if env.OtelHost == "" || env.OtelPort == "" {
return nil
}
addr := env.OtelHost + ":" + env.OtelPort
exporter, err := otlptracegrpc.New(ctx,
otlptracegrpc.WithEndpoint(addr),
otlptracegrpc.WithInsecure(),
@@ -36,7 +43,7 @@ func initOtel(ctx context.Context) error {
trace.WithResource(
resource.NewWithAttributes(
semconv.SchemaURL,
semconv.ServiceNameKey.String("lanhu-platform"),
semconv.ServiceNameKey.String(name),
),
),
)

View File

@@ -89,6 +89,7 @@ func RunTask(ctx context.Context) error {
ErrorHandler: asynq.ErrorHandlerFunc(func(ctx context.Context, task *asynq.Task, err error) {
slog.Error("任务执行失败", "task", task.Type(), "error", err)
}),
Logger: &AppAsynqLogger{},
})
var mux = asynq.NewServeMux()
@@ -114,6 +115,7 @@ func RunTask(ctx context.Context) error {
func RunCron(ctx context.Context) error {
server := asynq.NewSchedulerFromRedisClient(deps.Redis, &asynq.SchedulerOpts{
Location: time.Local,
Logger: &AppAsynqLogger{},
})
// 每小时清理一次一小时之前的过期通道
@@ -133,3 +135,33 @@ func RunCron(ctx context.Context) error {
return nil
}
type AppAsynqLogger struct{}
func (l *AppAsynqLogger) Debug(args ...any) {
slog.Debug("Asynq", anyToAttrs(args)...)
}
func (l *AppAsynqLogger) Info(args ...any) {
slog.Info("Asynq", anyToAttrs(args)...)
}
func (l *AppAsynqLogger) Warn(args ...any) {
slog.Warn("Asynq", anyToAttrs(args)...)
}
func (l *AppAsynqLogger) Error(args ...any) {
slog.Error("Asynq", anyToAttrs(args)...)
}
func (l *AppAsynqLogger) Fatal(args ...any) {
slog.Error("Asynq[Fatal]", anyToAttrs(args)...)
}
func anyToAttrs(args ...any) []any {
attrs := make([]any, len(args))
for i, arg := range args {
attrs[i] = slog.Any(fmt.Sprintf("arg%d", i), arg)
}
return attrs
}