Skip to content

Instantly share code, notes, and snippets.

@eXpl0it3r
Last active June 21, 2023 23:48
Show Gist options
  • Save eXpl0it3r/507b24f9f65454916415678c8eac3830 to your computer and use it in GitHub Desktop.
Save eXpl0it3r/507b24f9f65454916415678c8eac3830 to your computer and use it in GitHub Desktop.
Redirect Stream to spdlog Logger
#include <streambuf>
#include <ostream>
#include "spdlog/spdlog.h"
template<class Element = char, class Trait = std::char_traits<Element>>
class StreamLogger : public std::basic_streambuf<Element, Trait>
{
public:
StreamLogger(std::ostream& stream, std::shared_ptr<spdlog::logger> logger)
: m_stream{ stream }, m_logger{ std::move(logger) }
{
// Redirect provided stream
m_buffer = m_stream.rdbuf(this);
};
~StreamLogger()
{
try
{
// Restore provided stream
m_stream.rdbuf(m_buffer);
}
catch(const std::ios_base::failure& exception)
{
const auto message = std::string{ "StreamLogger was unable to restore the provided stream: " };
m_logger->error(message + exception.what());
}
}
StreamLogger(const StreamLogger& other) = delete;
StreamLogger& operator=(const StreamLogger& other) = delete;
StreamLogger(StreamLogger&& other) noexcept = default;
StreamLogger& operator=(StreamLogger&& other) noexcept = default;
protected:
std::streamsize xsputn(const Element* elements, const std::streamsize count) override
{
m_string_buffer.append(elements, static_cast<std::string::size_type>(count));
return count;
}
typename Trait::int_type overflow(typename Trait::int_type final_character) override
{
m_logger->error(m_string_buffer);
m_string_buffer.clear();
return Trait::not_eof(final_character);
}
std::basic_ostream<Element, Trait>& m_stream;
std::streambuf* m_buffer;
std::basic_string<Element, Trait> m_string_buffer;
std::shared_ptr<spdlog::logger> m_logger;
};
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
MIT License
Copyright (c) 2020-2023 Lukas Dürrenberger
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
*/
@SoilRos
Copy link

SoilRos commented Jun 21, 2023

After trying some work arounds, these are are the few things that may fix things:

  • Make constructor private
  • Delete move constructor/assignment
  • Add a factory function that returns a non- discardable unique pointer
  • std::basic_streambuf<Element, Trait> didn’t want to do anything for me. I had to write everything without character and traits templates, maybe has something to do with my standard library, I still don’t understand why 🤷🏻‍♂️.
  • Add an open source license ;)

@eXpl0it3r
Copy link
Author

Make constructor private

How do you construct an instance then?

Delete move constructor/assignment

I guess that makes sense, if it's not movable anyways.

Add a factory function that returns a non- discardable unique pointer

What's a non-discardable unique pointer? 😄

std::basic_streambuf<Element, Trait> didn’t want to do anything for me

Maybe something with spdlog changed. The class is already three years old.

Add an open source license ;)

Done 🙂

@SoilRos
Copy link

SoilRos commented Jun 21, 2023

What's a non-discardable unique pointer? 😄

I mean this function signature: [[nodiscard]] std::unique_ptr<StreamLogger<…>> StreamLogger<…>::make(…). The pointer must not be discarded because there is no observable side-effects if the object is immediately discarded. This is so that people don’t forget to assign it to an object on creation.

How do you construct an instance then?

The factory function make(…) still has access to private parts for of its class, for example, the constructor.

Maybe something with spdlog changed.

No really, my tests also didn’t work with std::stringing and std::cout when I used the templated version.

@SoilRos
Copy link

SoilRos commented Jun 21, 2023

Add an open source license ;)

Done 🙂

Thank you :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment