webhook

package
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 16, 2025 License: MIT Imports: 9 Imported by: 0

README

slog: Webhook 处理器

tag Go Version GoDoc Build Status Go report Coverage Contributors License

slog 库提供通用格式化器 + 构建自定义格式化器的助手。

🚀 安装

go get github.com/samber/slog-webhook/v2

兼容性: go >= 1.23

在 v3.0.0 之前,不会对导出的 API 进行破坏性更改。

💡 使用方法

GoDoc: https://pkg.go.dev/github.com/samber/slog-webhook/v2

处理器选项
type Option struct {
  // 日志级别 (默认: debug)
  Level     slog.Leveler

  // URL
  Endpoint string
  Timeout  time.Duration // 默认: 10s

  // 可选: 自定义 webhook 事件构建器
  Converter Converter
  // 可选: 自定义序列化器
  Marshaler func(v any) ([]byte, error)
  // 可选: 从上下文获取属性
  AttrFromContext []func(ctx context.Context) []slog.Attr

  // 可选: 参见 slog.HandlerOptions
  AddSource   bool
  ReplaceAttr func(groups []string, a slog.Attr) slog.Attr
}

其他全局参数:

slogwebhook.SourceKey = "source"
slogwebhook.ContextKey = "extra"
slogwebhook.ErrorKeys = []string{"error", "err"}
slogwebhook.RequestIgnoreHeaders = false
支持的属性

slogwebhook.DefaultConverter 解释以下属性:

属性名称 slog.Kind 底层类型
"user" group (见下文)
"error" any error
"request" any *http.Request
其他属性 *

其他属性将被注入到 extra 字段中。

用户必须是 slog.Group 类型。例如:

slog.Group("user",
  slog.String("id", "user-123"),
  slog.String("username", "samber"),
  slog.Time("created_at", time.Now()),
)
示例
import (
	"fmt"
	"net/http"
	"time"

	slogwebhook "github.com/samber/slog-webhook/v2"

	"log/slog"
)

func main() {
  url := "https://webhook.site/xxxxxx"

  logger := slog.New(slogwebhook.Option{Level: slog.LevelDebug, Endpoint: url}.NewWebhookHandler())
  logger = logger.With("release", "v1.0.0")

  req, _ := http.NewRequest(http.MethodGet, "https://api.screeb.app", nil)
  req.Header.Set("Content-Type", "application/json")
  req.Header.Set("X-TOKEN", "1234567890")

  logger.
    With(
      slog.Group("user",
        slog.String("id", "user-123"),
        slog.Time("created_at", time.Now()),
      ),
    ).
    With("request", req).
    With("error", fmt.Errorf("an error")).
    Error("a message")
}

输出:

{
  "error": {
    "error": "an error",
    "kind": "*errors.errorString",
    "stack": null
  },
  "extra": {
	"release": "v1.0.0"
  },
  "level": "ERROR",
  "logger": "samber/slog-webhook",
  "message": "a message",
  "request": {
    "headers": {
      "Content-Type": "application/json",
      "X-Token": "1234567890"
    },
    "host": "api.screeb.app",
    "method": "GET",
    "url": {
      "fragment": "",
      "host": "api.screeb.app",
      "path": "",
      "query": {},
      "raw_query": "",
      "scheme": "https",
      "url": "https://api.screeb.app"
    }
  },
  "timestamp": "2023-04-10T14:00:0.000000",
  "user": {
	"id": "user-123",
    "created_at": "2023-04-10T14:00:0.000000"
  }
}
链路追踪

导入 samber/slog-otel 库。

import (
	slogwebhook "github.com/samber/slog-webhook"
	slogotel "github.com/samber/slog-otel"
	"go.opentelemetry.io/otel/sdk/trace"
)

func main() {
	tp := trace.NewTracerProvider(
		trace.WithSampler(trace.AlwaysSample()),
	)
	tracer := tp.Tracer("hello/world")

	ctx, span := tracer.Start(context.Background(), "foo")
	defer span.End()

	span.AddEvent("bar")

	logger := slog.New(
		slogwebhook.Option{
			// ...
			AttrFromContext: []func(ctx context.Context) []slog.Attr{
				slogotel.ExtractOtelAttrFromContext([]string{"tracing"}, "trace_id", "span_id"),
			},
		}.NewWebhookHandler(),
	)

	logger.ErrorContext(ctx, "a message")
}

🤝 贡献

不要犹豫 ;)

# 安装一些开发依赖
make tools

# 运行测试
make test
# 或
make watch-test

👤 贡献者

贡献者

💫 表达你的支持

如果这个项目对你有帮助,请给一个 ⭐️!

GitHub Sponsors

📝 许可证

版权所有 © 2023 Samuel Berthe

本项目采用 MIT 许可证。

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	SourceKey            = "source"
	ContextKey           = "extra"
	ErrorKeys            = []string{"error", "err"}
	RequestKey           = "request"
	RequestIgnoreHeaders = false
)

Functions

func DefaultConverter

func DefaultConverter(addSource bool, replaceAttr func(groups []string, a slog.Attr) slog.Attr, loggerAttr []slog.Attr, groups []string, record *slog.Record) map[string]any

Types

type Converter

type Converter func(addSource bool, replaceAttr func(groups []string, a slog.Attr) slog.Attr, loggerAttr []slog.Attr, groups []string, record *slog.Record) map[string]any

type Option

type Option struct {
	// log level (default: debug)
	Level slog.Leveler

	// URL
	Endpoint string
	Timeout  time.Duration // default: 10s

	// optional: customize webhook event builder
	Converter Converter
	// optional: custom marshaler
	Marshaler func(v any) ([]byte, error)
	// optional: fetch attributes from context
	AttrFromContext []func(ctx context.Context) []slog.Attr

	// optional: see slog.HandlerOptions
	AddSource   bool
	ReplaceAttr func(groups []string, a slog.Attr) slog.Attr
}

func (Option) NewWebhookHandler

func (o Option) NewWebhookHandler() slog.Handler

type WebhookAdapter

type WebhookAdapter struct {
	*modules.BaseModule
	// contains filtered or unexported fields
}

WebhookAdapter Webhook模块适配器

func NewWebhookAdapter

func NewWebhookAdapter() *WebhookAdapter

NewWebhookAdapter 创建Webhook适配器

func (*WebhookAdapter) Configure

func (w *WebhookAdapter) Configure(config modules.Config) error

Configure 配置Webhook模块

type WebhookHandler

type WebhookHandler struct {
	// contains filtered or unexported fields
}

func (*WebhookHandler) Enabled

func (h *WebhookHandler) Enabled(_ context.Context, level slog.Level) bool

func (*WebhookHandler) Handle

func (h *WebhookHandler) Handle(ctx context.Context, record slog.Record) error

func (*WebhookHandler) WithAttrs

func (h *WebhookHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*WebhookHandler) WithGroup

func (h *WebhookHandler) WithGroup(name string) slog.Handler

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL