c++spdlog

Extend spdlog for custom type


Is there a way to extend spdlog to support a custom struct as an item when formatting using {}?

So when I have a

struct p {
    int x;
    int y;
    int z;
};

p my_p;

I want to do

spdlog::info("p = {}", my_p);
// after registering some kind of formatter object for {p}

instead of

spdlog::info("p = (x={}, y={}, z={})", my_p.x, my_p.y, my_p.z);

Solution

  • #include "spdlog/spdlog.h"
    #include "spdlog/fmt/ostr.h" // must be included
    
    class some_class {};
    std::ostream& operator<<(std::ostream& os, const some_class& c)
    { 
      return os << "some_class"; 
    }
    

    see https://github.com/gabime/spdlog/wiki/1.-QuickStart#log-user-defined-objects