quill
Static Public Member Functions | List of all members
DirectFormatCodec< T > Struct Template Reference

Provides codec functionality for serializing complex user-defined types into strings. More...

#include <DirectFormatCodec.h>

Inheritance diagram for DirectFormatCodec< T >:
Inheritance graph
[legend]

Static Public Member Functions

static size_t compute_encoded_size (quill::detail::SizeCacheVector &conditional_arg_size_cache, T const &arg)
 
static void encode (std::byte *&buffer, quill::detail::SizeCacheVector const &conditional_arg_size_cache, uint32_t &conditional_arg_size_cache_index, T const &arg)
 
static std::string_view decode_arg (std::byte *&buffer)
 
static void decode_and_store_arg (std::byte *&buffer, quill::DynamicFormatArgStore *args_store)
 

Detailed Description

template<typename T>
struct DirectFormatCodec< T >

Provides codec functionality for serializing complex user-defined types into strings.

This codec is particularly useful for logging user-defined types, it converts an object into a string representation using the fmt::formatteron the hot path.

When using this codec, a fmt::formatter specialization must exist for the user-defined type.

It eliminates the need to explicitly write more verbose code, such as:

LOG_INFO(l, "{}", fmtquill::format("{}", obj));

Instead, you can directly write:

LOG_INFO(logger, "{}", obj);
class User
{
public:
User(std::string name, std::string surname, uint32_t age)
: name(std::move(name)), surname(std::move(surname)), age(age)
{
favorite_colors.push_back("red");
favorite_colors.push_back("blue");
favorite_colors.push_back("green");
};
std::string name;
std::string surname;
uint32_t age;
std::vector<std::string> favorite_colors;
};
template <>
struct fmtquill::formatter<User>
{
constexpr auto parse(format_parse_context& ctx) { return ctx.begin(); }
auto format(::User const& user, format_context& ctx) const
{
return fmtquill::format_to(ctx.out(), "Name: {}, Surname: {}, Age: {}, Favorite Colors: {}",
user.name, user.surname, user.age, user.favorite_colors);
}
};
template <>
struct quill::Codec<User> : quill::DirectFormatCodec<User>
{
};
int main()
{
// ... init code
User user_1{"Super", "User", 1};
LOG_INFO(logger, "User is [{}]", user_1);
}
Note
The user-provided fmtquill::formatter<T> must be a pure function of arg: its output must depend only on the argument and produce the same byte count every time it is invoked on the same value. This is required because the formatter runs twice on the frontend: once in compute_encoded_size() to determine the buffer size, and again in encode() to write the bytes. The same property allows the codec to be used with view types (e.g. fmtquill::join_view) — for views we additionally construct a temporary T{arg} each time, since fmt disallows formatting view types as lvalues.

The documentation for this struct was generated from the following file: