Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example how to replace default logger. #2194

Merged
merged 1 commit into from
Nov 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,20 @@ void file_events_example()
}
```

---
#### Replace the Default Logger
```c++
void replace_default_logger_example()
{
auto new_logger = spdlog::basic_logger_mt("new_default_logger", "logs/new-default-log.txt", true);
spdlog::set_default_logger(new_logger);
spdlog::set_level(spdlog::level::info);
spdlog::debug("This message should not be displayed!");
spdlog::set_level(spdlog::level::trace);
spdlog::debug("This message should be displayed..");
}
```

---
## Benchmarks

Expand Down
18 changes: 18 additions & 0 deletions example/example.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ void syslog_example();
void udp_example();
void custom_flags_example();
void file_events_example();
void replace_default_logger_example();

#include "spdlog/spdlog.h"
#include "spdlog/cfg/env.h" // support for loading levels from the environment variable
Expand Down Expand Up @@ -80,6 +81,7 @@ int main(int, char *[])
udp_example();
custom_flags_example();
file_events_example();
replace_default_logger_example();

// Flush all *registered* loggers using a worker thread every 3 seconds.
// note: registered loggers *must* be thread safe for this to work correctly!
Expand Down Expand Up @@ -326,3 +328,19 @@ void file_events_example()
spdlog::logger my_logger("some_logger", file_sink);
my_logger.info("Some log line");
}

void replace_default_logger_example()
{
// store the old logger so we don't break other examples.
auto old_logger = spdlog::default_logger();

auto new_logger = spdlog::basic_logger_mt("new_default_logger", "logs/new-default-log.txt", true);
spdlog::set_default_logger(new_logger);
spdlog::set_level(spdlog::level::info);
spdlog::debug("This message should not be displayed!");
spdlog::set_level(spdlog::level::trace);
spdlog::debug("This message should be displayed..");

spdlog::set_default_logger(old_logger);
}