Subversion Repositories Tewi

Rev

Rev 62 | Rev 191 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3 nishi 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
 
62 nishi 7
#include <time.h>
3 nishi 8
#include <stdio.h>
9
#include <stdbool.h>
10
#include <string.h>
11
#include <stdlib.h>
12
#include <stdarg.h>
13
 
182 nishi 14
#ifdef _PSP
15
#include <pspdebug.h>
16
#endif
17
 
62 nishi 18
FILE* logfile;
19
 
3 nishi 20
bool cm_do_log = false;
21
 
22
#define LOGNAME_LENGTH 12
23
 
62 nishi 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);
182 nishi 29
#ifdef _PSP
30
	pspDebugScreenPrintf("[%s] %s\n", date, log);
31
#else
62 nishi 32
	fprintf(logfile, "[%s] %s\n", date, log);
182 nishi 33
#endif
62 nishi 34
	fflush(logfile);
35
}
36
 
3 nishi 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;
12 nishi 60
				char* c = va_arg(args, char*);
61
				result = cm_strcat(tmp, c == NULL ? "(null)" : c);
3 nishi 62
				free(tmp);
6 nishi 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);
3 nishi 70
			}
71
		} else {
72
			cbuf[0] = log[i];
73
			char* tmp = result;
74
			result = cm_strcat(tmp, cbuf);
75
			free(tmp);
76
		}
77
	}
78
 
182 nishi 79
#ifdef _PSP
80
	pspDebugScreenPrintf("%s %s\n", namebuf, result);
81
#else
62 nishi 82
	fprintf(logfile, "%s %s\n", namebuf, result);
182 nishi 83
#endif
3 nishi 84
	va_end(args);
85
 
86
	free(result);
87
}