summaryrefslogtreecommitdiff
path: root/compat/win32/syslog.c
blob: 0af18d88825915dec4d3a8c3cd1cfe3e6ad36a0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include "../../git-compat-util.h"
 
static HANDLE ms_eventlog;
 
void openlog(const char *ident, int logopt, int facility)
{
	if (ms_eventlog)
		return;
 
	ms_eventlog = RegisterEventSourceA(NULL, ident);
 
	if (!ms_eventlog)
		warning("RegisterEventSource() failed: %lu", GetLastError());
}
 
void syslog(int priority, const char *fmt, ...)
{
	WORD logtype;
	char *str, *pos;
	int str_len;
	va_list ap;
 
	if (!ms_eventlog)
		return;
 
	va_start(ap, fmt);
	str_len = vsnprintf(NULL, 0, fmt, ap);
	va_end(ap);
 
	if (str_len < 0) {
		warning_errno("vsnprintf failed");
		return;
	}
 
	str = malloc(st_add(str_len, 1));
	if (!str) {
		warning_errno("malloc failed");
		return;
	}
 
	va_start(ap, fmt);
	vsnprintf(str, str_len + 1, fmt, ap);
	va_end(ap);
 
	while ((pos = strstr(str, "%1")) != NULL) {
		size_t offset = pos - str;
		char *new_pos;
		char *oldstr = str;
		str = realloc(str, st_add(++str_len, 1));
		if (!str) {
			free(oldstr);
			warning_errno("realloc failed");
			return;
		}
		new_pos = str + offset;
		memmove(new_pos + 2, new_pos + 1, strlen(new_pos));
		new_pos[1] = ' ';
	}
 
	switch (priority) {
	case LOG_EMERG:
	case LOG_ALERT:
	case LOG_CRIT:
	case LOG_ERR:
		logtype = EVENTLOG_ERROR_TYPE;
		break;
 
	case LOG_WARNING:
		logtype = EVENTLOG_WARNING_TYPE;
		break;
 
	case LOG_NOTICE:
	case LOG_INFO:
	case LOG_DEBUG:
	default:
		logtype = EVENTLOG_INFORMATION_TYPE;
		break;
	}
 
	ReportEventA(ms_eventlog, logtype, 0, 0, NULL, 1, 0,
	    (const char **)&str, NULL);
	free(str);
}