How do I add structured logging with JSON in C++?

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; }

structured logging C++ JSON logging nlohmann/json logging framework