log: add LOG_ERRNO()

Works like LOG_ERR(), but appends a string representation of the
current errno value to the log message string.
This commit is contained in:
Daniel Eklöf 2018-12-19 21:01:01 +01:00
parent 8897e480c5
commit 7f2c0681a7
2 changed files with 22 additions and 2 deletions

20
log.c
View file

@ -2,11 +2,13 @@
#include <stdio.h> #include <stdio.h>
#include <stdarg.h> #include <stdarg.h>
#include <string.h>
#include <stdbool.h> #include <stdbool.h>
#include <errno.h>
static void static void
_log(enum log_class log_class, const char *module, const char *file, int lineno, _log(enum log_class log_class, const char *module, const char *file, int lineno,
const char *fmt, va_list va) const char *fmt, int sys_errno, va_list va)
{ {
bool colorize = true; bool colorize = true;
@ -35,6 +37,10 @@ _log(enum log_class log_class, const char *module, const char *file, int lineno,
//printf("%%s\n", buf); //printf("%%s\n", buf);
vprintf(fmt, va); vprintf(fmt, va);
if (sys_errno != 0)
printf(": %s", strerror(sys_errno));
printf("\n"); printf("\n");
} }
@ -44,6 +50,16 @@ log_msg(enum log_class log_class, const char *module,
{ {
va_list ap; va_list ap;
va_start(ap, fmt); va_start(ap, fmt);
_log(log_class, module, file, lineno, fmt, ap); _log(log_class, module, file, lineno, fmt, 0, ap);
va_end(ap);
}
void log_errno(enum log_class log_class, const char *module,
const char *file, int lineno,
const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
_log(log_class, module, file, lineno, fmt, errno, ap);
va_end(ap); va_end(ap);
} }

4
log.h
View file

@ -5,11 +5,15 @@ enum log_class { LOG_CLASS_ERROR, LOG_CLASS_WARNING, LOG_CLASS_INFO, LOG_CLASS_D
void log_msg(enum log_class log_class, const char *module, void log_msg(enum log_class log_class, const char *module,
const char *file, int lineno, const char *file, int lineno,
const char *fmt, ...) __attribute__((format (printf, 5, 6))); const char *fmt, ...) __attribute__((format (printf, 5, 6)));
void log_errno(enum log_class log_class, const char *module,
const char *file, int lineno, const char *file, int lineno,
const char *fmt, ...) __attribute__((format (printf, 5, 6))); const char *fmt, ...) __attribute__((format (printf, 5, 6)));
#define LOG_ERR(fmt, ...) \ #define LOG_ERR(fmt, ...) \
log_msg(LOG_CLASS_ERROR, LOG_MODULE, __FILE__, __LINE__, fmt, ## __VA_ARGS__) log_msg(LOG_CLASS_ERROR, LOG_MODULE, __FILE__, __LINE__, fmt, ## __VA_ARGS__)
#define LOG_ERRNO(fmt, ...) \
log_errno(LOG_CLASS_ERROR, LOG_MODULE, __FILE__, __LINE__, fmt, ## __VA_ARGS__)
#define LOG_WARN(fmt, ...) \ #define LOG_WARN(fmt, ...) \
log_msg(LOG_CLASS_WARNING, LOG_MODULE, __FILE__, __LINE__, fmt, ## __VA_ARGS__) log_msg(LOG_CLASS_WARNING, LOG_MODULE, __FILE__, __LINE__, fmt, ## __VA_ARGS__)
#define LOG_INFO(fmt, ...) \ #define LOG_INFO(fmt, ...) \