Structured logging is essential for modern application development as it allows developers to log events in a uniform format, making it easier to parse and analyze logs. In C++, you can implement structured logging using JSON format, which can enhance readability and provide a structured way to capture log details.
Here is an example of how to implement JSON structured logging in C++ using the popular nlohmann/json
library:
#include
#include
#include
using json = nlohmann::json;
void log_event(const std::string& message, const std::string& level) {
json log_entry;
log_entry["level"] = level;
log_entry["message"] = message;
log_entry["timestamp"] = std::time(0);
// Output to console
std::cout << log_entry.dump() << std::endl;
// Optionally, write to file
std::ofstream log_file("logs.json", std::ios::app);
if (log_file.is_open()) {
log_file << log_entry.dump() << std::endl;
log_file.close();
}
}
int main() {
log_event("Application started", "info");
log_event("An error occurred", "error");
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?