printf-style formatting of logs message part
Is it possible to change message formatter to use one which supports printf-style formatting (i.e %d) ? And if so, is there some sample code on how to do this?
can you give a concrete example ?
Well, I was just curious if it was possible to change the default Python/C# style formatter ("My cats name is {}", "Carl") to printf style ("My cats name is %s", "Carl"). I can't find where the hook to fmt is made.
I would like this too. I have a large pre-existing codebase where I want to change the logging library, but all the current log messages assume printf-style formatting. It appears that fmtlib even supports the printf-style syntax, one would only have to go and change where spdlog invokes the formatting APIs (I assume - I have not yet looked).
http://fmtlib.net/latest/api.html#printf-formatting-functions
EDIT:
Don't have time to test it tonight, but I took a quick poke around and it looks like this is the relevant spot: https://github.com/gabime/spdlog/blob/3afabcd17e65b05d6b418a08584279e0c67d12fc/include/spdlog/details/logger_impl.h#L69
pull request about this is welcome
It's not so easy. I don't see any fmt::BasicWriter support for this.
:+1:
This feature would make my life easier too! :+1:
Want to switch from my own simple logger into spdlog, but put it on hold because of this. +1
But...we can workaround it by compose the full log via printf with our own approach, and then adapt to spdlog by always printing full string.
I was interesting in printf style formatting to. I have played around with a extra version of the fmt lib. I found the following:
fmt has got the header "printf.h" that supports printf style formatting. There are the functions sprintf, fprintf and printf. The difference between this functions and the standard printf functions is that they want to get the variable parameter list as a object of the type "ArgList". Maybe this could be helpfull.
For the DLL I build I found this not very helpfull. I ended up providing two Ways: for the old code I just use oldstyle printf to a buffer before invoking spdlog logging. For the new code I have created a log builder object that takes its parameters over a streaming style interface.
I found that there is no easy conversation between the oldstyle printf parameter list and the functionality of "printf.h" - at least if you want/need a C style dll export interface. It is not possible to parse a oldstyle VARARG parameter list without the information about the parameter types that are bound to the format string. And this is a very oldstyle unsafe approach, so I think it's the best to use old style printf functions before logging for old code, and the safe fmt way of formating for new code.
Supporting printf() style formatting would be useful to me also
I'm using a following workaround:
std::string format(const char *fmt, ...) {
const size_t buf_size = 100000;
char buf[buf_size];
va_list ap;
va_start (ap, fmt);
size_t real_size = vsnprintf(buf, buf_size, fmt, ap);
va_end (ap);
return std::string(buf, std::min(real_size, buf_size));
}
#define SPDLOG_STR_H(x) #x
#define SPDLOG_STR_HELPER(x) SPDLOG_STR_H(x)
#define LOG_INFO(...) spdlog::get("root")->info("[" + string(__FUNCTION__) + ":" + SPDLOG_STR_HELPER(__LINE__) + "] " + __VA_ARGS__)
#define LOGF_INFO(fstr, ...) LOG_INFO(format(fstr, __VA_ARGS__))
So now I can log like below:
LOGF_INFO("unknown path: %s", url_path.c_str());
I also need this. My workaround was similar to rayrapetyan's. It works.
performance might suffer with this wrapper - each call creates a std::string (which typically allocates on the heap afaik). Also, this will be executed even if the log level is below threshold (so the message would be thrown anyway).
That was one of my concerns for sure. In my case we are porting code that uses printf style formatting so changing these to {} wasn't really an option. My code is slightly different:
if (spdlog::get(LOGGER_REGISTRY_STRING)->level() <= logging_level) {
// We are OK to log this
va_start(arg_list_p, format_p);
bool formatting_error = false;
try {
if (vsnprintf(log_message, sizeof(log_message), format_p, arg_list_p) < 0)
{
log_message[LOG_TEXT_BUFFER_SIZE-1] = 0;// output string exceeded buffer size, force a terminating null
}
} catch (...) {
formatting_error = true;
}
va_end(arg_list_p);
if (!formatting_error) {
file_logger->log(logging_level, log_message);
file_logger->flush();
}
}
Sorry I cannot get the code formatting to work properly here....
It is better but the call to spdlog::get(loggername) is bit costy since a mutex is involved. Better keep a local reference to the logger instead of calling get() every time.
Very good suggestion, thank you!
@batduder You can use three back ticks to enclose your code like this ```
Everyone: I'm curious - why not just use sed or something to replace %s (and friends) with {} instead of these acrobatics?
sed -i 's/%s/{}/g' *.cpp
sed -i 's/%d/{}/g' *.cpp
sed -i 's/%f/{}/g' *.cpp
There will be edge cases like 0x%x and float format strings that will need special care.
OK so like Slack. I have repaired my comment above. The 'code' button above (<>) only adds 1 tick.
A good suggestion on sed and we will consider that. My issue though is that we didn't want to tweak the existing code too much and there is a lot more than just %s being used. We'd have to be pretty careful "sed'ing" thousands of log statements. But your suggestion is a good one.
This is what I've temporarily settled on.
#define LOG_SETUP(func, fmt, ...) \
do {\
char buf__[512]; \
snprintf(buf__, sizeof(buf__), fmt, ##__VA_ARGS__); \
func(buf__); \
} while(0)
#define LOGINFO(fmt,...) LOG_SETUP(console->info, fmt, ##__VA_ARGS__)
#define LOGDEBUG(fmt,...) LOG_SETUP(console->debug, fmt, ##__VA_ARGS__)
<etc>
where console is a globally defined logger.
Does anyone see any issues with this?