debug_log.c (1811B)
1 #include <stdlib.h> 2 #include <stdio.h> 3 #include <time.h> 4 5 #include "debug_log.h" 6 7 struct timespec _timecontainer; 8 9 int debugLogInit(debug_log_t *log, int autoflush) { 10 11 log->capacity = 0; 12 log->items = (debug_log_item_t*)malloc(sizeof(debug_log_item_t) * DEBUG_LOG_CAPACITY_CHUNK); 13 14 if (log->items == NULL) { 15 log = NULL; 16 return 1; 17 } 18 19 log->error_string_buffer = (char*)calloc(DEBUG_LOG_CAPACITY_DESCRIPTION, sizeof(char)); 20 21 if (log->error_string_buffer == NULL) { 22 log = NULL; 23 return 1; 24 } 25 26 log->capacity = DEBUG_LOG_CAPACITY_CHUNK; 27 log->count = 0; 28 clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &_timecontainer); 29 log->ns_start = _timecontainer.tv_nsec; 30 log->autoflush = autoflush != 0 ? 1 : 0; 31 32 return 0; 33 } 34 35 /** 36 * TODO Auto extend memory for log if capacity runs out 37 */ 38 39 int debugLogAdd(debug_log_t *log, char *origin, char level, char *description) { 40 if (log->count == log->capacity || log->capacity == 0) 41 return 1; 42 43 clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &_timecontainer); 44 (log->items+log->count)->ns = _timecontainer.tv_nsec; 45 (log->items+log->count)->level = level; 46 47 if (description == NULL) 48 (log->items+log->count)->description = log->error_string_buffer; 49 else 50 (log->items+log->count)->description = description; 51 52 53 if (origin == NULL) 54 (log->items+log->count)->origin = log->origin_string_buffer; 55 else 56 (log->items+log->count)->origin = origin; 57 58 59 if (log->autoflush > 0) 60 fprintf(stderr, "%s: %s\n", (log->items+log->count)->origin, (log->items+log->count)->description); 61 62 log->error_string_buffer = NULL; 63 log->origin_string_buffer = NULL; 64 65 log->count++; 66 67 return 0; 68 } 69 70 int debugLogSetDescription(debug_log_t *log, const char *d) { 71 log->error_string_buffer = d; 72 } 73 74 int debugLogSetOrigin(debug_log_t *log, const char *o) { 75 log->origin_string_buffer = o; 76 }