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

Some short guidance for adding sinks on the fly #3014

Closed
damienhocking opened this issue Feb 16, 2024 · 7 comments
Closed

Some short guidance for adding sinks on the fly #3014

damienhocking opened this issue Feb 16, 2024 · 7 comments

Comments

@damienhocking
Copy link

damienhocking commented Feb 16, 2024

We had a need to add a callback sink to our logs so we can reprocess log messages to different formats (json and MQTT) while keeping the original logging. I discovered a small gotcha. To add a sink, be careful how you access sinks() in the logger. This doesn't work:

auto sinks = log_->sinks();
sinks.push_back(std::make_shared<spdlog::sinks::callback_sink<std::mutex> >([this](const spdlog::details::log_msg& msg) {this->LogCallback(msg);}));

"auto sinks = ..." gives you a copy of the sinks vector. You're not modifying the sinks vector in the logger. You need to use auto& (or the original sink_ptr type defined in common.h, but it needs to be a reference to the vector):

auto& sinks = log_->sinks();
sinks.push_back( .....etc

Hopefully this saves someone else an hour of head-scratching.

@tt4g
Copy link
Contributor

tt4g commented Feb 16, 2024

Wiki has a definition of spdlog::logger::sinks() and notes: https://github.com/gabime/spdlog/wiki/4.-Sinks#adding-sinks-to-the-logger-after-creation

And you can also use dist_sink: https://github.com/gabime/spdlog/wiki/4.-Sinks

@damienhocking
Copy link
Author

Yes. That wasn't my point though. It's the compiler gotcha with auto, you get a vector copy, which isn't the actual sink vector in the logger.

@tt4g
Copy link
Contributor

tt4g commented Feb 16, 2024

That is a C++ specification and spdlog cannot do anything about it.

@damienhocking
Copy link
Author

OK. All I was trying to do was offer a suggestion for users who might need to add a sink and could get bitten by just using auto. It's not a spdlog bug, or a compiler bug, it's the C++ standard as you say.

@tt4g
Copy link
Contributor

tt4g commented Feb 17, 2024

I misunderstood that you wanted to provide a workaround since it was not a discussion. My apologies.
Thank you for your contribution.

Since closed issues will no longer be viewed, I encourage you to edit the wiki and share your findings.

@damienhocking
Copy link
Author

From now on I'll add things like this to the wiki (which is done). I'll close this.

@tt4g
Copy link
Contributor

tt4g commented Feb 20, 2024

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants