userver icon indicating copy to clipboard operation
userver copied to clipboard

Add the ability to create your own formatters

Open nepridumalnik opened this issue 1 year ago • 2 comments

Add a description

I suggest to add the ability to create and use your own formatters for logging not only to a custom format via a callback (for example, LOG_ADD_FORMATTER(&CustomFormatCb, "custom_formatter_name"), or in another way.

nepridumalnik avatar Dec 04 '24 09:12 nepridumalnik

Hi, logger in userver allows you to customize logging format for your own types. Have you trying a suggestion from LogHelper to declare your own logging::LogHelper& operator<<(logging::LogHelper&, const auto& T)? this one https://github.com/userver-framework/userver/blob/develop/universal/include/userver/logging/log_helper.hpp#L287

Could you please enrich your suggestion with e.g. pseudo-code and example when it could be useful for other developers?

theg4sh avatar Dec 04 '24 15:12 theg4sh

The number of log output formats in userver is limited, and LogHelper uses tskv (Stream-like tskv-formatted log message builder), as described in its documentation. I suggest using callbacks to create your own formatters. For example (pseudocode):

// Formatter function
std::string CustomFormatCb(const SomeLogStruct& log)
{
    return fmt::format(R"("{timestamp}": "{}", "level": "{}", "message": "{}")", log.timestamp, log.level, log.message);
}

Then, set it in the code:

// ...
    LOG_ADD_FORMATTER(&CustomFormatCb, "custom_formatter_name")
// ...

This will allow you to customize the log details and output format—JSON, YAML, etc.—instead of relying on tskv or other built-in userver formats. It may be useful if you need to use some kind of log aggregation system that requires a specific log format to be displayed in the user interface.

nepridumalnik avatar Dec 05 '24 05:12 nepridumalnik

Now it is possible to change log format in https://github.com/userver-framework/userver/blob/develop/core/include/userver/logging/component.hpp#L67. If it is not enough and you really want custom formats registration, please re-create new issue.

segoon avatar Aug 17 '25 14:08 segoon