diff --git a/alog.c b/alog.c index 4e9f7ae..bd603b2 100644 --- a/alog.c +++ b/alog.c @@ -24,6 +24,7 @@ #include #define TEST_ALOG_STATE() if (!ALOG_LOGGING_STATE) { _init_alog(); } +#define MAX_TIMESTAMP 30 struct _global_logging_state *ALOG_LOGGING_STATE; int _alog_num_out_fds; @@ -48,6 +49,10 @@ void _init_alog() { _alog_err_fds[0] = 2; } +void init_alog() { + TEST_ALOG_STATE(); +} + // TODO: should I dont close stdin and stdout? void deinit_alog() { TEST_ALOG_STATE(); @@ -161,21 +166,31 @@ void alog ( // TODO: try to get this all into 1 call to sprintf time_t t = time(NULL); struct tm * p = localtime(&t); - char *timestamp = malloc(strftime(NULL, 0, "[%c]", p) + 1); - strftime(timestamp, sizeof(timestamp), "[%c]", p); - char *msg_and_timestamp = malloc(sizeof(timestamp) + 1 + (strlen(message) + 1) + 2); + int timestamp_len = strftime(NULL, MAX_TIMESTAMP, "[%c]", p) + 1; + char *timestamp = calloc(timestamp_len , sizeof(char)); + strftime(timestamp, timestamp_len+1, "[%c]", p); + + size = (timestamp_len + strlen(message) + 1); + char *msg_and_timestamp = calloc(size, sizeof(char)); sprintf(msg_and_timestamp, "%s %s\n", timestamp, message); free(timestamp); + // TODO: Why even use msg_and_timestamp if I am going to write it wholesale into buffer? - size = snprintf(NULL, 0, msg_and_timestamp, fmt_list); + size = vsnprintf(NULL, 0, msg_and_timestamp, fmt_list); + va_start(fmt_list, message); + va_end(fmt_list); buffer = malloc(size + 1); - sprintf(buffer, msg_and_timestamp, fmt_list); + vsprintf(buffer, msg_and_timestamp, fmt_list); + va_end(fmt_list); free(msg_and_timestamp); + // if severity is PRINT we avoid timestamp } else { - size = snprintf(NULL, 0, message, fmt_list); + size = vsnprintf(NULL, 0, message, fmt_list); + va_start(fmt_list, message); buffer = malloc(size + 1); - sprintf(buffer, message, fmt_list); + vsprintf(buffer, message, fmt_list); + va_end(fmt_list); } for (int i = 0; i < _alog_num_out_fds; i++) { @@ -198,7 +213,6 @@ void alog ( } free(buffer); - va_end(fmt_list); } #ifdef ALOG_HIJACK_PRINTF diff --git a/alog.h b/alog.h index 30d3093..ef2deb9 100644 --- a/alog.h +++ b/alog.h @@ -65,6 +65,7 @@ typedef enum { * err fds: stderr */ void _init_alog(); +void init_alog(); /* deinitializes all global state memory used in this library */ void deinit_alog();