Repository navigation
6. Asynchronous logging
To turn async mode on call spdlog::set_async_mode(q_size) //size must be power of 2
This will make spdlog to create and use async_logger objects instead of the regular ones.
Each such logger has a queue with pre allocated slots and a worker thread.
When the user logs a message to an async logger the following happen:
-
If the queuse is not full, the log message is pushed into it. Otherwise, if the queue is full (the number of messages in it reached
max_size), the call blocks until there is room again (or optionally spdlog discards the message and returns immediately to the caller - see below) -
The worker thread pops the message from the queue and logs the message using the logger's sinks.
-
If an exception happens in the worker thread (e.g. failed logging to file) an exception will be re-thrown when the user calls the next log message. This way the user can be notified on errors happening in the worker thread.
User can decide what to do when the queue is full:
- Block the call until there is more room (default behaviour)
- Discard the message and never block - by setting the
spdlog::async_overflow_policy:
spdlog::set_async_mode(q_size, spdlog::async_overflow_policy::discard_log_msg)async loggers are always thread safe. Moreover, they use lockfree queues to prevent locking even when multiple threads use the same logger simultaneously.
Sometimes the user needs to do some initialization on the newly created worker thread (for example set thread affinity or priority, attach worker thread to a JVM). Or he might wish to execute some code before thread exit (for example when detaching thread from a JVM).
To achieve this the user can provide callback functions or lambdas to the set_async_mode call:
auto warmup = []() {/* Some init code in the worker thread*/};
auto flush_interval_ms = std::chrono::milliseconds::zero();
auto teardown = []() {/* Some cleanup code in the worker thread*/};
spdlog::set_async_mode(q_size, spdlog::async_overflow_policy::block_retry, warmup, flush_interval_ms, teardown);There is a bug in VS runtime that cause the application dead lock when it exits. If you use async logging, please make sure to call spdlog::drop_all() before main() exit. If some loggers are not in the registry, those should be release manual as well. stackoverflow: std::thread join hangs if called after main exits when using vs2012 rc