logger.c (2570B)
1 /* Copyright (C) 2013-2023, 2025 Vincent Forest (vaplv@free.fr) 2 * 3 * The RSys library is free software: you can redistribute it and/or modify 4 * it under the terms of the GNU General Public License as published 5 * by the Free Software Foundation, either version 3 of the License, or 6 * (at your option) any later version. 7 * 8 * The RSys library is distributed in the hope that it will be useful, 9 * but WITHOUT ANY WARRANTY; without even the implied warranty of 10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 * GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License 14 * along with the RSys library. If not, see <http://www.gnu.org/licenses/>. */ 15 16 #define _POSIX_C_SOURCE 200112L /* vsnprintf support */ 17 #include "logger.h" 18 19 res_T 20 logger_print 21 (struct logger* logger, const enum log_type type, const char* log, ...) 22 { 23 va_list vargs_list; 24 res_T res; 25 ASSERT(logger && log && (unsigned)type < LOG_TYPES_COUNT__); 26 va_start(vargs_list, log); 27 res = logger_vprint(logger, type, log, vargs_list); 28 va_end(vargs_list); 29 return res; 30 } 31 32 res_T 33 logger_vprint 34 (struct logger* logger, 35 const enum log_type type, 36 const char* log, 37 va_list vargs_list) 38 { 39 va_list vargs_list_cp; 40 int sz; 41 ASSERT(logger && log && (unsigned)type < LOG_TYPES_COUNT__); 42 43 if(logger == LOGGER_DEFAULT) { 44 FILE* stream = type == LOG_OUTPUT ? stdout : stderr; 45 vfprintf(stream, log, vargs_list); 46 fflush(stream); 47 return RES_OK; 48 } 49 50 if(!logger_has_stream(logger, type)) 51 return RES_OK; 52 53 mutex_lock(logger->mutex); 54 55 VA_COPY(vargs_list_cp, vargs_list); 56 sz = vsnprintf 57 (darray_char_data_get(&logger->buffer), 58 darray_char_size_get(&logger->buffer), 59 log, vargs_list_cp); 60 va_end(vargs_list_cp); 61 ASSERT(sz > 0); 62 63 /* If there is not sufficient space in the logger buffer, resize it */ 64 if((size_t)sz >= darray_char_size_get(&logger->buffer)) { 65 res_T res = darray_char_resize(&logger->buffer, (size_t)sz+1/*+1<=>'\0'*/); 66 if(res != RES_OK) { 67 mutex_unlock(logger->mutex); 68 return res; 69 } 70 71 VA_COPY(vargs_list_cp, vargs_list); 72 sz = vsnprintf 73 (darray_char_data_get(&logger->buffer), 74 darray_char_size_get(&logger->buffer), 75 log, vargs_list); 76 va_end(vargs_list_cp); 77 ASSERT((size_t)sz < darray_char_size_get(&logger->buffer)); 78 } 79 mutex_unlock(logger->mutex); 80 /* Print the formatted string */ 81 logger->streams[type].writer 82 (darray_char_cdata_get(&logger->buffer), logger->streams[type].ctx); 83 return RES_OK; 84 }