Skip to content

2. Creating loggers

Denis edited this page Apr 15, 2015 · 54 revisions

Each logger contains a vector of one or more std::shared_ptr<spdlog::sink>. On each log call (if the log level is right) the logger will call the sink(log_msg) function on each of them.

spdlog's sinks have _mt (multi threaded) or _st (single threaded) suffixes to indicate the thread safety. While single threaded sinks cannot be used from multiple threads simultaneously they might be faster because no locking is employed.

Creating loggers using the factory functions

The easiest way to create loggers is to use the factory functions in spdlog.h:

//Create and return a shared_ptr to a multithreaded console logger.
auto console = spd::stdout_logger_mt("some_unique_name");

This will create a console logger, register it in spdlog's global registry with "some_unique_name" as its id, and return it as shared_ptr.

This logger can later be accessed from anywhere using spdlog::get("some_unique_name");

Note: spdlog::get method is slow, cause internally it's locking mutex for safe iteration through registered loggers, and does significantly impact performance. Better save somewhere shared_ptrspdlog::logger and use it directly for logging in specific logger.

Create rotating file logger

//Create rotating file multithreaded logger
 auto file_logger = spd::rotating_logger_mt("file_logger", "logs/mylogfile", 1048576 * 5, 3);
..
..
auto same_logger= spdlog::get("file_logger);

Creating asynchronous loggers

Call the spdlog::set_async_mode(size_T queue_size) to tell spdlog to create async loggers. The "queue_size" param indicates the number of pre-allocated slots in the message queue and must be power of two

//Create asynchronous, rotating file multi threaded logger
spdlog::set_async_mode(1048576);
auto file_logger = spd::rotating_logger_mt("file_logger", "logs/mylogfile", 1048576 * 5, 3);

Creating loggers manually

auto sink = std::make_shared<spdlog::sinks::stdout_sink_mt>();
auto my_logger= std::make_shared<spdlog::logger>("mylogger", sink);

Please note that manually created loggers(i.e. were not created using the spdlog.h factory methods) do not get registered. If you want to register such logger use the register_logger(..) function.

Example:

spdlog::register_logger(my_logger);
...
auto the_same_logger = spdlog::get("mylogger");

Creating loggers with multiple sinks

std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(std::make_shared<spdlog::sinks::stdout_sink_st>());
sinks.push_back(std::make_shared<spdlog::sinks::daily_file_sink_st>("logfile", "txt", 23, 59));
auto combined_logger = std::make_shared<spdlog::logger>("name", begin(sinks), end(sinks));
//register it if you need to access it globaly
spdlog::register_logger(combine_logger);