Files
rust_logger/README.md
2026-01-21 14:03:53 +08:00

136 lines
3.2 KiB
Markdown
Raw Permalink 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.

```mermaid
classDiagram
class LogLevel {
<<enumeration>>
DEBUG
INFO
WARNING
ERROR
FATAL
}
class LogRecord {
+DateTime timestamp
+LogLevel level
+String message
+String target
}
class LogOutput {
<<interface>>
+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 {
<<interface>>
<<Send + Sync>>
+write(record: LogRecord) Future
}
%% 具体实现
class PostgresOutput {
-PgPool pool
+write(record)
}
class ConsoleOutput {
+write(record)
}
%% 业务线程持有的 Logger (Producer)
class Logger {
<<Thread-Safe>>
<<Shared via Arc>>
-mpsc::Sender~LogRecord~ tx
-LogLevel min_level
+log(level, msg)
}
%% 后台异步任务 (Consumer)
class BackgroundWorker {
<<Active Object>>
<<Running in tokio::spawn>>
-mpsc::Receiver~LogRecord~ rx
-Vec~Box~LogOutput~~ outputs
+run()
}
%% 数据包
class LogRecord {
<<Immutable>>
+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 # 模拟业务服务使用
```