fix timestamp and printing

Signed-off-by: Aidan Hahn <aidan@aidanis.online>
This commit is contained in:
Aidan Hahn 2022-07-29 12:57:54 -07:00
parent 7ff43f0346
commit eeaa710f68
No known key found for this signature in database
GPG key ID: 18D8AD0591CA303E
2 changed files with 23 additions and 8 deletions

30
alog.c
View file

@ -24,6 +24,7 @@
#include <time.h>
#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