modules

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: 12 Imported by: 0

README

slog 模块注册系统

slog 模块注册系统为日志库提供了强大的插件化架构,让开发者可以轻松地扩展和定制日志功能。

🚀 快速开始

使用现有模块
import "github.com/darkit/slog/modules"

// 快速启用单个模块
logger := slog.UseFactory("formatter", modules.Config{
    "type":   "time",
    "format": "2006-01-02 15:04:05",
}).Build()

// 链式使用多个模块
logger = slog.UseFactory("formatter", modules.Config{
    "type": "time",
}).UseFactory("webhook", modules.Config{
    "endpoint": "https://api.example.com/webhook",
    "timeout":  "30s",
}).Build()
配置驱动方式
configs := []modules.ModuleConfig{
    {
        Type:     "formatter",
        Name:     "time-fmt",
        Enabled:  true,
        Priority: 10,
        Config:   modules.Config{"type": "time"},
    },
    {
        Type:     "webhook", 
        Name:     "alert-hook",
        Enabled:  true,
        Priority: 100,
        Config:   modules.Config{
            "endpoint": "https://alerts.example.com",
            "level":    "error",
        },
    },
}

logger := slog.UseConfig(configs).Build()

📦 模块架构

模块类型
类型 说明 优先级 用途
Formatter 格式化器 1-50 对日志内容进行格式化处理
Middleware 中间件 51-100 日志处理的中间层逻辑
Handler 处理器 101-150 自定义日志处理逻辑
Sink 接收器 151-200 日志的最终输出目标
核心接口
// Module 模块接口
type Module interface {
    Name() string                     // 模块名称
    Type() ModuleType                 // 模块类型
    Configure(config Config) error   // 配置模块
    Handler() slog.Handler           // 获取处理器
    Priority() int                   // 执行优先级
    Enabled() bool                   // 是否启用
}

// ModuleFactory 模块工厂函数
type ModuleFactory func(config Config) (Module, error)

🛠 创建自定义模块

步骤1:定义模块结构
package email

import (
    "log/slog"
    "github.com/darkit/slog/modules"
)

// EmailModule 邮件通知模块
type EmailModule struct {
    *modules.BaseModule
    smtpHost     string
    smtpPort     int
    username     string
    password     string
    recipients   []string
    minLevel     slog.Level
}

func NewEmailModule() *EmailModule {
    return &EmailModule{
        BaseModule: modules.NewBaseModule("email", modules.TypeSink, 150),
        minLevel:   slog.LevelWarn, // 默认只发送警告及以上级别
    }
}
步骤2:实现配置方法
func (e *EmailModule) Configure(config modules.Config) error {
    if err := e.BaseModule.Configure(config); err != nil {
        return err
    }

    // 解析配置
    if host, ok := config["smtp_host"].(string); ok {
        e.smtpHost = host
    }
    
    if port, ok := config["smtp_port"].(int); ok {
        e.smtpPort = port
    }
    
    if username, ok := config["username"].(string); ok {
        e.username = username
    }
    
    if password, ok := config["password"].(string); ok {
        e.password = password
    }
    
    if recipients, ok := config["recipients"].([]string); ok {
        e.recipients = recipients
    }
    
    if level, ok := config["min_level"].(string); ok {
        switch level {
        case "debug":
            e.minLevel = slog.LevelDebug
        case "info":
            e.minLevel = slog.LevelInfo
        case "warn":
            e.minLevel = slog.LevelWarn
        case "error":
            e.minLevel = slog.LevelError
        }
    }

    // 创建处理器
    e.SetHandler(e.createEmailHandler())
    return nil
}
步骤3:实现处理器逻辑
func (e *EmailModule) createEmailHandler() slog.Handler {
    return &EmailHandler{
        module: e,
    }
}

type EmailHandler struct {
    module *EmailModule
}

func (h *EmailHandler) Enabled(ctx context.Context, level slog.Level) bool {
    return h.module.Enabled() && level >= h.module.minLevel
}

func (h *EmailHandler) Handle(ctx context.Context, record slog.Record) error {
    if !h.Enabled(ctx, record.Level) {
        return nil
    }
    
    // 构建邮件内容
    subject := fmt.Sprintf("[%s] %s", record.Level, record.Message)
    body := h.formatLogRecord(record)
    
    // 发送邮件
    return h.sendEmail(subject, body)
}

func (h *EmailHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
    // 处理属性
    return h
}

func (h *EmailHandler) WithGroup(name string) slog.Handler {
    // 处理分组
    return h
}

func (h *EmailHandler) sendEmail(subject, body string) error {
    // 实现邮件发送逻辑
    // 使用 net/smtp 或第三方邮件库
    return nil
}

func (h *EmailHandler) formatLogRecord(record slog.Record) string {
    // 格式化日志记录为邮件正文
    return fmt.Sprintf("时间: %s\n级别: %s\n消息: %s\n", 
        record.Time.Format("2006-01-02 15:04:05"),
        record.Level,
        record.Message)
}
步骤4:注册模块工厂
// init 函数中注册模块工厂
func init() {
    modules.RegisterFactory("email", func(config modules.Config) (modules.Module, error) {
        module := NewEmailModule()
        return module, module.Configure(config)
    })
}
步骤5:使用自定义模块
// 使用自定义邮件模块
logger := slog.UseFactory("email", modules.Config{
    "smtp_host": "smtp.gmail.com",
    "smtp_port": 587,
    "username":  "[email protected]", 
    "password":  "your-app-password",
    "recipients": []string{"[email protected]", "[email protected]"},
    "min_level": "error",
}).Build()

logger.Error("系统发生严重错误", "component", "database", "error", "connection timeout")

📚 现有模块参考

Formatter 模块

位置:modules/formatter/

支持的格式化器类型:

  • time - 时间格式化
  • error - 错误信息脱敏
  • pii - 个人身份信息脱敏
  • http - HTTP请求/响应格式化

使用示例:

slog.UseFactory("formatter", modules.Config{
    "type":   "time",
    "format": "2006-01-02 15:04:05",
})
Webhook 模块

位置:modules/webhook/

将日志发送到HTTP端点,支持:

  • 自定义端点URL
  • 超时控制
  • 级别过滤
  • 重试机制

使用示例:

slog.UseFactory("webhook", modules.Config{
    "endpoint": "https://api.slack.com/webhooks/...",
    "timeout":  "30s",
    "level":    "warn",
})
Syslog 模块

位置:modules/syslog/

发送日志到系统日志服务,支持:

  • TCP/UDP协议
  • 远程syslog服务器
  • 标准syslog格式

使用示例:

slog.UseFactory("syslog", modules.Config{
    "network": "udp",
    "addr":    "localhost:514",
    "level":   "info",
})
Multi 模块

位置:modules/multi/

Multi模块提供了强大的日志分发、路由、故障转移和负载均衡功能,是构建高可用、高性能日志系统的核心组件。

核心功能
功能 说明 使用场景
Fanout 扇出分发 同时发送到多个目标(如文件+网络)
Router 条件路由 基于日志内容智能路由(如按区域分发)
Failover 故障转移 高可用性,主备切换
Pool 负载均衡 高性能,分散负载
Pipe 中间件链 链式处理,数据转换
TCP 自动重连 网络日志传输
Recover 错误恢复 异常处理和容错
1. Fanout(扇出分发)

并行将日志发送到多个处理器,适用于需要同时输出到多个目标的场景。

// 同时输出到文件、控制台和远程服务器
logger := slog.UseFactory("multi", modules.Config{
    "type": "fanout",
    "handlers": []modules.Config{
        {
            "type": "file",
            "config": modules.Config{
                "path": "/var/log/app.log",
                "format": "json",
            },
        },
        {
            "type": "console", 
            "config": modules.Config{
                "format": "text",
                "color": true,
            },
        },
        {
            "type": "tcp",
            "config": modules.Config{
                "endpoint": "logstash.company.com:5044",
                "format": "json",
            },
        },
    },
}).Build()

logger.Info("用户登录", "user_id", "12345", "ip", "192.168.1.100")
// 这条日志会同时写入:文件、控制台显示、发送到logstash
2. Router(智能路由)

基于日志内容的条件路由,将不同类型的日志发送到不同的目标。

// 按服务和级别路由日志
logger := slog.UseFactory("multi", modules.Config{
    "type": "router",
    "routes": []modules.Config{
        {
            "name": "error-alerts",
            "condition": modules.Config{
                "level": "error",
                "service": "payment",
            },
            "handler": modules.Config{
                "type": "webhook",
                "endpoint": "https://alerts.company.com/payment",
            },
        },
        {
            "name": "user-events", 
            "condition": modules.Config{
                "component": "auth",
            },
            "handler": modules.Config{
                "type": "file",
                "path": "/var/log/auth.log",
            },
        },
        {
            "name": "performance-metrics",
            "condition": modules.Config{
                "type": "metric",
            },
            "handler": modules.Config{
                "type": "tcp",
                "endpoint": "metrics.company.com:8086",
            },
        },
    },
}).Build()

// 这些日志会被路由到不同目标
logger.Error("支付失败", "service", "payment", "error", "timeout")  // -> 发送告警
logger.Info("用户登录", "component", "auth", "user", "alice")        // -> auth.log
logger.Info("响应耗时", "type", "metric", "duration", "120ms")       // -> 指标收集器
3. Failover(故障转移)

提供高可用性,当主要日志目标不可用时自动切换到备用目标。

// 多级故障转移:主数据中心 -> 备数据中心 -> 本地文件
logger := slog.UseFactory("multi", modules.Config{
    "type": "failover",
    "handlers": []modules.Config{
        {
            "name": "primary",
            "type": "tcp", 
            "config": modules.Config{
                "endpoint": "logs-primary.company.com:5044",
                "timeout": "5s",
            },
        },
        {
            "name": "secondary",
            "type": "tcp",
            "config": modules.Config{
                "endpoint": "logs-backup.company.com:5044", 
                "timeout": "10s",
            },
        },
        {
            "name": "local",
            "type": "file",
            "config": modules.Config{
                "path": "/var/log/failover.log",
                "max_size": "100MB",
            },
        },
    },
}).Build()

logger.Error("数据库连接失败")
// 首先尝试发送到主服务器,失败后尝试备用服务器,都失败则写入本地文件
4. Pool(负载均衡)

通过处理器池分散负载,提高日志处理性能和吞吐量。

// 负载均衡到多个Elasticsearch节点
logger := slog.UseFactory("multi", modules.Config{
    "type": "pool",
    "strategy": "round_robin", // 或 "random", "hash"
    "handlers": []modules.Config{
        {
            "type": "elasticsearch",
            "config": modules.Config{
                "endpoint": "http://es-node1.company.com:9200",
                "index": "logs-2024",
            },
        },
        {
            "type": "elasticsearch", 
            "config": modules.Config{
                "endpoint": "http://es-node2.company.com:9200",
                "index": "logs-2024",
            },
        },
        {
            "type": "elasticsearch",
            "config": modules.Config{
                "endpoint": "http://es-node3.company.com:9200", 
                "index": "logs-2024",
            },
        },
    },
}).Build()

// 高并发场景下日志会被均匀分发到三个ES节点
for i := 0; i < 10000; i++ {
    logger.Info("订单处理", "order_id", i, "status", "completed")
}
5. Pipe(中间件管道)

链式处理日志,支持数据转换、过滤、增强等操作。

// 中间件链:DLP脱敏 -> 添加追踪ID -> 格式转换 -> 发送
logger := slog.UseFactory("multi", modules.Config{
    "type": "pipe",
    "middlewares": []modules.Config{
        {
            "type": "dlp",
            "config": modules.Config{
                "enabled": true,
                "phone": true,
                "email": true,
                "card": true,
            },
        },
        {
            "type": "tracer",
            "config": modules.Config{
                "add_trace_id": true,
                "add_span_id": true,
            },
        },
        {
            "type": "formatter",
            "config": modules.Config{
                "output_format": "json",
                "timestamp_format": "rfc3339",
            },
        },
    ],
    "final_handler": modules.Config{
        "type": "tcp",
        "endpoint": "logs.company.com:5044",
    },
}).Build()

logger.Info("用户注册", "phone", "13812345678", "email", "[email protected]")
// 输出: {"time":"2024-01-01T12:00:00Z","level":"INFO","msg":"用户注册","phone":"138****5678","email":"u***@***.com","trace_id":"abc123","span_id":"def456"}
6. TCP自动重连

提供自动重连的TCP客户端,适用于网络日志传输。

// 自动重连的TCP日志传输
logger := slog.UseFactory("multi", modules.Config{
    "type": "tcp",
    "endpoint": "logstash.company.com:5044",
    "auto_reconnect": true,
    "max_retries": 10,
    "retry_interval": "1s",
    "connection_timeout": "30s",
    "write_timeout": "10s",
}).Build()

// 网络中断时会自动重试连接
logger.Error("网络异常", "component", "database", "error", "connection lost")
7. Recover(错误恢复)

处理日志处理过程中的panic和错误,提供容错能力。

// 带错误恢复的日志处理
logger := slog.UseFactory("multi", modules.Config{
    "type": "recover",
    "recovery_handler": modules.Config{
        "type": "file",
        "path": "/var/log/errors.log",
    },
    "main_handler": modules.Config{
        "type": "custom", // 可能有bug的自定义处理器
    },
    "on_error": modules.Config{
        "continue": true,        // 出错后继续处理
        "log_error": true,      // 记录错误信息
        "fallback_enabled": true, // 启用备选处理器
    },
}).Build()

logger.Info("这可能触发处理器错误")
// 即使处理器出现panic,也会被捕获并记录到错误日志中,不会导致程序崩溃
复合使用示例

将多种功能组合使用,构建企业级日志系统:

// 企业级日志系统:路由 + 故障转移 + 负载均衡 + 恢复
configs := []modules.ModuleConfig{
    {
        Type:     "multi",
        Name:     "enterprise-logging",
        Enabled:  true,
        Priority: 100,
        Config:   modules.Config{
            "type": "router",
            "routes": []modules.Config{
                {
                    "name": "critical-alerts",
                    "condition": modules.Config{"level": "error"},
                    "handler": modules.Config{
                        "type": "failover",
                        "handlers": []modules.Config{
                            {"type": "webhook", "endpoint": "https://alerts.company.com"},
                            {"type": "file", "path": "/var/log/critical.log"},
                        },
                    },
                },
                {
                    "name": "business-logs",
                    "condition": modules.Config{"service": "api"},
                    "handler": modules.Config{
                        "type": "pool", 
                        "handlers": []modules.Config{
                            {"type": "elasticsearch", "endpoint": "http://es1:9200"},
                            {"type": "elasticsearch", "endpoint": "http://es2:9200"},
                            {"type": "elasticsearch", "endpoint": "http://es3:9200"},
                        },
                    },
                },
                {
                    "name": "default",
                    "handler": modules.Config{
                        "type": "fanout",
                        "handlers": []modules.Config{
                            {"type": "file", "path": "/var/log/app.log"},
                            {"type": "tcp", "endpoint": "logs.company.com:5044"},
                        },
                    },
                },
            },
        },
    },
}

logger := slog.UseConfig(configs).Build()

// 不同类型的日志会被智能路由到相应的处理器
logger.Error("支付异常", "service", "payment")      // -> 告警系统 + 本地文件
logger.Info("API请求", "service", "api")          // -> ES集群(负载均衡)
logger.Debug("调试信息")                         // -> 文件 + TCP(扇出)
性能优化配置
// 高性能配置
logger := slog.UseFactory("multi", modules.Config{
    "type": "fanout",
    "async": true,              // 异步处理
    "buffer_size": 10000,       // 缓冲区大小
    "flush_interval": "1s",     // 刷新间隔
    "worker_count": 4,          // 工作协程数
    "handlers": []modules.Config{
        {
            "type": "pool",
            "batch_size": 100,      // 批处理大小
            "handlers": []modules.Config{
                {"type": "elasticsearch", "endpoint": "http://es1:9200"},
                {"type": "elasticsearch", "endpoint": "http://es2:9200"},
            },
        },
    },
}).Build()

🎯 最佳实践

1. 模块命名
  • 使用描述性的名称
  • 避免与现有模块冲突
  • 建议使用小写字母和下划线
2. 优先级设置
// 推荐的优先级范围
const (
    PriorityFormatter  = 10-50   // 格式化器
    PriorityMiddleware = 51-100  // 中间件  
    PriorityHandler    = 101-150 // 处理器
    PrioritySink      = 151-200  // 接收器
)
3. 错误处理
func (m *MyModule) Configure(config modules.Config) error {
    if err := m.BaseModule.Configure(config); err != nil {
        return fmt.Errorf("配置基础模块失败: %w", err)
    }
    
    // 验证必需的配置项
    endpoint, ok := config["endpoint"].(string)
    if !ok || endpoint == "" {
        return fmt.Errorf("endpoint配置项是必需的")
    }
    
    return nil
}
4. 资源管理
type MyModule struct {
    *modules.BaseModule
    conn    net.Conn
    closeCh chan struct{}
}

func (m *MyModule) Configure(config modules.Config) error {
    // 配置逻辑...
    
    // 创建资源
    conn, err := net.Dial("tcp", endpoint)
    if err != nil {
        return err
    }
    m.conn = conn
    m.closeCh = make(chan struct{})
    
    // 启动后台协程
    go m.backgroundWorker()
    
    return nil
}

func (m *MyModule) Close() error {
    close(m.closeCh)
    if m.conn != nil {
        return m.conn.Close()
    }
    return nil
}
5. 配置验证
type ModuleConfig struct {
    Endpoint string   `json:"endpoint" validate:"required,url"`
    Timeout  string   `json:"timeout" validate:"required"`
    Level    string   `json:"level" validate:"oneof=debug info warn error"`
    Headers  []string `json:"headers"`
}

func validateConfig(config modules.Config) (*ModuleConfig, error) {
    var cfg ModuleConfig
    
    // 类型转换和验证
    if endpoint, ok := config["endpoint"].(string); ok {
        cfg.Endpoint = endpoint
    } else {
        return nil, fmt.Errorf("endpoint必须是字符串类型")
    }
    
    // 更多验证逻辑...
    
    return &cfg, nil
}

🔍 调试和测试

调试模块
func (m *MyModule) Configure(config modules.Config) error {
    // 启用调试日志
    if debug, ok := config["debug"].(bool); ok && debug {
        m.enableDebugLogging()
    }
    
    return nil
}

func (m *MyModule) debugLog(msg string, args ...any) {
    if m.debugEnabled {
        log.Printf("[%s] %s", m.Name(), fmt.Sprintf(msg, args...))
    }
}
单元测试
func TestEmailModule(t *testing.T) {
    module := NewEmailModule()
    
    config := modules.Config{
        "smtp_host": "localhost",
        "smtp_port": 25,
        "recipients": []string{"[email protected]"},
    }
    
    err := module.Configure(config)
    assert.NoError(t, err)
    assert.Equal(t, "email", module.Name())
    assert.Equal(t, modules.TypeSink, module.Type())
}

📝 贡献指南

  1. Fork 项目
  2. 创建特性分支 (git checkout -b feature/my-module)
  3. modules/ 目录下创建模块目录
  4. 实现模块接口
  5. 添加单元测试
  6. 更新文档
  7. 提交 Pull Request

📖 参考资料

Documentation

Index

Constants

This section is empty.

Variables

View Source
var GlobalInterfaceChecker = &InterfaceChecker{}

全局接口检查器实例

Functions

func BestPractices

func BestPractices()

BestPractices 最佳实践指南

func FeatureComparison

func FeatureComparison()

FeatureComparison 功能对比

func Frame added in v0.1.3

func Frame(pc uintptr) runtime.Frame

Frame 获取调用帧。

func GradualMigrationExample

func GradualMigrationExample()

渐进式迁移示例

func NewSystemExample

func NewSystemExample()

NewSystemExample 展示新系统的简洁性

func OldSystemExample

func OldSystemExample()

OldSystemExample 展示旧系统的复杂性

func PerformanceComparison

func PerformanceComparison()

PerformanceComparison 性能对比示例

func RegisterFactory

func RegisterFactory(name string, factory ModuleFactory) error

RegisterFactory 全局注册工厂

func RegisterGlobalPlugin

func RegisterGlobalPlugin(plugin Plugin, pluginType PluginType) error

RegisterGlobalPlugin 全局注册插件

func RegisterModule

func RegisterModule(module Module) error

RegisterModule 全局注册模块

func SourceLabel added in v0.1.3

func SourceLabel(f runtime.Frame) string

SourceLabel 将 frame 转为短路径标签。

func UpdateModuleConfig added in v0.1.2

func UpdateModuleConfig(name string, config Config) error

UpdateModuleConfig 重新配置现有模块

Types

type BaseComponent

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

BaseComponent 基础组件实现

func NewBaseComponent

func NewBaseComponent(name string, moduleType ModuleType) *BaseComponent

NewBaseComponent 创建基础组件

func (*BaseComponent) Disable

func (bc *BaseComponent) Disable()

Disable 实现Enableable接口

func (*BaseComponent) Enable

func (bc *BaseComponent) Enable()

Enable 实现Enableable接口

func (*BaseComponent) Enabled

func (bc *BaseComponent) Enabled() bool

Enabled 实现Enableable接口

func (*BaseComponent) Name

func (bc *BaseComponent) Name() string

Name 实现Named接口

func (*BaseComponent) Priority

func (bc *BaseComponent) Priority() int

Priority 实现Prioritized接口

func (*BaseComponent) SetPriority

func (bc *BaseComponent) SetPriority(priority int)

SetPriority 实现Prioritized接口

func (*BaseComponent) Type

func (bc *BaseComponent) Type() ModuleType

Type 实现Typed接口

type BaseModule

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

BaseModule 基础模块实现

func NewBaseModule

func NewBaseModule(name string, typ ModuleType, priority int) *BaseModule

NewBaseModule 创建基础模块

func (*BaseModule) Configure

func (m *BaseModule) Configure(config Config) error

func (*BaseModule) Enabled

func (m *BaseModule) Enabled() bool

func (*BaseModule) Handler

func (m *BaseModule) Handler() slog.Handler

func (*BaseModule) Name

func (m *BaseModule) Name() string

func (*BaseModule) Priority

func (m *BaseModule) Priority() int

func (*BaseModule) SetEnabled

func (m *BaseModule) SetEnabled(enabled bool)

func (*BaseModule) SetHandler

func (m *BaseModule) SetHandler(handler slog.Handler)

func (*BaseModule) Type

func (m *BaseModule) Type() ModuleType

type BasePlugin

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

BasePlugin 基础插件实现

func NewBasePlugin

func NewBasePlugin(name string) *BasePlugin

NewBasePlugin 创建基础插件

func (*BasePlugin) Configure

func (bp *BasePlugin) Configure(config map[string]interface{}) error

Configure 配置插件

func (*BasePlugin) Disable

func (bp *BasePlugin) Disable()

Disable 禁用插件

func (*BasePlugin) Enable

func (bp *BasePlugin) Enable()

Enable 启用插件

func (*BasePlugin) Enabled

func (bp *BasePlugin) Enabled() bool

Enabled 检查插件是否启用

func (*BasePlugin) GetConfig

func (bp *BasePlugin) GetConfig(key string) (interface{}, bool)

GetConfig 获取配置项

func (*BasePlugin) Name

func (bp *BasePlugin) Name() string

Name 返回插件名称

type ComponentInterface

type ComponentInterface interface {
	Named
	Typed
	Enableable
}

ComponentInterface 组件基础接口 - 组合核心基础功能

type Config

type Config map[string]any

Config 通用配置接口

func (Config) Bind added in v0.1.1

func (c Config) Bind(target any) error

Bind 将通用 Config 映射到强类型结构体或其他合法的 JSON 目标对象。

它通过标准库的 JSON 编解码器完成类型转换,避免在业务代码中散布显式的类型断言。 使用示例:

var opts struct {
    Endpoint string        `json:"endpoint"`
    Timeout  time.Duration `json:"timeout"`
}
if err := cfg.Bind(&opts); err != nil { ... }

任何实现了 json.Unmarshaler / encoding.TextUnmarshaler 的类型,都会被透明支持。

type Configurable

type Configurable interface {
	// Configure 配置组件
	Configure(config Config) error

	// GetConfig 获取当前配置(可选实现)
	GetConfig() Config
}

Configurable 可配置接口 - 只负责配置管理

type ConfigurableComponent

type ConfigurableComponent struct {
	*BaseComponent
	// contains filtered or unexported fields
}

ConfigurableComponent 可配置组件

func NewConfigurableComponent

func NewConfigurableComponent(name string, moduleType ModuleType) *ConfigurableComponent

NewConfigurableComponent 创建可配置组件

func (*ConfigurableComponent) Configure

func (cc *ConfigurableComponent) Configure(config Config) error

Configure 实现Configurable接口

func (*ConfigurableComponent) GetConfig

func (cc *ConfigurableComponent) GetConfig() Config

GetConfig 实现Configurable接口

type ConfigurableModule

type ConfigurableModule interface {
	ComponentInterface
	Configurable
}

ConfigurableModule 可配置模块接口

type ConfigurablePlugin

type ConfigurablePlugin interface {
	Plugin

	// Configure 配置插件
	Configure(config map[string]interface{}) error

	// GetConfig 获取配置项
	GetConfig(key string) (interface{}, bool)
}

ConfigurablePlugin 可配置插件接口

type Disposable

type Disposable interface {
	// Dispose 释放资源
	Dispose() error

	// IsDisposed 检查是否已释放
	IsDisposed() bool
}

Disposable 可释放接口 - 只负责资源清理

type Enableable

type Enableable interface {
	// Enabled 返回组件是否启用
	Enabled() bool

	// Enable 启用组件
	Enable()

	// Disable 禁用组件
	Disable()
}

Enableable 可启用接口 - 只负责启用状态管理

type ExampleFormatterPlugin

type ExampleFormatterPlugin struct {
	*BasePlugin
	// contains filtered or unexported fields
}

ExampleFormatterPlugin 示例格式化器插件 演示如何将旧的Module转换为新的Plugin

func NewExampleFormatterPlugin

func NewExampleFormatterPlugin(name string, priority int) *ExampleFormatterPlugin

NewExampleFormatterPlugin 创建示例格式化器插件

func (*ExampleFormatterPlugin) Handler

func (efp *ExampleFormatterPlugin) Handler() slog.Handler

Handler 实现HandlerPlugin接口

func (*ExampleFormatterPlugin) Priority

func (efp *ExampleFormatterPlugin) Priority() int

Priority 实现PrioritizedPlugin接口

func (*ExampleFormatterPlugin) SetHandler

func (efp *ExampleFormatterPlugin) SetHandler(handler slog.Handler)

SetHandler 设置处理器

type Formatter

type Formatter interface {
	// Format 格式化数据
	Format(data interface{}) ([]byte, error)

	// MimeType 返回格式化后的MIME类型
	MimeType() string
}

Formatter 格式化器接口 - 只负责数据格式化

type FormatterModule

type FormatterModule interface {
	ComponentInterface
	Formatter
}

FormatterModule 格式化器模块接口

type FormatterProvider added in v0.1.2

type FormatterProvider interface {
	// FormatterFunctions 返回一组与 slog.Handler ReplaceAttr 兼容的格式化函数。
	FormatterFunctions() []func([]string, slog.Attr) (slog.Value, bool)
}

FormatterProvider 提供格式化函数,避免使用反射适配。

type FullModule

FullModule 完整模块接口 - 包含所有基础功能

type HandlerComponent

type HandlerComponent struct {
	*ConfigurableComponent
	// contains filtered or unexported fields
}

HandlerComponent 处理器组件

func NewHandlerComponent

func NewHandlerComponent(name string, moduleType ModuleType, handler slog.Handler) *HandlerComponent

NewHandlerComponent 创建处理器组件

func (*HandlerComponent) Handler

func (hc *HandlerComponent) Handler() slog.Handler

Handler 实现HandlerProvider接口

func (*HandlerComponent) SetHandler

func (hc *HandlerComponent) SetHandler(handler slog.Handler)

SetHandler 实现HandlerProvider接口

type HandlerModule

type HandlerModule interface {
	ComponentInterface
	HandlerProvider
}

HandlerModule 处理器模块接口

type HandlerPlugin

type HandlerPlugin interface {
	Plugin

	// Handler 返回slog处理器
	Handler() slog.Handler
}

HandlerPlugin 处理器插件接口

type HandlerProvider

type HandlerProvider interface {
	// Handler 返回slog处理器
	Handler() slog.Handler

	// SetHandler 设置slog处理器
	SetHandler(handler slog.Handler)
}

HandlerProvider 处理器提供者接口 - 只负责提供slog处理器

type Healthable

type Healthable interface {
	// HealthCheck 执行健康检查
	HealthCheck() error

	// IsHealthy 检查是否健康
	IsHealthy() bool
}

Healthable 健康检查接口 - 只负责健康状态

type Initializable

type Initializable interface {
	// Initialize 初始化组件
	Initialize() error

	// IsInitialized 检查是否已初始化
	IsInitialized() bool
}

Initializable 可初始化接口 - 只负责初始化

type InterfaceChecker

type InterfaceChecker struct{}

InterfaceChecker 接口检查工具

func (*InterfaceChecker) CheckConfigurable

func (ic *InterfaceChecker) CheckConfigurable(obj interface{}) (Configurable, bool)

CheckConfigurable 检查是否实现Configurable接口

func (*InterfaceChecker) CheckEnableable

func (ic *InterfaceChecker) CheckEnableable(obj interface{}) (Enableable, bool)

CheckEnableable 检查是否实现Enableable接口

func (*InterfaceChecker) CheckFullModule

func (ic *InterfaceChecker) CheckFullModule(obj interface{}) (FullModule, bool)

CheckFullModule 检查是否实现FullModule接口

func (*InterfaceChecker) CheckHandlerProvider

func (ic *InterfaceChecker) CheckHandlerProvider(obj interface{}) (HandlerProvider, bool)

CheckHandlerProvider 检查是否实现HandlerProvider接口

func (*InterfaceChecker) CheckNamed

func (ic *InterfaceChecker) CheckNamed(obj interface{}) (Named, bool)

CheckNamed 检查是否实现Named接口

func (*InterfaceChecker) CheckTyped

func (ic *InterfaceChecker) CheckTyped(obj interface{}) (Typed, bool)

CheckTyped 检查是否实现Typed接口

func (*InterfaceChecker) GetImplementedInterfaces

func (ic *InterfaceChecker) GetImplementedInterfaces(obj interface{}) []string

GetImplementedInterfaces 获取对象实现的所有接口列表

type LegacyModuleWrapper

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

LegacyModuleWrapper 旧模块包装器 将旧的Module接口适配到新的接口系统

func NewLegacyModuleWrapper

func NewLegacyModuleWrapper(module Module) *LegacyModuleWrapper

NewLegacyModuleWrapper 创建旧模块包装器

func (*LegacyModuleWrapper) Configure

func (lmw *LegacyModuleWrapper) Configure(config Config) error

Configure 实现Configurable接口

func (*LegacyModuleWrapper) Disable

func (lmw *LegacyModuleWrapper) Disable()

Disable 实现Enableable接口

func (*LegacyModuleWrapper) Enable

func (lmw *LegacyModuleWrapper) Enable()

Enable 实现Enableable接口

func (*LegacyModuleWrapper) Enabled

func (lmw *LegacyModuleWrapper) Enabled() bool

Enabled 实现Enableable接口

func (*LegacyModuleWrapper) GetConfig

func (lmw *LegacyModuleWrapper) GetConfig() Config

GetConfig 实现Configurable接口

func (*LegacyModuleWrapper) Handler

func (lmw *LegacyModuleWrapper) Handler() slog.Handler

Handler 实现HandlerProvider接口

func (*LegacyModuleWrapper) Name

func (lmw *LegacyModuleWrapper) Name() string

Name 实现Named接口

func (*LegacyModuleWrapper) Priority

func (lmw *LegacyModuleWrapper) Priority() int

Priority 实现Prioritized接口

func (*LegacyModuleWrapper) SetHandler

func (lmw *LegacyModuleWrapper) SetHandler(handler slog.Handler)

SetHandler 实现HandlerProvider接口

func (*LegacyModuleWrapper) SetPriority

func (lmw *LegacyModuleWrapper) SetPriority(priority int)

SetPriority 实现Prioritized接口

func (*LegacyModuleWrapper) Type

func (lmw *LegacyModuleWrapper) Type() ModuleType

Type 实现Typed接口

type LifecycleComponent

type LifecycleComponent struct {
	*HandlerComponent
	// contains filtered or unexported fields
}

LifecycleComponent 生命周期组件

func NewLifecycleComponent

func NewLifecycleComponent(name string, moduleType ModuleType, handler slog.Handler) *LifecycleComponent

NewLifecycleComponent 创建生命周期组件

func (*LifecycleComponent) Dispose

func (lc *LifecycleComponent) Dispose() error

Dispose 实现Disposable接口

func (*LifecycleComponent) Initialize

func (lc *LifecycleComponent) Initialize() error

Initialize 实现Initializable接口

func (*LifecycleComponent) IsDisposed

func (lc *LifecycleComponent) IsDisposed() bool

IsDisposed 实现Disposable接口

func (*LifecycleComponent) IsInitialized

func (lc *LifecycleComponent) IsInitialized() bool

IsInitialized 实现Initializable接口

func (*LifecycleComponent) IsRunning

func (lc *LifecycleComponent) IsRunning() bool

IsRunning 实现Startable接口

func (*LifecycleComponent) Start

func (lc *LifecycleComponent) Start() error

Start 实现Startable接口

func (*LifecycleComponent) Stop

func (lc *LifecycleComponent) Stop() error

Stop 实现Startable接口

type ManagedModule

type ManagedModule interface {
	FullModule
	Initializable
	Startable
	Disposable
}

ManagedModule 托管模块接口 - 包含生命周期管理

type Measurable

type Measurable interface {
	// GetMetrics 获取性能指标
	GetMetrics() map[string]interface{}

	// ResetMetrics 重置性能指标
	ResetMetrics()
}

Measurable 可度量接口 - 只负责性能指标

type Middleware

type Middleware interface {
	// Handle 中间件处理函数
	Handle(next func()) func()

	// Order 中间件执行顺序
	Order() int
}

Middleware 中间件接口 - 只负责中间件逻辑

type MiddlewareModule

type MiddlewareModule interface {
	ComponentInterface
	Middleware
}

MiddlewareModule 中间件模块接口

type MigrationAdapter

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

MigrationAdapter 迁移适配器:帮助平滑迁移

func NewMigrationAdapter

func NewMigrationAdapter() *MigrationAdapter

NewMigrationAdapter 创建迁移适配器

func (*MigrationAdapter) WrapOldModule

func (ma *MigrationAdapter) WrapOldModule(module Module) Plugin

WrapOldModule 将旧的Module包装为Plugin

type MigrationExample

type MigrationExample struct{}

MigrationExample 展示如何从旧的Module系统迁移到新的Plugin系统

type Module

type Module interface {
	// Name 返回模块名称
	Name() string
	// Type 返回模块类型
	Type() ModuleType
	// Configure 配置模块
	Configure(config Config) error
	// Handler 返回slog处理器
	Handler() slog.Handler
	// Priority 返回优先级,数字越小优先级越高
	Priority() int
	// Enabled 返回模块是否启用
	Enabled() bool
}

Module 定义模块接口

func CreateModule

func CreateModule(name string, config Config) (Module, error)

CreateModule 全局创建模块

func GetModule

func GetModule(name string) (Module, bool)

GetModule 全局获取模块

func NewHandlerModule added in v0.1.3

func NewHandlerModule(name string, handler slog.Handler) Module

NewHandlerModule 便捷创建处理器模块,默认优先级 100。

type ModuleAdapter

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

ModuleAdapter 模块适配器,帮助将旧接口转换为新接口

func NewModuleAdapter

func NewModuleAdapter(module Module) *ModuleAdapter

NewModuleAdapter 创建模块适配器

func (*ModuleAdapter) AsConfigurable

func (ma *ModuleAdapter) AsConfigurable() Configurable

AsConfigurable 转换为Configurable接口

func (*ModuleAdapter) AsEnableable

func (ma *ModuleAdapter) AsEnableable() Enableable

AsEnableable 转换为Enableable接口

func (*ModuleAdapter) AsHandlerProvider

func (ma *ModuleAdapter) AsHandlerProvider() HandlerProvider

AsHandlerProvider 转换为HandlerProvider接口

func (*ModuleAdapter) AsNamed

func (ma *ModuleAdapter) AsNamed() Named

AsNamed 转换为Named接口

func (*ModuleAdapter) AsPrioritized

func (ma *ModuleAdapter) AsPrioritized() Prioritized

AsPrioritized 转换为Prioritized接口

func (*ModuleAdapter) AsTyped

func (ma *ModuleAdapter) AsTyped() Typed

AsTyped 转换为Typed接口

type ModuleConfig

type ModuleConfig struct {
	Type     string `json:"type"`
	Name     string `json:"name"`
	Enabled  bool   `json:"enabled"`
	Priority int    `json:"priority"`
	Config   Config `json:"config"`
}

ModuleConfig 模块配置

type ModuleFactory

type ModuleFactory func(config Config) (Module, error)

ModuleFactory 模块工厂函数

type ModuleType

type ModuleType int

ModuleType 定义模块类型

const (
	TypeFormatter  ModuleType = iota // 格式化器
	TypeHandler                      // 处理器
	TypeMiddleware                   // 中间件
	TypeSink                         // 日志接收器
)

func (ModuleType) String

func (mt ModuleType) String() string

type MonitoredComponent

type MonitoredComponent struct {
	*LifecycleComponent
	// contains filtered or unexported fields
}

MonitoredComponent 被监控的组件

func NewMonitoredComponent

func NewMonitoredComponent(name string, moduleType ModuleType, handler slog.Handler) *MonitoredComponent

NewMonitoredComponent 创建被监控的组件

func (*MonitoredComponent) AddMetric

func (mc *MonitoredComponent) AddMetric(key string, value interface{})

AddMetric 添加自定义指标

func (*MonitoredComponent) GetMetrics

func (mc *MonitoredComponent) GetMetrics() map[string]interface{}

GetMetrics 实现Measurable接口

func (*MonitoredComponent) HealthCheck

func (mc *MonitoredComponent) HealthCheck() error

HealthCheck 实现Healthable接口

func (*MonitoredComponent) IsHealthy

func (mc *MonitoredComponent) IsHealthy() bool

IsHealthy 实现Healthable接口

func (*MonitoredComponent) ResetMetrics

func (mc *MonitoredComponent) ResetMetrics()

ResetMetrics 实现Measurable接口

type MonitoredModule

type MonitoredModule interface {
	FullModule
	Healthable
	Measurable
}

MonitoredModule 被监控的模块接口 - 包含监控功能

type Named

type Named interface {
	// Name 返回组件名称
	Name() string
}

Named 命名接口 - 只负责提供名称

type OldModuleWrapper

type OldModuleWrapper struct {
	*BasePlugin
	// contains filtered or unexported fields
}

OldModuleWrapper 旧模块包装器

func (*OldModuleWrapper) Configure

func (omw *OldModuleWrapper) Configure(config map[string]interface{}) error

Configure 配置包装器

func (*OldModuleWrapper) Enabled

func (omw *OldModuleWrapper) Enabled() bool

Enabled 检查是否启用

func (*OldModuleWrapper) Handler

func (omw *OldModuleWrapper) Handler() slog.Handler

Handler 获取处理器

func (*OldModuleWrapper) Priority

func (omw *OldModuleWrapper) Priority() int

Priority 获取优先级

type Plugin

type Plugin interface {
	// Name 返回插件名称
	Name() string

	// Enabled 检查插件是否启用
	Enabled() bool

	// Enable 启用插件
	Enable()

	// Disable 禁用插件
	Disable()
}

Plugin 简化的插件接口 - 单一职责原则

func GetGlobalPlugin

func GetGlobalPlugin(name string) (Plugin, bool)

GetGlobalPlugin 全局获取插件

func GetGlobalPluginsByType

func GetGlobalPluginsByType(pluginType PluginType) []Plugin

GetGlobalPluginsByType 全局获取指定类型的插件

type PluginInfo

type PluginInfo struct {
	Name     string                 `json:"name"`
	Type     PluginType             `json:"type"`
	Enabled  bool                   `json:"enabled"`
	Priority int                    `json:"priority"`
	Config   map[string]interface{} `json:"config,omitempty"`
}

PluginInfo 插件信息

type PluginManager

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

PluginManager 简化的插件管理器

func GetGlobalPluginManager

func GetGlobalPluginManager() *PluginManager

GetGlobalPluginManager 获取全局插件管理器

func NewPluginManager

func NewPluginManager() *PluginManager

NewPluginManager 创建新的插件管理器

func (*PluginManager) Disable

func (pm *PluginManager) Disable()

Disable 禁用管理器

func (*PluginManager) DisableAll

func (pm *PluginManager) DisableAll()

DisableAll 禁用所有插件

func (*PluginManager) DisablePlugin

func (pm *PluginManager) DisablePlugin(name string) error

DisablePlugin 禁用指定插件

func (*PluginManager) Enable

func (pm *PluginManager) Enable()

Enable 启用管理器

func (*PluginManager) EnableAll

func (pm *PluginManager) EnableAll()

EnableAll 启用所有插件

func (*PluginManager) EnablePlugin

func (pm *PluginManager) EnablePlugin(name string) error

EnablePlugin 启用指定插件

func (*PluginManager) GetPlugin

func (pm *PluginManager) GetPlugin(name string) (Plugin, bool)

GetPlugin 获取指定名称的插件

func (*PluginManager) GetPluginsByType

func (pm *PluginManager) GetPluginsByType(pluginType PluginType) []Plugin

GetPluginsByType 获取指定类型的所有插件(按优先级排序)

func (*PluginManager) GetStats

func (pm *PluginManager) GetStats() PluginStats

GetStats 获取插件统计信息

func (*PluginManager) IsEnabled

func (pm *PluginManager) IsEnabled() bool

IsEnabled 检查管理器是否启用

func (*PluginManager) ListPlugins

func (pm *PluginManager) ListPlugins() []string

ListPlugins 列出所有插件名称

func (*PluginManager) RegisterPlugin

func (pm *PluginManager) RegisterPlugin(plugin Plugin, pluginType PluginType) error

RegisterPlugin 注册插件

func (*PluginManager) UnregisterPlugin

func (pm *PluginManager) UnregisterPlugin(name string) error

UnregisterPlugin 注销插件

type PluginStats

type PluginStats struct {
	TotalPlugins   int                   `json:"total_plugins"`
	EnabledPlugins int                   `json:"enabled_plugins"`
	TypeCounts     map[PluginType]int    `json:"type_counts"`
	PluginInfo     map[string]PluginInfo `json:"plugin_info"`
}

PluginStats 插件统计信息

type PluginType

type PluginType string

PluginType 插件类型枚举

const (
	PluginFormatter  PluginType = "formatter"
	PluginHandler    PluginType = "handler"
	PluginMiddleware PluginType = "middleware"
	PluginSink       PluginType = "sink"
)

type Prioritized

type Prioritized interface {
	// Priority 返回优先级,数字越小优先级越高
	Priority() int

	// SetPriority 设置优先级
	SetPriority(priority int)
}

Prioritized 优先级接口 - 只负责优先级管理

type PrioritizedModule

type PrioritizedModule interface {
	ComponentInterface
	Prioritized
}

PrioritizedModule 有优先级的模块接口

type PrioritizedPlugin

type PrioritizedPlugin interface {
	Plugin

	// Priority 返回优先级,数字越小优先级越高
	Priority() int
}

PrioritizedPlugin 有优先级的插件接口

type Processor

type Processor interface {
	// Process 处理数据
	Process(data interface{}) (interface{}, error)
}

Processor 处理器接口 - 只负责数据处理

type ProcessorModule

type ProcessorModule interface {
	ComponentInterface
	Processor
}

ProcessorModule 处理器模块接口

type Registry

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

Registry 模块注册中心

func GetRegistry

func GetRegistry() *Registry

GetRegistry 获取全局注册中心

func NewRegistry

func NewRegistry() *Registry

NewRegistry 创建新的注册中心

func (*Registry) Create

func (r *Registry) Create(name string, config Config) (Module, error)

Create 通过工厂创建模块

func (*Registry) Get

func (r *Registry) Get(name string) (Module, bool)

Get 获取模块

func (*Registry) GetByType

func (r *Registry) GetByType(moduleType ModuleType) []Module

GetByType 按类型获取模块列表

func (*Registry) List

func (r *Registry) List() []Module

List 列出所有模块

func (*Registry) ListFactories

func (r *Registry) ListFactories() []string

ListFactories 列出所有已注册的工厂名称

func (*Registry) Register

func (r *Registry) Register(module Module) error

Register 注册模块实例

func (*Registry) RegisterFactory

func (r *Registry) RegisterFactory(name string, factory ModuleFactory) error

RegisterFactory 注册模块工厂

func (*Registry) Remove

func (r *Registry) Remove(name string) error

Remove 移除模块

func (*Registry) Update added in v0.1.2

func (r *Registry) Update(name string, config Config) error

Update 重新配置已注册模块

type SimpleFormatter

type SimpleFormatter struct {
	*BaseComponent
}

SimpleFormatter 简单格式化器实现

func NewSimpleFormatter

func NewSimpleFormatter(name string) *SimpleFormatter

NewSimpleFormatter 创建简单格式化器

func (*SimpleFormatter) Format

func (sf *SimpleFormatter) Format(data interface{}) ([]byte, error)

Format 实现Formatter接口

func (*SimpleFormatter) MimeType

func (sf *SimpleFormatter) MimeType() string

MimeType 实现Formatter接口

type SimpleProcessor

type SimpleProcessor struct {
	*BaseComponent
}

SimpleProcessor 简单处理器实现

func NewSimpleProcessor

func NewSimpleProcessor(name string) *SimpleProcessor

NewSimpleProcessor 创建简单处理器

func (*SimpleProcessor) Process

func (sp *SimpleProcessor) Process(data interface{}) (interface{}, error)

Process 实现Processor接口

type Sink

type Sink interface {
	// Write 写入数据
	Write(data []byte) (int, error)

	// Flush 刷新缓冲区
	Flush() error

	// Close 关闭接收器
	Close() error
}

Sink 数据接收器接口 - 只负责数据输出

type SinkModule

type SinkModule interface {
	ComponentInterface
	Sink
}

SinkModule 接收器模块接口

type Startable

type Startable interface {
	// Start 启动组件
	Start() error

	// Stop 停止组件
	Stop() error

	// IsRunning 检查是否正在运行
	IsRunning() bool
}

Startable 可启动接口 - 只负责启动/停止

type Typed

type Typed interface {
	// Type 返回组件类型
	Type() ModuleType
}

Typed 类型接口 - 只负责提供类型信息

type WriteSyncer added in v0.1.3

type WriteSyncer interface {
	io.Writer
}

WriteSyncer 兼容 io.Writer,用于输出 handler。

func NewStdWriter added in v0.1.3

func NewStdWriter() WriteSyncer

NewStdWriter 返回标准输出 writer。

Directories

Path Synopsis
output

Jump to

Keyboard shortcuts

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