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 332 : extern void colopresso_log(colopresso_log_level_t level, const char *format, ...)
34 : {
35 332 : const char truncated[] = "... [truncated]";
36 : va_list args;
37 : int result;
38 : #if defined(__EMSCRIPTEN__) && defined(COLOPRESSO_ELECTRON_APP)
39 : int flags;
40 : #endif
41 : size_t pos;
42 : char buffer[2048];
43 :
44 332 : if (g_log_callback) {
45 182 : va_start(args, format);
46 182 : result = vsnprintf(buffer, sizeof(buffer), format, args);
47 182 : va_end(args);
48 :
49 182 : if (result >= (int)sizeof(buffer)) {
50 1 : pos = sizeof(buffer) - sizeof(truncated) - 1;
51 1 : if (pos > 0) {
52 1 : snprintf(buffer + pos, sizeof(truncated), "%s", truncated);
53 : }
54 : }
55 :
56 182 : g_log_callback(level, buffer);
57 : }
58 :
59 : #if defined(__EMSCRIPTEN__) && defined(COLOPRESSO_ELECTRON_APP)
60 : else {
61 : flags = EM_LOG_CONSOLE;
62 :
63 : if (level >= CPRES_LOG_LEVEL_ERROR) {
64 : flags |= EM_LOG_ERROR;
65 : } else if (level >= CPRES_LOG_LEVEL_WARNING) {
66 : flags |= EM_LOG_WARN;
67 : } else if (!CPRES_DEBUG) {
68 : return;
69 : }
70 :
71 : va_start(args, format);
72 : result = vsnprintf(buffer, sizeof(buffer), format, args);
73 : va_end(args);
74 :
75 : if (result >= (int)sizeof(buffer)) {
76 : pos = sizeof(buffer) - sizeof(truncated) - 1;
77 : if (pos > 0) {
78 : snprintf(buffer + pos, sizeof(truncated), "%s", truncated);
79 : }
80 : }
81 :
82 : emscripten_log(flags, "%s", buffer);
83 : }
84 : #else
85 : else if (CPRES_DEBUG && level >= CPRES_LOG_LEVEL_DEBUG) {
86 : va_start(args, format);
87 : vfprintf(stderr, format, args);
88 : va_end(args);
89 : fprintf(stderr, "\n");
90 : }
91 : #endif
92 332 : }
93 :
94 43 : extern void colopresso_log_reset(void)
95 : {
96 43 : g_log_callback = NULL;
97 43 : }
98 :
99 84 : extern void cpres_set_log_callback(colopresso_log_callback_t callback)
100 : {
101 84 : if (!callback) {
102 42 : colopresso_log_reset();
103 :
104 42 : return;
105 : }
106 :
107 42 : g_log_callback = callback;
108 : }
|