CBM_LOG_LEVEL support — distilled from #414 (closes #413, thanks @santanusinha). */
| 53 | |
| 54 | /* CBM_LOG_LEVEL support — distilled from #414 (closes #413, thanks @santanusinha). */ |
| 55 | void cbm_log_init_from_env(void) { |
| 56 | /* getenv() is safe here: this runs at startup before any thread is created, |
| 57 | * so there is no concurrent setenv() to race against. */ |
| 58 | const char *raw = getenv("CBM_LOG_LEVEL"); |
| 59 | if (raw && raw[0] != '\0') { |
| 60 | /* Textual form, case-insensitive. Index of each name == its enum value. */ |
| 61 | static const char *const names[] = {"debug", "info", "warn", "error", "none"}; |
| 62 | char lower[8]; |
| 63 | size_t i = 0; |
| 64 | for (; i < sizeof(lower) - 1 && raw[i] != '\0'; i++) { |
| 65 | lower[i] = (char)tolower((unsigned char)raw[i]); |
| 66 | } |
| 67 | lower[i] = '\0'; |
| 68 | if (raw[i] == '\0') { /* fully consumed — candidate textual match */ |
| 69 | for (size_t lvl = 0; lvl < sizeof(names) / sizeof(names[0]); lvl++) { |
| 70 | if (strcmp(lower, names[lvl]) == 0) { |
| 71 | cbm_log_set_level((CBMLogLevel)lvl); |
| 72 | goto parse_format; |
| 73 | } |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | /* Numeric form: 0=debug .. 4=none, matching CBMLogLevel. */ |
| 78 | char *end = NULL; |
| 79 | long n = strtol(raw, &end, CBM_DECIMAL_BASE); |
| 80 | if (end != raw && *end == '\0' && n >= CBM_LOG_DEBUG && n <= CBM_LOG_NONE) { |
| 81 | cbm_log_set_level((CBMLogLevel)n); |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /* Unrecognised value: leave the level unchanged (fail-open). */ |
| 86 | |
| 87 | parse_format:; |
| 88 | const char *fmt = getenv("CBM_LOG_FORMAT"); |
| 89 | if (fmt && fmt[0] != '\0') { |
| 90 | char lower_fmt[8]; |
| 91 | size_t i = 0; |
| 92 | for (; i < sizeof(lower_fmt) - 1 && fmt[i] != '\0'; i++) { |
| 93 | lower_fmt[i] = (char)tolower((unsigned char)fmt[i]); |
| 94 | } |
| 95 | lower_fmt[i] = '\0'; |
| 96 | if (fmt[i] == '\0' && strcmp(lower_fmt, "json") == 0) { |
| 97 | cbm_log_set_format(CBM_LOG_FORMAT_JSON); |
| 98 | } else if (fmt[i] == '\0' && strcmp(lower_fmt, "text") == 0) { |
| 99 | cbm_log_set_format(CBM_LOG_FORMAT_TEXT); |
| 100 | } |
| 101 | return; |
| 102 | } |
| 103 | |
| 104 | /* Format is intentionally explicit-only. Logs stay local to stderr and the |
| 105 | * optional in-process sink; deployment environment variables must not |
| 106 | * silently change the operator-selected output shape. */ |
| 107 | } |
| 108 | |
| 109 | void cbm_log_set_sink(cbm_log_sink_fn fn) { |
| 110 | cbm_log_set_sink_ex(fn, CBM_LOG_SINK_REPLACE); |
no test coverage detected