2 * os_win32/syslog_win32.cpp
4 * Home page of code is: http://smartmontools.sourceforge.net
6 * Copyright (C) 2004-8 Christian Franke <smartmontools-support@lists.sourceforge.net>
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2, or (at your option)
13 * You should have received a copy of the GNU General Public License
14 * (for example COPYING); if not, write to the Free
15 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 // Win32 Emulation of syslog() for smartd
20 // Writes to windows event log on NT4/2000/XP
21 // (Register syslogevt.exe as event message file)
22 // Writes to file "<ident>.log" on 9x/ME.
23 // If facility is set to LOG_LOCAL[0-7], log is written to
24 // file "<ident>.log", stdout, stderr, "<ident>[1-5].log".
33 #include <process.h> // getpid()
35 #define WIN32_LEAN_AND_MEAN
36 #include <windows.h> // RegisterEventSourceA(), ReportEventA(), ...
38 const char *syslog_win32_c_cvsid
= "$Id: syslog_win32.cpp,v 1.8 2008/03/04 22:09:48 ballen4705 Exp $"
43 #define snprintf _snprintf
44 #define vsnprintf _vsnprintf
47 #define ARGUSED(x) ((void)(x))
51 //MT runtime not necessary, because thread uses no unsafe lib functions
52 //#error Program must be linked with multithreaded runtime library
57 // Redirect event log to stdout for testing
59 static BOOL
Test_ReportEventA(HANDLE h
, WORD type
, WORD cat
, DWORD id
, PSID usid
,
60 WORD nstrings
, WORD datasize
, LPCTSTR
* strings
, LPVOID data
)
63 printf("%u %lu:%s", type
, id
, nstrings
!= 1?"\n":"");
64 for (i
= 0; i
< nstrings
; i
++)
65 printf(" \"%s\"\n", strings
[i
]);
70 HANDLE
Test_RegisterEventSourceA(LPCTSTR server
, LPCTSTR source
)
75 #define ReportEventA Test_ReportEventA
76 #define RegisterEventSourceA Test_RegisterEventSourceA
81 // should be identical to MSG_SYSLOG* in "syslogevt.h"
82 // (generated by "mc" from "syslogevt.mc")
83 #define MSG_SYSLOG 0x00000000L
84 #define MSG_SYSLOG_01 0x00000001L
86 #define MSG_SYSLOG_10 0x0000000AL
88 static char sl_ident
[100];
89 static char sl_logpath
[sizeof(sl_ident
) + sizeof("0.log")-1];
90 static FILE * sl_logfile
;
91 static char sl_pidstr
[16];
92 static HANDLE sl_hevtsrc
;
95 // Ring buffer for event log output via thread
99 static HANDLE evt_hthread
;
100 static char evt_lines
[MAXLINES
][LINELEN
+1];
101 static int evt_priorities
[MAXLINES
];
102 static volatile int evt_timeout
;
103 static int evt_index_in
, evt_index_out
;
104 static HANDLE evt_wait_in
, evt_wait_out
;
107 // Map syslog priority to event type
109 static WORD
pri2evtype(int priority
)
113 case LOG_EMERG
: case LOG_ALERT
:
114 case LOG_CRIT
: case LOG_ERR
:
115 return EVENTLOG_ERROR_TYPE
;
117 return EVENTLOG_WARNING_TYPE
;
118 case LOG_NOTICE
: case LOG_INFO
:
120 return EVENTLOG_INFORMATION_TYPE
;
125 // Map syslog priority to string
127 static const char * pri2text(int priority
)
130 case LOG_EMERG
: return "EMERG";
131 case LOG_ALERT
: return "ALERT";
132 case LOG_CRIT
: return "CRIT";
134 case LOG_ERR
: return "ERROR";
135 case LOG_WARNING
: return "Warn";
136 case LOG_NOTICE
: return "Note";
137 case LOG_INFO
: return "Info";
138 case LOG_DEBUG
: return "Debug";
143 // Output cnt events from ring buffer
145 static void report_events(int cnt
)
147 const char * msgs
[3+MAXLINES
];
155 pri
= evt_priorities
[evt_index_out
];
159 msgs
[2] = pri2text(pri
);
160 for (i
= 0; i
< cnt
; i
++) {
161 //assert(evt_priorities[evt_index_out] == pri);
162 msgs
[3+i
] = evt_lines
[evt_index_out
];
163 if (++evt_index_out
>= MAXLINES
)
166 ReportEventA(sl_hevtsrc
,
167 pri2evtype(pri
), // type
168 0, MSG_SYSLOG
+cnt
, // category, message id
169 NULL
, // no security id
170 (WORD
)(3+cnt
), 0, // 3+cnt strings, ...
171 msgs
, NULL
); // ... , no data
175 // Thread to combine several syslog lines into one event log entry
177 static ULONG WINAPI
event_logger_thread(LPVOID arg
)
184 // Wait for first line ...
187 if (WaitForSingleObject(evt_wait_out
, (evt_timeout
? INFINITE
: 0)) != WAIT_OBJECT_0
)
192 // ... wait some time for more lines with same prior
194 prior
= evt_priorities
[i
];
196 while (cnt
< MAXLINES
) {
198 evt_timeout
* ((1000L * (MAXLINES
-cnt
+1))/MAXLINES
);
199 if (WaitForSingleObject(evt_wait_out
, timeout
) != WAIT_OBJECT_0
)
203 if (evt_priorities
[i
] != prior
) {
210 // Output all in one event log entry
214 if (!ReleaseSemaphore(evt_wait_in
, cnt
, NULL
))
222 static void on_exit_event_logger(void)
224 // Output lines immediate if exiting
226 // Wait for thread to finish
227 WaitForSingleObject(evt_hthread
, 1000L);
228 CloseHandle(evt_hthread
);
231 DeregisterEventSource(sl_hevtsrc
); sl_hevtsrc
= 0;
234 // Leave event message source open to prevent losing messages during shutdown
239 static int start_event_logger()
243 if ( !(evt_wait_in
= CreateSemaphore(NULL
, MAXLINES
, MAXLINES
, NULL
))
244 || !(evt_wait_out
= CreateSemaphore(NULL
, 0, MAXLINES
, NULL
))) {
245 fprintf(stderr
,"CreateSemaphore failed, Error=%ld\n", GetLastError());
248 if (!(evt_hthread
= CreateThread(NULL
, 0, event_logger_thread
, NULL
, 0, &tid
))) {
249 fprintf(stderr
,"CreateThread failed, Error=%ld\n", GetLastError());
252 atexit(on_exit_event_logger
);
257 // Write lines to event log ring buffer
259 static void write_event_log(int priority
, const char * lines
)
263 for (i
= 0; lines
[i
]; i
++) {
265 while (lines
[i
+len
] && lines
[i
+len
] != '\n')
270 if (WaitForSingleObject(evt_wait_in
, INFINITE
) != WAIT_OBJECT_0
)
273 evt_priorities
[evt_index_in
] = priority
;
274 memcpy(evt_lines
[evt_index_in
], lines
+i
, (len
< LINELEN
? len
: LINELEN
));
276 evt_lines
[evt_index_in
][len
] = 0;
277 if (++evt_index_in
>= MAXLINES
)
279 // Signal avail if ring buffer full
280 if (++cnt
>= MAXLINES
) {
281 ReleaseSemaphore(evt_wait_out
, cnt
, NULL
);
292 ReleaseSemaphore(evt_wait_out
, cnt
, NULL
);
297 // Write lines to logfile
299 static void write_logfile(FILE * f
, int priority
, const char * lines
)
301 time_t now
; char stamp
[sizeof("2004-04-04 10:00:00")+13];
304 now
= time((time_t*)0);
305 if (!strftime(stamp
, sizeof(stamp
)-1, "%Y-%m-%d %H:%M:%S", localtime(&now
)))
308 for (i
= 0; lines
[i
]; i
++) {
310 while (lines
[i
+len
] && lines
[i
+len
] != '\n')
313 fprintf(f
, "%s %s[%s]: %-5s: ",
314 stamp
, sl_ident
, sl_pidstr
, pri2text(priority
));
315 fwrite(lines
+i
, len
, 1, f
);
325 void openlog(const char *ident
, int logopt
, int facility
)
328 if (sl_logpath
[0] || sl_logfile
|| sl_hevtsrc
)
329 return; // Already open
331 strncpy(sl_ident
, ident
, sizeof(sl_ident
)-1);
332 // logopt==LOG_PID assumed
335 if (snprintf(sl_pidstr
, sizeof(sl_pidstr
)-1, (pid
>= 0 ? "%d" : "0x%X"), pid
) < 0)
336 strcpy(sl_pidstr
,"?");
338 if (facility
== LOG_LOCAL0
) // "ident.log"
339 strcat(strcpy(sl_logpath
, sl_ident
), ".log");
340 else if (facility
== LOG_LOCAL1
) // stdout
342 else if (facility
== LOG_LOCAL2
) // stderr
344 else if (LOG_LOCAL2
< facility
&& facility
<= LOG_LOCAL7
) { // "ident[1-5].log"
345 snprintf(sl_logpath
, sizeof(sl_logpath
)-1, "%s%d.log",
346 sl_ident
, LOG_FAC(facility
)-LOG_FAC(LOG_LOCAL2
));
348 else // Assume LOG_DAEMON, use event log if possible, else "ident.log"
349 if (!(sl_hevtsrc
= RegisterEventSourceA(NULL
/*localhost*/, sl_ident
))) {
350 // Cannot open => Use logfile
351 long err
= GetLastError();
352 strcat(strcpy(sl_logpath
, sl_ident
), ".log");
353 if (GetVersion() & 0x80000000)
354 fprintf(stderr
, "%s: No event log on Win9x/ME, writing to %s\n",
355 sl_ident
, sl_logpath
);
357 fprintf(stderr
, "%s: Cannot register event source (Error=%ld), writing to %s\n",
358 sl_ident
, err
, sl_logpath
);
361 // Start event log thread
362 start_event_logger();
364 //assert(sl_logpath[0] || sl_logfile || sl_hevtsrc);
374 void vsyslog(int priority
, const char * message
, va_list args
)
378 // Translation of %m to error text not supported yet
379 if (strstr(message
, "%m"))
380 message
= "Internal error: \"%%m\" in log message";
383 if (vsnprintf(buffer
, sizeof(buffer
)-1, message
, args
) < 0)
384 strcpy(buffer
, "Internal Error: buffer overflow");
387 // Write to event log
388 write_event_log(priority
, buffer
);
390 else if (sl_logfile
) {
391 // Write to stdout/err
392 write_logfile(sl_logfile
, priority
, buffer
);
395 else if (sl_logpath
[0]) {
398 if (!(f
= fopen(sl_logpath
, "a")))
400 write_logfile(f
, priority
, buffer
);
409 void syslog(int priority
, const char *message
, ...)
412 va_start(args
, message
);
413 vsyslog(priority
, message
, args
);
417 int main(int argc
, char* argv
[])
420 openlog(argc
< 2 ? "test" : argv
[1], LOG_PID
, (argc
< 3 ? LOG_DAEMON
: LOG_LOCAL1
));
421 syslog(LOG_INFO
, "Info\n");
422 syslog(LOG_WARNING
, "Warning %d\n\n", 42);
423 syslog(LOG_ERR
, "Error %s", "Fatal");
424 for (i
= 0; i
< 100; i
++) {
428 sprintf(buf
, "Log Line %d\n", i
);
429 syslog(i
% 17 ? LOG_INFO
: LOG_ERR
, buf
);