使用try-catch捕获异常并记录日志,结合自定义异常类添加文件、行号、函数名等上下文信息,通过宏自动注入位置,集成spdlog等日志库实现分级异步输出,辅以断言和错误码记录关键函数执行状态,建立统一错误处理规范,确保日志清晰结构化,便于问题追踪分析。

在C++开发中,异常和错误的追踪是保障程序稳定性的关键环节。由于C++本身不内置完善的日志系统,开发者需要结合异常处理机制与日志记录策略,实现有效的错误信息追踪。以下是几种实用的方法。
在可能发生异常的代码区域使用try-catch结构,捕获标准异常或自定义异常,并将错误信息写入日志文件。
示例:
#include <stdexcept>
#include <iostream>
#include <fstream>
<p>void logError(const std::string& msg) {
std::ofstream logFile("error.log", std::ios::app);
if (logFile.is_open()) {
logFile << "[ERROR] " << msg << "\n";
logFile.close();
}
}</p><p>int main() {
try {
throw std::runtime_error("Something went wrong");
} catch (const std::exception& e) {
logError(std::string("Caught exception: ") + e.what());
}
return 0;
}</p>这种方法能捕获异常内容并持久化存储,便于后续分析。
立即学习“C++免费学习笔记(深入)”;
标准异常的
what()
#define THROW_EXCEPTION(msg) \
throw CustomException(msg, __FILE__, __LINE__, __func__)
<p>class CustomException : public std::exception {
public:
CustomException(const std::string& msg, const char<em> file, int line, const char</em> func)
: message(msg), file(file), line(line), func(func) {}</p><pre class='brush:php;toolbar:false;'>const char* what() const noexcept override {
std::ostringstream oss;
oss << "[" << file << ":" << line << "] "
<< func << "() - " << message;
whatBuffer = oss.str();
return whatBuffer.c_str();
}private: std::string message; const char file; int line; const char func; mutable std::string whatBuffer; };
使用宏定义在抛出异常时自动注入位置信息,提升日志可读性。
使用成熟的日志库可以简化日志管理,支持分级输出、异步写入、文件滚动等功能。
以spdlog为例:
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
<p>int main() {
auto logger = spdlog::basic_logger_mt("file_logger", "logs/basic.txt");</p><pre class='brush:php;toolbar:false;'>try {
// some error
throw std::runtime_error("Test error");
} catch (const std::exception& e) {
logger->error("Exception caught: {}", e.what());
}
spdlog::shutdown();
return 0;}
spdlog支持格式化输出、多线程安全和多种日志级别,适合大型项目。
对于非异常错误(如函数调用失败),可结合返回码与日志输出。
例如:
bool processData() {
if (!validateInput()) {
logError("Input validation failed in processData()");
return false;
}
// ...
return true;
}
在关键函数中加入日志输出,有助于定位执行路径和失败节点。
基本上就这些。关键是建立统一的错误处理规范,确保所有异常和关键错误都能被记录并包含足够上下文。日志信息要清晰、结构化,便于后期排查问题。不复杂但容易忽略。
以上就是C++异常日志记录 错误信息追踪方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号