[3] | 1 | /* $Id: log.c 62 2024-09-18 20:02:26Z nishi $ */
|
---|
| 2 |
|
---|
| 3 | #include "cm_log.h"
|
---|
| 4 |
|
---|
| 5 | #include "cm_string.h"
|
---|
| 6 |
|
---|
[62] | 7 | #include <time.h>
|
---|
[3] | 8 | #include <stdio.h>
|
---|
| 9 | #include <stdbool.h>
|
---|
| 10 | #include <string.h>
|
---|
| 11 | #include <stdlib.h>
|
---|
| 12 | #include <stdarg.h>
|
---|
| 13 |
|
---|
[62] | 14 | FILE* logfile;
|
---|
| 15 |
|
---|
[3] | 16 | bool cm_do_log = false;
|
---|
| 17 |
|
---|
| 18 | #define LOGNAME_LENGTH 12
|
---|
| 19 |
|
---|
[62] | 20 | void cm_force_log(const char* log) {
|
---|
| 21 | time_t t = time(NULL);
|
---|
| 22 | struct tm* tm = localtime(&t);
|
---|
| 23 | char date[513];
|
---|
| 24 | strftime(date, 512, "%a %b %d %H:%M:%S %Z %Y", tm);
|
---|
| 25 | fprintf(logfile, "[%s] %s\n", date, log);
|
---|
| 26 | fflush(logfile);
|
---|
| 27 | }
|
---|
| 28 |
|
---|
[3] | 29 | void cm_log(const char* name, const char* log, ...) {
|
---|
| 30 | if(!cm_do_log) return;
|
---|
| 31 | va_list args;
|
---|
| 32 | va_start(args, log);
|
---|
| 33 | char namebuf[LOGNAME_LENGTH + 1];
|
---|
| 34 | memset(namebuf, '.', LOGNAME_LENGTH);
|
---|
| 35 | namebuf[LOGNAME_LENGTH] = 0;
|
---|
| 36 | int i;
|
---|
| 37 | for(i = 0; name[i] != 0 && i < LOGNAME_LENGTH; i++) {
|
---|
| 38 | namebuf[i] = name[i];
|
---|
| 39 | }
|
---|
| 40 |
|
---|
| 41 | char* result = malloc(1);
|
---|
| 42 | result[0] = 0;
|
---|
| 43 |
|
---|
| 44 | char cbuf[2];
|
---|
| 45 | cbuf[1] = 0;
|
---|
| 46 |
|
---|
| 47 | for(i = 0; log[i] != 0; i++) {
|
---|
| 48 | if(log[i] == '%') {
|
---|
| 49 | i++;
|
---|
| 50 | if(log[i] == 's') {
|
---|
| 51 | char* tmp = result;
|
---|
[12] | 52 | char* c = va_arg(args, char*);
|
---|
| 53 | result = cm_strcat(tmp, c == NULL ? "(null)" : c);
|
---|
[3] | 54 | free(tmp);
|
---|
[6] | 55 | } else if(log[i] == 'd') {
|
---|
| 56 | int a = va_arg(args, int);
|
---|
| 57 | char buf[128];
|
---|
| 58 | sprintf(buf, "%d", a);
|
---|
| 59 | char* tmp = result;
|
---|
| 60 | result = cm_strcat(tmp, buf);
|
---|
| 61 | free(tmp);
|
---|
[3] | 62 | }
|
---|
| 63 | } else {
|
---|
| 64 | cbuf[0] = log[i];
|
---|
| 65 | char* tmp = result;
|
---|
| 66 | result = cm_strcat(tmp, cbuf);
|
---|
| 67 | free(tmp);
|
---|
| 68 | }
|
---|
| 69 | }
|
---|
| 70 |
|
---|
[62] | 71 | fprintf(logfile, "%s %s\n", namebuf, result);
|
---|
[3] | 72 | va_end(args);
|
---|
| 73 |
|
---|
| 74 | free(result);
|
---|
| 75 | }
|
---|