Skip to content

Instantly share code, notes, and snippets.

@v2px
Created November 10, 2024 17:11
Show Gist options
  • Save v2px/35037bd924b32ae0b8db3534763eaa43 to your computer and use it in GitHub Desktop.
Save v2px/35037bd924b32ae0b8db3534763eaa43 to your computer and use it in GitHub Desktop.
#include <sys/errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define TIMEBUF_LEN 32 /* this should fit %c for all locales */
int
psircd_log(const char *level, const char *fname, int lineno, const char *fxname, const char *fmt, ...) {
char *log_prefix = NULL;
char *log_line = NULL;
char *log_complete = NULL;
char *timestr = NULL;
struct tm *tptr = NULL;
va_list ap;
time_t now;
int ret = -1;
va_start(ap, fmt);
now = time(NULL);
if((time_t)-1 == now)
goto cleanup; /* time(3) does not necessarily set errno */
tptr = malloc(sizeof(struct tm));
if(NULL == tptr)
goto fail;
if(NULL == gmtime_r(&now, tptr))
goto fail;
timestr = malloc(TIMEBUF_LEN*sizeof(char));
if(NULL == timestr)
goto fail;
if(0 == strftime(timestr, TIMEBUF_LEN, "%c", tptr))
{
fprintf(stderr, "Logging failed: Formatted time did not for buffer.\n");
goto cleanup;
}
ret = asprintf(&log_prefix, "[%.24s %s] %s - %s:%d, %s:",
timestr, tptr->tm_zone, level, fname, lineno, fxname);
if(-1 == ret)
goto fail;
ret = vasprintf(&log_line, fmt, ap);
if(-1 == ret)
goto fail;
ret = asprintf(&log_complete, "%s %s", log_prefix, log_line);
if(-1 == ret)
goto fail;
printf("%s", log_complete);
fail:
if(errno)
fprintf(stderr, "Logging failed: (%d) %s\n", errno, strerror(errno));
cleanup:
free(timestr);
free(log_prefix);
free(log_line);
free(log_complete);
va_end(ap);
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment