From c5ebd345fdfb51c53d3bd57b51759265aaa4580a Mon Sep 17 00:00:00 2001 From: Peter Hutterer Date: Thu, 2 Mar 2023 14:10:53 +1000 Subject: [PATCH] tools: copy the default log handler to the eis demo server The default log handler logs to stderr, but we want stdout here to have it intermixed with our real log messages (easier to debug this way). Would probably be better to have this somewhere shared but for now this will do. --- tools/eis-demo-server.c | 48 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/tools/eis-demo-server.c b/tools/eis-demo-server.c index f6bebd1..a5e337a 100644 --- a/tools/eis-demo-server.c +++ b/tools/eis-demo-server.c @@ -70,6 +70,50 @@ static void sighandler(int signal) { static OBJECT_IMPLEMENT_UNREF_CLEANUP(eis_demo_client); +static void +log_handler(struct eis *eis, enum eis_log_priority priority, + const char *message, struct eis_log_context *ctx) +{ + struct lut { + const char *color; + const char *prefix; + } lut[] = { + { .color = ansi_colorcode[RED], .prefix = "", }, /* debug starts at 10 */ + { .color = ansi_colorcode[HIGHLIGHT], .prefix = "DEBUG", }, + { .color = ansi_colorcode[GREEN], .prefix = "INFO", }, + { .color = ansi_colorcode[BLUE], .prefix = "WARN", }, + { .color = ansi_colorcode[RED], .prefix = "ERROR", }, + }; + static time_t last_time = 0; + const char *reset_code = ansi_colorcode[RESET]; + + run_only_once { + if (!isatty(STDOUT_FILENO)) { + struct lut *l; + ARRAY_FOR_EACH(lut, l) + l->color = ""; + reset_code = ""; + } + } + + time_t now = time(NULL); + char timestamp[64]; + + if (last_time != now) { + struct tm *tm = localtime(&now); + strftime(timestamp, sizeof(timestamp), "%T", tm); + } else { + xsnprintf(timestamp, sizeof(timestamp), "..."); + } + + size_t idx = priority/10; + assert(idx < ARRAY_LENGTH(lut)); + fprintf(stdout, " EIS: %8s | %s%4s%s | %s\n", timestamp, + lut[idx].color, lut[idx].prefix, reset_code, message); + + last_time = now; +} + static void eis_demo_client_destroy(struct eis_demo_client *democlient) { @@ -540,8 +584,10 @@ int main(int argc, char **argv) _unref_(eis) *eis = eis_new(NULL); assert(eis); - if (verbose) + if (verbose) { eis_log_set_priority(eis, EIS_LOG_PRIORITY_DEBUG); + eis_log_set_handler(eis, log_handler); + } signal(SIGINT, sighandler);