main: client: factor out some common code for "--log-level" option

This commit is contained in:
Craig Barnes 2021-02-11 11:08:18 +00:00
parent 7698077331
commit 5437321f97
5 changed files with 61 additions and 58 deletions

40
log.c
View file

@ -10,11 +10,22 @@
#include <unistd.h>
#include "debug.h"
#include "util.h"
#include "xsnprintf.h"
static bool colorize = false;
static bool do_syslog = true;
static enum log_class log_level = LOG_CLASS_INFO;
static const char log_level_map[][8] = {
[LOG_CLASS_ERROR] = "error",
[LOG_CLASS_WARNING] = "warning",
[LOG_CLASS_INFO] = "info",
#if defined(_DEBUG)
[LOG_CLASS_DEBUG] = "debug",
#endif
};
void
log_init(enum log_colorize _colorize, bool _do_syslog,
enum log_facility syslog_facility, enum log_class _log_level)
@ -149,3 +160,32 @@ void log_errno_provided(enum log_class log_class, const char *module,
va_end(ap1);
va_end(ap2);
}
int
log_level_from_string(const char *str)
{
if (unlikely(str[0] == '\0'))
return -1;
for (int i = 0, n = ALEN(log_level_map); i < n; i++)
if (strcmp(str, log_level_map[i]) == 0)
return i;
return -1;
}
const char *
log_level_string_hint(void)
{
static char buf[64];
if (buf[0] != '\0')
return buf;
for (size_t i = 0, pos = 0, n = ALEN(log_level_map); i < n; i++) {
const char *entry = log_level_map[i];
const char *delim = (i + 1 < n) ? ", " : "";
pos += xsnprintf(buf + pos, sizeof(buf) - pos, "'%s'%s", entry, delim);
}
return buf;
}