0

I want to use spdlog for my code's logging. In my code, there is a important variable for the step in simulation, and I want it to be always displayed in my logs. Here is the format I wants.

[log_level][the_special_variable][logger_name] messages

So how could format the logger? Or there isn't any way to do that?

Edited: Sorry I am not good at asking a question in English.

I've read the Readme.md in spdlog's github, and i saw this

// Log patterns can contain custom flags.
// the following example will add new flag '%*' - which will be bound to a <my_formatter_flag> instance.
#include "spdlog/pattern_formatter.h"
class my_formatter_flag : public spdlog::custom_flag_formatter
{
public:
    void format(const spdlog::details::log_msg &, const std::tm &, spdlog::memory_buf_t &dest) override
    {
        std::string some_txt = "custom-flag";
        dest.append(some_txt.data(), some_txt.data() + some_txt.size());
    }

    std::unique_ptr<custom_flag_formatter> clone() const override
    {
        return spdlog::details::make_unique<my_formatter_flag>();
    }
};

void custom_flags_example()
{    
    auto formatter = std::make_unique<spdlog::pattern_formatter>();
    formatter->add_flag<my_formatter_flag>('*').set_pattern("[%n] [%*] [%^%l%$] %v");
    spdlog::set_formatter(std::move(formatter));
}

but I can't understand the usage of it. It seems like it can only add a string for the custom flag. I would like to kwon if it is OK to display a int variable.

Aaron Wu
  • 1
  • 4
  • Hey, welcome to SO! We like to help out with questions and problems that you can't just look up elsewhere. Have you looked at the spdlog docs on custom flags and have questions about that? Have you tried something and are wondering why it's not working? – Wutz Jul 16 '22 at 10:00

1 Answers1

0

Yes, it is okay to add an int to the log message, you just have to stringify it. For example, in the format method:

auto str = std::to_string(my_special_int_variable);
dest.append(...);

The only question is how you make your int var available in the formatter. The example above assumes it's a global variable.

Wutz
  • 2,246
  • 13
  • 15
  • thanks. Since the variable I want to use is Global, it works. But I also wanna know if it is possible with local variables too. – Aaron Wu Jul 16 '22 at 13:45