aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/log.c
diff options
context:
space:
mode:
authorEgor Tensin <Egor.Tensin@gmail.com>2023-06-28 22:41:51 +0200
committerEgor Tensin <Egor.Tensin@gmail.com>2023-06-28 22:57:48 +0200
commitf409cddcf9bb7f2684776902b38eaeddadede7ca (patch)
tree8d1a5295c6987563dc2bf6db400c7f770da933ba /src/log.c
parenttest: skip ci.sh w/ Valgrind (diff)
downloadcimple-f409cddcf9bb7f2684776902b38eaeddadede7ca.tar.gz
cimple-f409cddcf9bb7f2684776902b38eaeddadede7ca.zip
log: support logging levels
Diffstat (limited to 'src/log.c')
-rw-r--r--src/log.c53
1 files changed, 53 insertions, 0 deletions
diff --git a/src/log.c b/src/log.c
new file mode 100644
index 0000000..3886a1a
--- /dev/null
+++ b/src/log.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2023 Egor Tensin <Egor.Tensin@gmail.com>
+ * This file is part of the "cimple" project.
+ * For details, see https://github.com/egor-tensin/cimple.
+ * Distributed under the MIT License.
+ */
+
+#include "log.h"
+
+#include <stdio.h>
+#include <sys/time.h>
+#include <time.h>
+#include <unistd.h>
+
+int g_log_lvl = LOG_LVL_INFO;
+
+static inline void log_prefix_timestamp(FILE *dest)
+{
+ struct timeval tv;
+ struct tm tm;
+ char buf[64];
+ size_t used = 0;
+
+ if (gettimeofday(&tv, NULL) < 0)
+ return;
+ if (!gmtime_r(&tv.tv_sec, &tm))
+ return;
+
+ buf[0] = '\0';
+ used += strftime(buf + used, sizeof(buf) - used, "%F %T", &tm);
+ used += snprintf(buf + used, sizeof(buf) - used, ".%03ld | ", tv.tv_usec / 1000);
+ fprintf(dest, "%s", buf);
+}
+
+static inline void log_prefix_thread_id(FILE *dest)
+{
+ fprintf(dest, "%d | ", gettid());
+}
+
+int log_entry_start(int lvl, FILE *dest)
+{
+ if (lvl < g_log_lvl)
+ return 0;
+ flockfile(dest);
+ log_prefix_timestamp(dest);
+ log_prefix_thread_id(dest);
+ return 1;
+}
+
+void log_entry_end(FILE *dest)
+{
+ funlockfile(dest);
+}