aboutsummaryrefslogtreecommitdiff
path: root/src/lgr.c
blob: 4fa87219b6acb0ac6ec6d120ecbe9c8ef1750048 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// lgr.c --- logger                                                    -*- C -*-
//
// Copyright (c) 2026 Martin Michalec <martin@michalec.dev>
//
// 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 <unistd.h>
#endif // LGR_NO_UNISTD

#include <stdarg.h>

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