| 1 |
|
| 2 |
#include <stdio.h> |
| 3 |
#include <string.h> // strlen |
| 4 |
#include <stdarg.h> |
| 5 |
#include "utillog.h" |
| 6 |
|
| 7 |
#define LOGGER_BUFFER_SIZE 256 |
| 8 |
#define LOGGER_PREFIX_SIZE 32 |
| 9 |
|
| 10 |
typedef struct { |
| 11 |
logger_function callback; |
| 12 |
void *context; |
| 13 |
size_t pfxlen; |
| 14 |
} logger_struct; |
| 15 |
|
| 16 |
static logger_struct logger = { 0, NULL, 0 }; |
| 17 |
|
| 18 |
static char logger_buffer[LOGGER_BUFFER_SIZE+LOGGER_PREFIX_SIZE]; |
| 19 |
|
| 20 |
void loggerf (const char *format, ...) |
| 21 |
{ |
| 22 |
va_list args; |
| 23 |
int length; |
| 24 |
|
| 25 |
va_start(args, format); |
| 26 |
length = vsnprintf(logger_buffer + logger.pfxlen, LOGGER_BUFFER_SIZE, format, args); |
| 27 |
if (length > 0) |
| 28 |
{ |
| 29 |
if (length > LOGGER_BUFFER_SIZE) |
| 30 |
length = LOGGER_BUFFER_SIZE; |
| 31 |
} |
| 32 |
else |
| 33 |
{ |
| 34 |
loggerf("logger encoding error '%s'", format); |
| 35 |
length = (int)strlen(logger_buffer); |
| 36 |
} |
| 37 |
length += (int)logger.pfxlen; |
| 38 |
if (logger.callback) |
| 39 |
logger.callback(logger_buffer, logger.context); |
| 40 |
else |
| 41 |
printf("\n%s\n", logger_buffer); |
| 42 |
va_end(args); |
| 43 |
} |
| 44 |
|
| 45 |
void logger_callback (logger_function callback, void *context) |
| 46 |
{ |
| 47 |
logger.callback = callback; |
| 48 |
logger.context = context; |
| 49 |
} |
| 50 |
|
| 51 |
int logger_prefix (const char *prefix) |
| 52 |
{ |
| 53 |
size_t pfxlen; |
| 54 |
pfxlen = strlen(prefix); |
| 55 |
if (pfxlen > LOGGER_PREFIX_SIZE) |
| 56 |
return 0; |
| 57 |
memcpy(logger_buffer, prefix, pfxlen); |
| 58 |
logger.pfxlen = pfxlen; |
| 59 |
return 1; |
| 60 |
} |