装饰器模式通过抽象logger接口和可组合的decorator子类,实现异步日志功能动态叠加,如requestiddecorator和timestampdecorator,无需修改asyncfilelogger源码,确保异步性与解耦。

你需要在C++服务中为异步日志系统动态叠加功能,比如自动添加请求ID、格式化时间戳、过滤敏感字段、压缩日志体,且不修改原有日志器代码——装饰器模式正好满足这一需求,它允许你在运行时按需组合行为,避免继承爆炸和硬编码耦合。
定义可装饰的日志器接口
先声明抽象基类 Logger,所有具体日志器和装饰器都继承它。接口只暴露 log 方法,参数为 const std::string&,返回 void —— 这是装饰链调用的统一入口点。
注意:析构函数必须为 virtual,否则通过基类指针删除派生类装饰器对象时会漏掉子类资源清理。
class Logger {
public:
virtual ~Logger() = default;
virtual void log(const std::string& msg) = 0;
};
实现基础异步日志器(被装饰目标)
创建 AsyncFileLogger,内部使用 std::thread + std::queue + std::mutex 实现线程安全的异步写入。构造时传入文件路径,log 方法仅将消息推入队列,不阻塞调用线程。
这一步不能直接写磁盘,否则装饰器叠加后每层都可能触发同步 I/O,破坏异步性。
class AsyncFileLogger : public Logger {
private:
std::ofstream file_;
std::queue<:string> queue_;
std::mutex mtx_;
std::thread worker_;
std::atomic
public:
AsyncFileLogger(const std::string& path) : file_(path, std::ios::app) {
worker_ = std::thread([this] {
while (running_ || !queue_.empty()) {
std::string msg;
{
std::lock_guard<:mutex> lock(mtx_);
if (queue_.empty()) continue;
msg = std::move(queue_.front());
queue_.pop();
}
file_ file_.flush();
}
}
);
}
void log(const std::string& msg) override {
std::lock_guard<:mutex> lock(mtx_);
queue_.push(msg);
}
~AsyncFileLogger() {
running_ = false;
if (worker_.joinable()) worker_.join();
}
};
编写通用装饰器基类
Decorator 是所有装饰器的父类,持有一个 std::unique_ptr
class Decorator : public Logger {
protected:
std::unique_ptr
public:
explicit Decorator(std::unique_ptr
void log(const std::string& msg) override {
wrapped_->log(msg);
}
};
实现具体装饰功能
方法一:添加请求上下文(RequestIDDecorator)
在每条日志前拼接当前线程局部存储中的请求 ID。使用 thread_local std::string request_id 存储,需确保上游中间件已设置该值。若未设置,则 fallback 为空字符串,避免崩溃。
组合式C++代码评审方案,融合静态分析、AI推理、多轮迭代评审和C++专项检查,适用于PR审查、增量代码审查、全项目评审和代码质量评分,触发词包括review cpp、cpp代码评审、C++review、代码审查。
class RequestIDDecorator : public Decorator {
thread_local static std::string request_id;
public:
using Decorator::Decorator;
void log(const std::string& msg) override {
wrapped_->log("[" + request_id + "] " + msg);
}
};
thread_local std::string RequestIDDecorator::request_id = "";
方法二:时间戳增强(TimestampDecorator)
使用 std::chrono::system_clock::now() 获取毫秒级时间,格式化为 ISO8601 字符串(如 2024-05-22T14:23:18.123)。注意:不要用 std::put_time,它不支持毫秒;应手动拆解 time_point。
class TimestampDecorator : public Decorator {
public:
using Decorator::Decorator;
void log(const std::string& msg) override {
auto now = std::chrono::system_clock::now();
auto ms = std::chrono::duration_cast<:chrono::milliseconds>(now.time_since_epoch()) % 1000;
auto time_t = std::chrono::system_clock::to_time_t(now);
std::stringstream ss;
ss ss wrapped_->log("[" + ss.str() + "] " + msg);
}
};
方法三:敏感字段过滤(FilterDecorator)
接收正则表达式 pattern(如 R"(password\s*[:=]\s*\S+)"),对输入 msg 执行全局替换,用 "***" 遮盖匹配内容。注意:正则编译开销大,应在构造时完成,而非每次 log 时重复 compile。
class FilterDecorator : public Decorator {
private:
std::regex pattern_;
std::string replacement_;
public:
FilterDecorator(std::unique_ptr
: Decorator(std::move(logger)), pattern_(pattern), replacement_(replacement) {}
void log(const std::string& msg) override {
std::string filtered = std::regex_replace(msg, pattern_, replacement_);
wrapped_->log(filtered);
}
};
组合多个装饰器并启用
第一步:创建最内层日志器实例
auto logger = std::make_unique
第二步:逐层包裹装饰器,顺序决定执行顺序(最外层最先执行)
logger = std::make_unique
logger = std::make_unique
logger = std::make_unique
第三步:调用 log 触发完整装饰链
logger->log("User login succeeded"); // 输出形如:[req-abc123][2024-05-22T14:23:18.123] User login succeeded
第四步:确保 logger 生命周期覆盖整个程序运行期,建议用 std::shared_ptr 管理或作为全局静态变量持有。若在局部作用域构造后立即释放 unique_ptr,会导致装饰器链提前析构,后续 log 调用触发空指针异常。
【logger 必须在 main() 结束前保持有效,不可在作用域末尾自动销毁】
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










