用std::chrono::system_clock::now()获取时间,转time_t得秒级部分,duration_cast取毫秒余数,再用ostringstream拼接为“yyyy-mm-dd hh:mm:ss.mmm”格式。

如何用 C++ 实现一个线程安全、带毫秒级时间戳的简易 Logger
直接结论:不需要第三方库,用 std::chrono + std::mutex + std::ofstream 就能写出轻量、可靠、可复用的 Logger。关键不是“功能多”,而是时间精度不丢、多线程写日志不乱、文件不崩溃。
std::chrono::system_clock::now() 怎么格式化成 “YYYY-MM-DD HH:MM:SS.mmm”
标准库不提供直接格式化毫秒的接口,得手动拆解。别用 std::put_time(它只到秒),也别用 C 风格 strftime(不支持毫秒)。正确做法是先转为 time_t 拿秒级部分,再用 duration_cast 提取毫秒余数:
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);
auto ms = std::chrono::duration_cast<:chrono::milliseconds>(now.time_since_epoch()) % 1000;
std::ostringstream oss;
oss
<ul>
<li>必须用 <code>std::localtime</code> 而非 <code>std::gmtime</code>,否则时区错</li>
<li>
<code>% 1000</code> 是必须的——<code>time_since_epoch()</code> 返回的是纳秒或微秒级值,直接除会溢出或截断</li>
<li>
<code>std::setfill('0') + std::setw(3)</code> 保证毫秒恒为三位,避免 “1.2” 这种错位</li>
</ul>
<h3>为什么必须加 <code>std::mutex</code>,以及锁粒度怎么选</h3>
<p>多个线程同时调用 <code>operator 写同一个 <code>std::ofstream</code>,会导致日志行交叉(比如 A 线程写一半被 B 插入,结果变成 “A1B1A2B2”)。但锁整个 <code>log()</code> 函数太重,锁 <code>ofstream::write</code> 又太细——正确粒度是锁「格式化 + 一次 write」这个原子操作:</code></p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill5502" title="C++ Code Review Master"><img
src="https://img.php.cn/upload/skill/000/000/081/179051228971575.jpg" alt="C++ Code Review Master" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill5502" title="C++ Code Review Master" class="overflowclass">C++ Code Review Master</a>
<p class="overflowclass">组合式C++代码评审方案,融合静态分析、AI推理、多轮迭代评审和C++专项检查,适用于PR审查、增量代码审查、全项目评审和代码质量评分,触发词包括review cpp、cpp代码评审、C++review、代码审查。</p>
</div>
<a rel="nofollow" href="/xiazai/skill5502" title="C++ Code Review Master" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<pre class="brush:php;toolbar:false;">
class Logger {
std::ofstream file_;
mutable std::mutex mtx_;
public:
void log(const std::string& level, const std::string& msg) const {
std::lock_guard<:mutex> lk(mtx_);
auto ts = format_timestamp(); // 上面那段逻辑
file_
<ul>
<li>不要把 <code>file_</code> 声明为 <code>std::ofstream&</code> 引用——构造时若文件打开失败,引用会悬空</li>
<li>
<code>file_.flush()</code> 必须加,否则大量日志可能卡在缓冲区里,调试时“明明调了 log 却看不到输出”</li>
<li>如果追求极致性能且日志量极大,可考虑无锁环形缓冲 + 单独日志线程,但对“简单 Logger”属于过度设计</li>
</ul>
<h3>构造时打开文件失败怎么处理,以及 <code>std::ofstream</code> 的常见陷阱</h3>
<p>最常被忽略的是:<code>std::ofstream</code> 默认不抛异常,open 失败后 <code>file_.is_open()</code> 为 false,但后续 <code> 操作静默失败——日志全丢,还毫无提示。</code></p>
<ul>
<li>必须在构造函数里检查:<code>if (!file_.is_open()) { throw std::runtime_error("Failed to open log file: " + filename); }</code>
</li>
<li>避免使用相对路径(如 <code>"log.txt"</code>)——当前工作目录不确定,建议用绝对路径或从环境变量读取</li>
<li>不要在每次 <code>log()</code> 里重新 open/close 文件,磁盘 I/O 开销大,且并发时易冲突;应保持 long-lived file stream</li>
<li>如果需要按天滚动日志,不能靠重命名正在写的文件(Windows 下会失败),得在每日首次 log 时检测日期并新建流</li>
</ul>
<p>真正难的不是写几行格式化代码,而是确保时间不漂移、多线程不撕裂、文件句柄不泄漏、错误有反馈——这些细节一漏,Logger 就从调试帮手变成定时炸弹。</p></:mutex>C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










