spdlog icon indicating copy to clipboard operation
spdlog copied to clipboard

How do I log a std::iostream?

Open coyorkdow opened this issue 1 year ago • 2 comments

I have a pointer of std::iostream, the object it points to might be std::stringstream, std::fstream, or anything inherit the base type. What is the most efficient and elegant way to extract its content and print it via spdlog?

I can do the following.

 std::shared_ptr<std::iostream> content_stream = result.value()->getContent();
 std::stringstream ss;
 ss << content_stream->rdbuf();
 spdlog::info("object content is\n{}", ss.str());

Is there any better way? I don't think my current approach either efficient or elegant...

coyorkdow avatar Jul 25 '24 07:07 coyorkdow

The logging argument format uses fmt library, so spdlog does not support methods not supported by fmt.

tt4g avatar Jul 25 '24 12:07 tt4g

An elegant way would be to define custom type that accepts std::iostream, using https://fmt.dev/latest/api/#formatting-user-defined-types

And then one can just pass the stream to spdlog:

spdlog::info("Stream content is: {}", content_stream);

gabime avatar Jul 25 '24 12:07 gabime