Examples
C++ Logging Setup
Setting Up Logging
C++ logging setup with spdlog logs requests and errors.
Introduction to spdlog
spdlog is a fast, header-only C++ logging library. It provides an easy way to log messages with different severity levels, such as info, warn, error, and more. This makes it an excellent choice for logging requests and errors in C++ applications.
Installing spdlog
To use spdlog in your project, you can either clone the repository or use a package manager like vcpkg or Conan. Below is a quick guide on how to install spdlog using vcpkg:
git clone https://github.com/microsoft/vcpkg.git
cd vcpkg
./bootstrap-vcpkg.sh
./vcpkg integrate install
vcpkg install spdlog
Basic Setup of spdlog
Once spdlog is installed, you can include it in your project. Below is an example of how to set up a basic logger that logs to the console:
#include <spdlog/spdlog.h>
int main() {
auto console = spdlog::stdout_color_mt("console");
console->info("Welcome to spdlog!");
console->warn("This is a warning!");
console->error("An error has occurred!");
return 0;
}
File Logging with spdlog
spdlog can also log messages to files. This is useful for keeping a persistent log of application activities. Here's how you can set up file logging:
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
int main() {
auto file_logger = spdlog::basic_logger_mt("file_logger", "logs/app.log");
file_logger->info("Logging to a file!");
file_logger->warn("This is a file warning!");
file_logger->error("File error encountered!");
return 0;
}
Combining Console and File Logging
For comprehensive logging, you might want to log to both the console and a file. spdlog allows you to combine multiple sinks easily:
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/basic_file_sink.h>
int main() {
auto console_sink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
auto file_sink = std::make_shared<spdlog::sinks::basic_file_sink_mt>("logs/combined.log", true);
spdlog::logger logger("multi_sink", {console_sink, file_sink});
logger.set_level(spdlog::level::debug);
logger.info("This message goes to both console and file");
logger.warn("This warning is logged in both places");
logger.error("Error logged in console and file");
return 0;
}
Conclusion
Setting up logging in C++ with spdlog provides a robust solution for tracking application activity. Whether logging to the console, a file, or both, spdlog offers the flexibility and performance needed for both simple and advanced logging requirements.
Examples
- Previous
- API Testing
- Next
- Dockerized App