| 1 | // | ||
| 2 | // Created by Denys Fisher on 25.08.2025. | ||
| 3 | // | ||
| 4 | |||
| 5 | #ifndef LOG_H | ||
| 6 | #define LOG_H | ||
| 7 | #include <time.h> | ||
| 8 | #include <inttypes.h> | ||
| 9 | #include <stdio.h> | ||
| 10 | #include <stdlib.h> | ||
| 11 | #include <string.h> | ||
| 12 | #include <pthread.h> | ||
| 13 | |||
| 14 | static int _log_err_enabled = 0; | ||
| 15 | static pthread_once_t _log_err_once = PTHREAD_ONCE_INIT; | ||
| 16 | |||
| 17 | 0 | static void _log_err_init(void) { | |
| 18 | 0 | _log_err_enabled = getenv("SHARED_SIMPLE_DEBUG") != NULL; | |
| 19 | 0 | } | |
| 20 | |||
| 21 | #define LOG_ERR(fmt, ...) \ | ||
| 22 | do { \ | ||
| 23 | pthread_once(&_log_err_once, _log_err_init); \ | ||
| 24 | if (_log_err_enabled) \ | ||
| 25 | fprintf(stderr, "[ERR] %s:%d: " fmt "\n", \ | ||
| 26 | __FILE__, __LINE__, ##__VA_ARGS__); \ | ||
| 27 | } while(0) | ||
| 28 | |||
| 29 | 0 | static uint64_t __current_time_micros() { | |
| 30 | struct timespec ts; | ||
| 31 | 0 | clock_gettime(CLOCK_MONOTONIC, &ts); | |
| 32 | 0 | return (uint64_t) ts.tv_sec * 1000000 + ts.tv_nsec / 1000; | |
| 33 | } | ||
| 34 | extern uint64_t p_time; | ||
| 35 | |||
| 36 | #define LOG_INIT() \ | ||
| 37 | do { \ | ||
| 38 | p_time = __current_time_micros(); \ | ||
| 39 | } while(0) | ||
| 40 | |||
| 41 | #define LOG(fstr, ...) \ | ||
| 42 | do { \ | ||
| 43 | pid_t pid = getpid(); \ | ||
| 44 | uint64_t c_time = __current_time_micros() - p_time; \ | ||
| 45 | if (pid % 2 == 0) { \ | ||
| 46 | fprintf(stderr, "\t%" PRIu64 " - [%d] " fstr, c_time, pid, ##__VA_ARGS__); \ | ||
| 47 | } \ | ||
| 48 | else { \ | ||
| 49 | fprintf(stderr, "%" PRIu64 " - [%d] " fstr, c_time, pid, ##__VA_ARGS__); \ | ||
| 50 | } \ | ||
| 51 | } while(0) | ||
| 52 | |||
| 53 | #endif //LOG_H |