Line data Source code
1 : /*
2 : * SPDX-License-Identifier: GPL-3.0-or-later
3 : *
4 : * This file is part of colopresso
5 : *
6 : * Copyright (C) 2025-2026 COLOPL, Inc.
7 : *
8 : * Author: Go Kudo <g-kudo@colopl.co.jp>
9 : * Developed with AI (LLM) code assistance. See `NOTICE` for details.
10 : */
11 :
12 : #include <stdarg.h>
13 : #include <stdio.h>
14 :
15 : #include <colopresso.h>
16 :
17 : #include "internal/log.h"
18 :
19 : #if defined(__EMSCRIPTEN__) && defined(COLOPRESSO_ELECTRON_APP)
20 : #include <emscripten/emscripten.h>
21 : #endif
22 :
23 : #ifndef CPRES_DEBUG
24 : #ifdef DEBUG
25 : #define CPRES_DEBUG 1
26 : #else
27 : #define CPRES_DEBUG 0
28 : #endif
29 : #endif
30 :
31 : static colopresso_log_callback_t g_log_callback = NULL;
32 :
33 298 : void colopresso_log(colopresso_log_level_t level, const char *format, ...) {
34 298 : const char truncated[] = "... [truncated]";
35 : char buffer[2048];
36 : int result;
37 : va_list args;
38 : size_t pos;
39 :
40 298 : if (g_log_callback) {
41 182 : va_start(args, format);
42 182 : result = vsnprintf(buffer, sizeof(buffer), format, args);
43 182 : va_end(args);
44 :
45 182 : if (result >= (int)sizeof(buffer)) {
46 1 : pos = sizeof(buffer) - sizeof(truncated) - 1;
47 1 : if (pos > 0) {
48 1 : snprintf(buffer + pos, sizeof(truncated), "%s", truncated);
49 : }
50 : }
51 :
52 182 : g_log_callback(level, buffer);
53 : }
54 :
55 : #if defined(__EMSCRIPTEN__) && defined(COLOPRESSO_ELECTRON_APP) && level >= CPRES_LOG_LEVEL_DEBUG
56 : else {
57 : int flags = EM_LOG_CONSOLE;
58 :
59 : if (level >= CPRES_LOG_LEVEL_ERROR) {
60 : flags |= EM_LOG_ERROR;
61 : } else if (level >= CPRES_LOG_LEVEL_WARNING) {
62 : flags |= EM_LOG_WARN;
63 : } else if (!CPRES_DEBUG) {
64 : return;
65 : }
66 :
67 : va_start(args, format);
68 : result = vsnprintf(buffer, sizeof(buffer), format, args);
69 : va_end(args);
70 :
71 : if (result >= (int)sizeof(buffer)) {
72 : pos = sizeof(buffer) - sizeof(truncated) - 1;
73 : if (pos > 0) {
74 : snprintf(buffer + pos, sizeof(truncated), "%s", truncated);
75 : }
76 : }
77 :
78 : emscripten_log(flags, "%s", buffer);
79 : }
80 : #else
81 : else if (CPRES_DEBUG && level >= CPRES_LOG_LEVEL_DEBUG) {
82 : va_start(args, format);
83 : vfprintf(stderr, format, args);
84 : va_end(args);
85 : fprintf(stderr, "\n");
86 : }
87 : #endif
88 298 : }
89 :
90 43 : void colopresso_log_reset(void) { g_log_callback = NULL; }
91 :
92 84 : extern void cpres_set_log_callback(colopresso_log_callback_t callback) {
93 84 : if (!callback) {
94 42 : colopresso_log_reset();
95 42 : return;
96 : }
97 :
98 42 : g_log_callback = callback;
99 : }
|