Nilorea Library
C utilities for networking, threading, graphics
Loading...
Searching...
No Matches
n_log.c
Go to the documentation of this file.
1/*
2 * Nilorea Library
3 * Copyright (C) 2005-2026 Castagnier Mickael
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14 * implied. See the License for the specific language governing
15 * permissions and limitations under the License.
16 *
17 * SPDX-License-Identifier: Apache-2.0
18 */
19
27#include "nilorea/n_common.h"
28#include "nilorea/n_log.h"
29
30#include <pthread.h>
31#include <string.h>
32#include <inttypes.h>
33#include <sys/types.h>
34#include <sys/stat.h>
35#include <fcntl.h>
36
37#ifndef __windows__
38#include <syslog.h>
39#else
40#include <time.h>
41#include "nilorea/n_windows.h"
42#endif
43
45
46#define COLOR_RESET "\033[0m"
47#define COLOR_RED "\033[31m"
48#define COLOR_GREEN "\033[32m"
49#define COLOR_YELLOW "\033[33m"
50#define COLOR_BLUE "\033[34m"
51#define COLOR_MAGENTA "\033[35m"
52#define COLOR_CYAN "\033[36m"
53#define COLOR_WHITE "\033[37m"
54
56typedef struct LOG_LEVELS {
58 char* c_name;
59 int c_val; // cppcheck-suppress unusedStructMember ; used by downstream log consumers
60 char* w_name; // cppcheck-suppress unusedStructMember ; used by downstream log consumers
61
63
66 {
67 {"EMERG", LOG_EMERG, "ERROR"},
68 {"ALERT", LOG_ALERT, "ERROR"},
69 {"CRITICAL", LOG_CRIT, "ERROR"},
70 {"ERR", LOG_ERR, "ERROR"},
71 {"WARNING", LOG_WARNING, "WARNING"},
72 {"NOTICE", LOG_NOTICE, "SUCCESS"},
73 {"INFO", LOG_INFO, "INFORMATION"},
74 {"DEBUG", LOG_DEBUG, "INFORMATION"},
75 {NULL, -1, NULL}};
76
78static int LOG_LEVEL = LOG_NULL;
79
81static int LOG_TYPE = LOG_STDERR;
82
84static FILE* log_file = NULL;
85
87static char* proc_name = NULL;
88
94char* open_sysjrnl(const char* identity) {
95 __n_assert(identity, return NULL);
96#ifndef __windows__
97 /* LOG_CONS: log to console if no syslog available
98 * LOG_PID: add pid of calling process to log
99 * Local use 7 : compat with older logging systems
100 */
101 openlog(identity, LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL7);
102#endif
103 proc_name = strdup(identity);
104 return proc_name;
105} /* open_sysjrnl */
106
110void close_sysjrnl(void) {
111#ifndef __windows__
112 closelog();
113#endif
115} /* close_sysjrnl */
116
121void set_log_level(const int log_level) {
122 if (log_level == LOG_FILE) {
124 return;
125 }
126 if (log_level == LOG_STDERR) {
128 return;
129 }
130 if (log_level == LOG_SYSJRNL) {
132 return;
133 }
135#ifdef __windows__
136 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
137 if (hOut != INVALID_HANDLE_VALUE) {
138 DWORD dwMode = 0;
139 if (GetConsoleMode(hOut, &dwMode)) {
140 dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
141 if (SetConsoleMode(hOut, dwMode)) {
142 // color support is enabled
144 }
145 }
146 }
147#else
148 // Probably a terminal, may support colors
149 if (isatty(fileno(stdout))) {
151 }
152#endif
153} /* set_log_level() */
154
159int get_log_level(void) {
160 return LOG_LEVEL;
161} /* get_log_level() */
162
168int set_log_file(char* file) {
169 __n_assert(file, return FALSE);
170
171 if (log_file) {
172 fclose(log_file);
173 log_file = NULL;
174 }
175
176 int fd = open(file, O_CREAT | O_APPEND | O_WRONLY, 0600); // rw------- permissions
177 if (fd == -1) {
178 n_log(LOG_ERR, "couldn't create %s with 0600 permission", _str(file));
179 return FALSE;
180 }
181
182 log_file = fdopen(fd, "a");
183 if (!log_file) {
184 close(fd);
185 n_log(LOG_ERR, "fdopen returned an invalid file descriptor pointer for %s:%d", _str(file), fd);
186 return FALSE;
187 }
188
190
191 return TRUE;
192} /* set_log_file */
193
198FILE* get_log_file(void) {
199 return log_file;
200} /*get_log_level() */
201
202#ifndef _vscprintf
209int _vscprintf_so(const char* format, va_list pargs) {
210 int retval;
211 va_list argcopy;
212 va_copy(argcopy, pargs);
213 retval = vsnprintf(NULL, 0, format, argcopy);
214 va_end(argcopy);
215 return retval;
216}
217#endif
218
219#ifndef vasprintf
227int vasprintf(char** strp, const char* fmt, va_list ap) {
228 long long int len = _vscprintf_so(fmt, ap);
229 if (len == -1)
230 return -1;
231 char* str = NULL;
232 Malloc(str, char, (size_t)len + 1 + sizeof(void*)); // len + EndOfString + padding
233 if (!str)
234 return -1;
235 int r = vsnprintf(str, (size_t)(len + 1), fmt, ap); /* "secure" version of vsprintf */
236 if (r == -1)
237 return free(str), -1;
238 *strp = str;
239 return r;
240}
241#endif
242
243#ifndef asprintf
251int asprintf(char* strp[], const char* fmt, ...) {
252 va_list ap;
253 va_start(ap, fmt);
254 int r = vasprintf(strp, fmt, ap);
255 va_end(ap);
256 return r;
257}
258#endif
259
268void _n_log(int level, const char* file, const char* func, int line, const char* format, ...) {
269 FILE* out = NULL;
270
271 if (level == LOG_NULL)
272 return;
273
274 if (!log_file)
275 out = stderr;
276 else
277 out = log_file;
278
279 int log_level = get_log_level();
280
281 if (level <= log_level) {
282 va_list args;
283 char* syslogbuffer = NULL;
284 char* eventbuffer = NULL;
285 char* syslogsafebuffer = NULL;
286#ifdef __windows__
287 size_t needed = 0;
288 const char* name = "NULL";
289 if (proc_name)
290 name = proc_name;
291#endif
292
293 const char* color = "";
294 const char* color_reset = "";
295
297 color_reset = COLOR_RESET;
298 switch (level) {
299 case LOG_EMERG:
300 color = COLOR_RED;
301 break;
302 case LOG_ALERT:
303 color = COLOR_MAGENTA;
304 break;
305 case LOG_CRIT:
306 color = COLOR_RED;
307 break;
308 case LOG_ERR:
309 color = COLOR_RED;
310 break;
311 case LOG_WARNING:
312 color = COLOR_YELLOW;
313 break;
314 case LOG_NOTICE:
315 color = COLOR_GREEN;
316 break;
317 case LOG_INFO:
318 color = COLOR_CYAN;
319 break;
320 case LOG_DEBUG:
321 color = COLOR_BLUE;
322 break;
323 default:
324 color = COLOR_WHITE;
325 break;
326 }
327 }
328 switch (LOG_TYPE) {
329 case LOG_SYSJRNL:
330 va_start(args, format);
331 if (vasprintf(&syslogbuffer, format, args) == -1) {
332 syslogbuffer = NULL;
333 }
334 va_end(args);
335 // Fallback if vasprintf is NULL */
336 syslogsafebuffer = syslogbuffer ? syslogbuffer : "<log: vasprintf failed>";
337#ifdef __windows__
338 /* Sanitize syslog content to prevent command injection via system().
339 * Only mutate when syslogbuffer is non-NULL: syslogsafebuffer then
340 * points to heap memory. When syslogbuffer is NULL it points to a
341 * read-only string literal and must not be written to. */
342 if (syslogbuffer) {
343 for (char* p = syslogsafebuffer; *p; p++) {
344 if (*p == '"' || *p == '&' || *p == '|' || *p == '<' || *p == '>' || *p == '^') *p = '_';
345 }
346 }
347 int snprintf_ret = snprintf(NULL, 0, "start /B EventCreate /t %s /id 666 /l APPLICATION /so %s /d \"%s\" > NUL 2>&1", prioritynames[level].w_name, name, syslogsafebuffer);
348 if (snprintf_ret > 0) {
349 needed = (unsigned long long)snprintf_ret;
350 Malloc(eventbuffer, char, needed + 4);
351 if (eventbuffer) {
352 snprintf(eventbuffer, needed + 4, "start /B EventCreate /t %s /id 666 /l APPLICATION /so %s /d \"%s\" > NUL 2>&1", prioritynames[level].w_name, name, syslogsafebuffer);
353 system(eventbuffer);
354 }
355 }
356#else
357 syslog(level, "%s->%s:%d %s", _str(file), _str(func), line, syslogsafebuffer);
358#endif
359 FreeNoLog(syslogbuffer);
360 FreeNoLog(eventbuffer);
361 break;
362 default:
363 fprintf(out, "%s%s:%jd:%s->%s:%d ", color, prioritynames[level].c_name, (intmax_t)time(NULL), _str(file), _str(func), line);
364 if (format) {
365 va_start(args, format);
366 vfprintf(out, format, args);
367 va_end(args);
368 }
369 fprintf(out, "%s\n", color_reset);
370 break;
371 }
372 fflush(out);
373 }
374} /* _n_log( ... ) */
375
383int open_safe_logging(TS_LOG** log, char* pathname, char* opt) {
384 if (!log) {
385 n_log(LOG_ERR, "Invalid log pointer (NULL)");
386 return FALSE;
387 }
388
389 if (*log) {
390 if ((*log)->file) {
391 n_log(LOG_ERR, "Log file '%s' already open", _str(pathname));
392 return -1000; // already open
393 }
394 n_log(LOG_ERR, "Log struct already allocated without file");
395 return FALSE;
396 }
397
398 if (!pathname || !opt) {
399 n_log(LOG_ERR, "Invalid pathname or mode (pathname=%s, opt=%s)", _str(pathname), _str(opt));
400 return FALSE;
401 }
402
403 Malloc((*log), TS_LOG, 1);
404 if (!(*log)) {
405 n_log(LOG_ERR, "Failed to allocate TS_LOG structure");
406 return FALSE;
407 }
408
409 pthread_mutex_init(&(*log)->LOG_MUTEX, NULL);
410
411 int flags = 0;
412 if (strcmp(opt, "a") == 0 || strcmp(opt, "a+") == 0) {
413 flags = O_CREAT | O_APPEND | O_WRONLY;
414 } else if (strcmp(opt, "w") == 0 || strcmp(opt, "w+") == 0) {
415 flags = O_CREAT | O_TRUNC | O_WRONLY;
416 } else {
417 n_log(LOG_ERR, "Unsupported open mode '%s' for pathname '%s'", _str(opt), _str(pathname));
418 pthread_mutex_destroy(&(*log)->LOG_MUTEX);
419 Free(*log);
420 *log = NULL;
421 return FALSE;
422 }
423
424 int fd = open(pathname, flags, 0600);
425 if (fd == -1) {
426 n_log(LOG_ERR, "Failed to open '%s' with 0600 permissions", _str(pathname));
427 pthread_mutex_destroy(&(*log)->LOG_MUTEX);
428 Free(*log);
429 *log = NULL;
430 return FALSE;
431 }
432
433 (*log)->file = fdopen(fd, opt);
434 if (!(*log)->file) {
435 n_log(LOG_ERR, "fdopen failed for '%s' (fd=%d, mode='%s')", _str(pathname), fd, _str(opt));
436 close(fd);
437 pthread_mutex_destroy(&(*log)->LOG_MUTEX);
438 Free(*log);
439 *log = NULL;
440 return FALSE;
441 }
442
443 return TRUE;
444} /* open_safe_logging */
445
452int write_safe_log(TS_LOG* log, char* pat, ...) {
453 /* argument list */
454 va_list arg;
455 char str[2048] = "";
456
457 if (!log)
458 return FALSE;
459
460 va_start(arg, pat);
461
462 vsnprintf(str, sizeof(str), pat, arg);
463
464 va_end(arg);
465
466 pthread_mutex_lock(&log->LOG_MUTEX);
467 fprintf(log->file, "%s", str);
468 fflush(log->file);
469 pthread_mutex_unlock(&log->LOG_MUTEX);
470
471 return TRUE;
472
473} /* write_safe_log( ... ) */
474
481 if (!log)
482 return FALSE;
483
484 pthread_mutex_lock(&log->LOG_MUTEX);
485 fflush(log->file);
486 pthread_mutex_unlock(&log->LOG_MUTEX);
487
488 pthread_mutex_destroy(&log->LOG_MUTEX);
489
490 fclose(log->file);
491
492 Free(log);
493
494 return TRUE;
495
496} /* close_safe_logging( ...) */
int log_level
Definition ex_fluid.c:60
#define FreeNoLog(__ptr)
Free Handler without log.
Definition n_common.h:272
#define Malloc(__ptr, __struct, __size)
Malloc Handler to get errors and set to 0.
Definition n_common.h:204
#define __n_assert(__ptr, __ret)
macro to assert things
Definition n_common.h:279
#define _str(__PTR)
define true
Definition n_common.h:193
#define Free(__ptr)
Free Handler to get errors.
Definition n_common.h:263
pthread_mutex_t LOG_MUTEX
mutex for thread-safe writting
Definition n_log.h:97
FILE * file
File handler.
Definition n_log.h:99
#define LOG_ALERT
action must be taken immediately
Definition n_log.h:72
#define LOG_SYSJRNL
to sysjrnl
Definition n_log.h:52
FILE * get_log_file(void)
return the current log_file
Definition n_log.c:198
int write_safe_log(TS_LOG *log, char *pat,...)
write to a thread-safe logging file
Definition n_log.c:452
int open_safe_logging(TS_LOG **log, char *pathname, char *opt)
Open a thread-safe logging file.
Definition n_log.c:383
#define LOG_EMERG
system is unusable
Definition n_log.h:70
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
Definition n_log.h:89
#define LOG_FILE
internal, logging to file
Definition n_log.h:48
void close_sysjrnl(void)
Close syslog connection or clean internals for event log.
Definition n_log.c:110
#define LOG_DEBUG
debug-level messages
Definition n_log.h:84
#define LOG_ERR
error conditions
Definition n_log.h:76
char * open_sysjrnl(const char *identity)
Open connection to syslog or create internals for event log.
Definition n_log.c:94
#define LOG_STDERR
internal, default LOG_TYPE
Definition n_log.h:50
#define LOG_CRIT
critical conditions
Definition n_log.h:74
int close_safe_logging(TS_LOG *log)
close a thread-safe logging file
Definition n_log.c:480
int set_log_file(char *file)
Set the logging to a file instead of stderr.
Definition n_log.c:168
void set_log_level(const int log_level)
Set the global log level value ( static int LOG_LEVEL )
Definition n_log.c:121
#define LOG_NOTICE
normal but significant condition
Definition n_log.h:80
#define LOG_WARNING
warning conditions
Definition n_log.h:78
#define LOG_NULL
no log output
Definition n_log.h:46
#define LOG_INFO
informational
Definition n_log.h:82
void _n_log(int level, const char *file, const char *func, int line, const char *format,...)
Logging function.
Definition n_log.c:268
int get_log_level(void)
Get the global log level value.
Definition n_log.c:159
ThreadSafe LOGging structure.
Definition n_log.h:95
Common headers and low-level functions & define.
#define COLOR_RESET
Definition n_log.c:46
static LOG_LEVELS prioritynames[]
array of log levels
Definition n_log.c:65
#define COLOR_BLUE
Definition n_log.c:50
static char * proc_name
static proc name, for windows event log
Definition n_log.c:87
int c_val
Definition n_log.c:59
static int LOG_LEVEL
static global maximum wanted log level value
Definition n_log.c:78
#define COLOR_YELLOW
Definition n_log.c:49
static int LOG_TYPE
static global logging type ( STDERR, FILE, SYSJRNL )
Definition n_log.c:81
int vasprintf(char **strp, const char *fmt, va_list ap)
snprintf from a va_list, helper for asprintf
Definition n_log.c:227
int asprintf(char *strp[], const char *fmt,...)
snprintf from a va_list
Definition n_log.c:251
static int terminal_support_colors
Definition n_log.c:44
#define COLOR_CYAN
Definition n_log.c:52
#define COLOR_MAGENTA
Definition n_log.c:51
#define COLOR_WHITE
Definition n_log.c:53
static FILE * log_file
static FILE handling if logging to file is enabled
Definition n_log.c:84
char * w_name
Definition n_log.c:60
char * c_name
string of log type
Definition n_log.c:58
#define COLOR_RED
Definition n_log.c:47
#define COLOR_GREEN
Definition n_log.c:48
int _vscprintf_so(const char *format, va_list pargs)
compute the size of a string made with format 'fmt' and arguments in the va_list 'ap',...
Definition n_log.c:209
internal struct to handle log types
Definition n_log.c:56
Generic log system.