From 43a56680a6c5bc52165dbd9bb7609cbf02be1ea2 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Fri, 6 Nov 2026 05:48:49 +0300 Subject: feat(lgr): add logger --- src/lgr.c | 119 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 src/lgr.c (limited to 'src') diff --git a/src/lgr.c b/src/lgr.c new file mode 100644 index 0000000..4fa8721 --- /dev/null +++ b/src/lgr.c @@ -0,0 +1,119 @@ +// lgr.c --- logger -*- C -*- +// +// Copyright (c) 2026 Martin Michalec +// +// SPDX-License-Identifier: MIT +// +// This file is part of COSMOS Codebase. +// +// Commentary: +// +// Code: + +#include "lgr.h" +#include "dbg.h" +#include "arena.h" +#include "sb.h" + +#ifndef LGR_NO_UNISTD +#include +#endif // LGR_NO_UNISTD + +#include + +void +_lgr_log (struct lgr lgr, enum lgr_lvl lvl, const char *fmt, ...) +{ + if (lgr._ctx && lvl > lgr._ctx->max_lvl) return; + + va_list ap; + + if (lgr._fun == NULL) { + #ifndef LGR_NO_FEAT_CTX + if (_lgr_ctx_top) { + lgr = _lgr_ctx_top->lgr; + } else + #endif // LGR_NO_FEAT_CTX + #ifndef LGR_NO_FEAT_STDIO + if (1) { + va_start (ap, fmt); + vfprintf (stderr, fmt, ap); + va_end (ap); + return; + } else + #endif // LGR_NO_FEAT_STDIO + return; + } + + // HOLD(cmmm): redo directly with arena support... + struct sb sb = { .hdr.gpa = GPA_SCR }; + va_start (ap, fmt); + sb_vprintf (&sb, fmt, ap); + va_end (ap); + + lgr._fun (lgr._ctx, lvl, ms_mv (sb_ms (sb))); + DA_DROP (&sb); +} + +#ifndef LGR_NO_FEAT_DECORATORS + +#endif // LGR_NO_FEAT_DECORATORS + +#ifndef LGR_NO_FEAT_FD + +void +lgr_fd_fun (struct lgr_hdr *ctx, enum lgr_lvl lvl, struct mv mv) +{ + UNUSED (ctx); + UNUSED (lvl); + UNUSED (mv); + DBG_TODO ("implement"); +} + +#endif // LGR_NO_FEAT_FD + +#ifndef LGR_NO_FEAT_STRM + +void +lgr_strm_fun (struct lgr_hdr *_ctx, enum lgr_lvl lvl, struct mv mv) +{ + struct lgr_strm *ctx = (void *) _ctx; + fwrite (mv.beg, mv_sz (mv), 1, ctx->strm); +} + +#endif // LGR_NO_FEAT_STRM + +#ifndef LGR_NO_FEAT_CTX + +THREAD_LOCAL struct lgr_ctx_frame *_lgr_ctx_top = NULL; + +struct lgr_ctx_frame * +lgr_ctx_beg (struct lgr lgr) +{ + struct lgr_ctx_frame *new = SCR_GRAB_T (*new); + new->lgr = lgr; + new->next = _lgr_ctx_top; + _lgr_ctx_top = new; + return new; +} + +struct lgr +lgr_ctx_end (void) +{ + struct lgr lgr = _lgr_ctx_top->lgr; + _lgr_ctx_top = _lgr_ctx_top->next; + return lgr; +} + +void +lgr_ctx_rollback (struct lgr_ctx_frame *to) +{ + while (_lgr_ctx_top != to) { + DBG_ASSERT_NN (_lgr_ctx_top); + _lgr_ctx_top = _lgr_ctx_top->next; + } +} + +#endif // LGR_NO_FEAT_CTX + +// lgr.c ends here -- cgit v1.3.1