```mermaid classDiagram class LogLevel { <> DEBUG INFO WARNING ERROR FATAL } class LogRecord { +DateTime timestamp +LogLevel level +String message +String target } class LogOutput { <> +write(record: LogRecord) Future } class ConsoleOutput { +write(record: LogRecord) } class PostgresOutput { -PgPool pool +new(pool: PgPool) +write(record: LogRecord) } class FileOutput { -File file +write(record: LogRecord) } class LoggerConfig { +LogLevel min_level +Vec~Box~LogOutput~~ outputs } class Logger { -Sender~LogRecord~ tx -LogLevel min_level +init(config: LoggerConfig) Arc~Logger~ +log(level, message, target) -run_background_task(rx, outputs) } %% Relationships LogOutput <|.. ConsoleOutput : Implements LogOutput <|.. PostgresOutput : Implements LogOutput <|.. FileOutput : Implements Logger ..> LogRecord : Creates Logger o-- LoggerConfig : Uses LoggerConfig o-- LogOutput : Aggregates (0..*) LogRecord -- LogLevel : Has ``` ```mermaid classDiagram %% 接口定义:强调 Send + Sync 约束 class LogOutput { <> <> +write(record: LogRecord) Future } %% 具体实现 class PostgresOutput { -PgPool pool +write(record) } class ConsoleOutput { +write(record) } %% 业务线程持有的 Logger (Producer) class Logger { <> <> -mpsc::Sender~LogRecord~ tx -LogLevel min_level +log(level, msg) } %% 后台异步任务 (Consumer) class BackgroundWorker { <> <> -mpsc::Receiver~LogRecord~ rx -Vec~Box~LogOutput~~ outputs +run() } %% 数据包 class LogRecord { <> +timestamp +level +message } %% 关系描述 LogOutput <|.. PostgresOutput LogOutput <|.. ConsoleOutput %% 关键的线程安全机制:MPSC Channel Logger "1" o-- "1" `mpsc::Sender` : Owns BackgroundWorker "1" o-- "1" `mpsc::Receiver` : Owns %% 逻辑流 ClientThread ..> Logger : 1. Calls log() (Non-blocking) Logger ..> `mpsc::Sender` : 2. Sends Record `mpsc::Sender` ..> `mpsc::Receiver` : 3. Channel Transfer (Thread-Safe) `mpsc::Receiver` ..> BackgroundWorker : 4. Receives Record BackgroundWorker --> LogOutput : 5. Serialized Writes ``` ```text my-logger/ ├── Cargo.toml ├── .env # 数据库配置 ├── src/ │ ├── lib.rs # 库入口,定义宏 │ ├── model.rs # 定义 LogLevel, LogRecord │ ├── outputs/ # 输出模块 │ │ ├── mod.rs # Trait 定义 │ │ ├── console.rs # 控制台输出实现 │ │ └── postgres.rs # 数据库输出实现 │ ├── core.rs # Logger 核心逻辑 (Channel, Spawn) │ └── main.rs # 模拟业务服务使用 ```