Files
goproxy/examples/plugin/plugins/logger/logger_plugin.go
DarkiT 098c721ee9 增强插件系统:添加插件类型支持
- 在插件接口和基本插件结构中引入插件类型(PluginType),并定义了多种预定义的插件类型。
- 更新插件管理器以支持按类型管理插件,新增按类型获取、初始化和启动插件的方法。
- 修改现有插件(如日志插件和统计插件)以实现插件类型接口,确保兼容性。
- 优化插件信息输出,包含插件类型信息。

此更新提升了插件系统的灵活性和可扩展性,便于未来添加更多插件类型。
2025-03-14 11:07:53 +08:00

129 lines
3.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"time"
"github.com/darkit/goproxy/examples/plugin"
)
// LoggerPlugin 日志插件
// 提供文件日志和控制台日志功能
type LoggerPlugin struct {
*plugin.BasePlugin // 嵌入基本插件结构
logFile *os.File // 日志文件
logger *log.Logger // 日志记录器
config map[string]interface{} // 配置
}
// Plugin 导出的插件变量
// 注意变量名必须是Plugin大小写敏感
var Plugin = &LoggerPlugin{
BasePlugin: plugin.NewBasePlugin(
"LoggerPlugin",
"1.0.0",
"简单的日志记录插件",
"开发者",
plugin.PluginTypeUtils, // 设置插件类型为工具插件
),
}
// Init 初始化插件
func (p *LoggerPlugin) Init(ctx context.Context, config map[string]interface{}) error {
p.config = config
// 获取日志文件路径
logPath, ok := config["log_path"].(string)
if !ok {
// 使用默认路径
logPath = "logs"
}
// 确保日志目录存在
if err := os.MkdirAll(logPath, 0o755); err != nil {
return fmt.Errorf("创建日志目录失败: %v", err)
}
// 创建日志文件
logFilePath := filepath.Join(logPath, fmt.Sprintf("app_%s.log", time.Now().Format("2006-01-02")))
logFile, err := os.OpenFile(logFilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
return fmt.Errorf("打开日志文件失败: %v", err)
}
p.logFile = logFile
p.logger = log.New(logFile, "[LoggerPlugin] ", log.LstdFlags)
p.logger.Println("日志插件初始化完成")
fmt.Println("日志插件初始化完成,日志文件:", logFilePath)
return nil
}
// Start 启动插件
func (p *LoggerPlugin) Start(ctx context.Context) error {
if p.logger == nil {
return fmt.Errorf("插件未初始化")
}
p.logger.Println("日志插件已启动")
fmt.Println("日志插件已启动")
return nil
}
// Stop 停止插件
func (p *LoggerPlugin) Stop(ctx context.Context) error {
if p.logger != nil {
p.logger.Println("日志插件正在停止")
}
if p.logFile != nil {
if err := p.logFile.Close(); err != nil {
return fmt.Errorf("关闭日志文件失败: %v", err)
}
}
fmt.Println("日志插件已停止")
return nil
}
// Log 记录日志
func (p *LoggerPlugin) Log(level, message string) {
if p.logger == nil {
fmt.Printf("[%s] %s\n", level, message)
return
}
logMsg := fmt.Sprintf("[%s] %s", level, message)
p.logger.Println(logMsg)
// 如果配置了同时输出到控制台
if consoleOutput, ok := p.config["console_output"].(bool); ok && consoleOutput {
fmt.Println(logMsg)
}
}
// Info 记录信息日志
func (p *LoggerPlugin) Info(message string) {
p.Log("INFO", message)
}
// Warn 记录警告日志
func (p *LoggerPlugin) Warn(message string) {
p.Log("WARN", message)
}
// Error 记录错误日志
func (p *LoggerPlugin) Error(message string) {
p.Log("ERROR", message)
}
// main 函数是必须的,但不会被调用
func main() {
// 不会被执行,仅用于编译插件
}