如何修改AWS C++ SDK的日志输出格式(含字段顺序与时间戳)
自定义AWS C++ SDK日志格式以匹配应用规范
你不需要修改SDK源码,通过扩展SDK的日志接口就能实现自定义格式,以下是两种可行方案:
方案1:继承FormattedLogSystem重写格式化逻辑
ConsoleLogSystem本质是FormattedLogSystem的子类,而FormattedLogSystem的日志格式化方法是可重写的虚函数。你可以创建自定义子类,实现符合自身规范的日志格式:
#include <aws/core/utils/logging/FormattedLogSystem.h> #include <aws/core/utils/DateTime.h> #include <iomanip> #include <sstream> #include <thread> class CustomConsoleLogSystem : public Aws::Utils::Logging::FormattedLogSystem { public: using Base = Aws::Utils::Logging::FormattedLogSystem; CustomConsoleLogSystem(Aws::Utils::Logging::LogLevel logLevel) : Base(logLevel) {} // 重写日志格式化方法,按自定义规则拼接字段 Aws::String FormatLogLine(Aws::Utils::Logging::LogLevel logLevel, const Aws::String& tag, const Aws::String& message) const override { // 自定义时间戳格式,示例为YYYY-MM-DD HH:MM:SS.sss auto now = Aws::Utils::DateTime::Now(); std::stringstream timestampStream; timestampStream << std::setw(4) << std::setfill('0') << now.GetYear() << "-" << std::setw(2) << std::setfill('0') << static_cast<int>(now.GetMonth()) << "-" << std::setw(2) << std::setfill('0') << now.GetDay() << " " << std::setw(2) << std::setfill('0') << now.GetHour() << ":" << std::setw(2) << std::setfill('0') << now.Minute() << ":" << std::setw(2) << std::setfill('0') << now.Second() << "." << std::setw(3) << std::setfill('0') << now.Milliseconds(); // 按需求调整字段顺序,示例为[线程ID] 时间戳 [日志级别] 类名 日志内容 std::stringstream logStream; logStream << "[" << std::this_thread::get_id() << "] " << timestampStream.str() << " " << "[" << LogLevelToString(logLevel) << "] " << tag << " " << message << std::endl; return logStream.str(); } };
然后在应用初始化时替换默认日志系统:
#include <aws/core/utils/logging/AWSLogging.h> int main() { // 初始化自定义日志系统,设置日志级别 auto customLogger = Aws::MakeShared<CustomConsoleLogSystem>("CustomConsoleLogger", Aws::Utils::Logging::LogLevel::Debug); Aws::Utils::Logging::InitializeAWSLogging(customLogger); // 后续AWS SDK操作的日志会按自定义格式输出 // 程序结束时关闭日志系统 Aws::Utils::Logging::ShutdownAWSLogging(); return 0; }
方案2:完全实现LogSystemInterface接口
如果需要更灵活的控制(比如输出到文件、整合第三方日志库等),可以直接实现Aws::Utils::Logging::LogSystemInterface接口,自定义日志的输出逻辑:
#include <aws/core/utils/logging/LogSystemInterface.h> #include <aws/core/utils/DateTime.h> #include <iostream> #include <thread> class CustomLogSystem : public Aws::Utils::Logging::LogSystemInterface { public: Aws::Utils::Logging::LogLevel GetLogLevel() const override { return Aws::Utils::Logging::LogLevel::Info; } void Log(Aws::Utils::Logging::LogLevel logLevel, const char* tag, const char* message) override { // 自定义格式和输出逻辑,示例输出到stdout auto now = Aws::Utils::DateTime::Now(); std::cout << "[" << std::this_thread::get_id() << "] " << now.ToLocalTimeString(Aws::Utils::DateFormat::ISO_8601) << " " << "[" << LogLevelToString(logLevel) << "] " << tag << " " << message << std::endl; } };
初始化方式和方案1一致,用InitializeAWSLogging设置自定义实例即可。
内容的提问来源于stack exchange,提问作者Grant S
相关产品推荐
相关产品推荐

