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