2 * os_win32/syslog_win32.cpp
4 * Home page of code is: http://smartmontools.sourceforge.net
6 * Copyright (C) 2004-12 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, see <http://www.gnu.org/licenses/>.
18 // Win32 Emulation of syslog() for smartd
19 // Writes to windows event log on NT4/2000/XP
20 // (Register syslogevt.exe as event message file)
21 // If facility is set to LOG_LOCAL[0-7], log is written to
22 // file "<ident>.log", stdout, stderr, "<ident>[1-5].log".
31 #include <process.h> // getpid()
33 #define WIN32_LEAN_AND_MEAN
34 #include <windows.h> // RegisterEventSourceA(), ReportEventA(), ...
36 const char *syslog_win32_cpp_cvsid
= "$Id: syslog_win32.cpp 3575 2012-07-19 21:32:56Z chrfranke $"
41 #define snprintf _snprintf
42 #define vsnprintf _vsnprintf
45 #define ARGUSED(x) ((void)(x))
49 //MT runtime not necessary, because thread uses no unsafe lib functions
50 //#error Program must be linked with multithreaded runtime library
55 // Redirect event log to stdout for testing
57 static BOOL
Test_ReportEventA(HANDLE h
, WORD type
, WORD cat
, DWORD id
, PSID usid
,
58 WORD nstrings
, WORD datasize
, LPCTSTR
* strings
, LPVOID data
)
61 printf("%u %lu:%s", type
, id
, nstrings
!= 1?"\n":"");
62 for (i
= 0; i
< nstrings
; i
++)
63 printf(" \"%s\"\n", strings
[i
]);
68 HANDLE
Test_RegisterEventSourceA(LPCTSTR server
, LPCTSTR source
)
73 #define ReportEventA Test_ReportEventA
74 #define RegisterEventSourceA Test_RegisterEventSourceA
79 // should be identical to MSG_SYSLOG* in "syslogevt.h"
80 // (generated by "mc" from "syslogevt.mc")
81 #define MSG_SYSLOG 0x00000000L
82 #define MSG_SYSLOG_01 0x00000001L
84 #define MSG_SYSLOG_10 0x0000000AL
86 static char sl_ident
[100];
87 static char sl_logpath
[sizeof(sl_ident
) + sizeof("0.log")-1];
88 static FILE * sl_logfile
;
89 static char sl_pidstr
[16];
90 static HANDLE sl_hevtsrc
;
93 // Ring buffer for event log output via thread
97 static HANDLE evt_hthread
;
98 static char evt_lines
[MAXLINES
][LINELEN
+1];
99 static int evt_priorities
[MAXLINES
];
100 static volatile int evt_timeout
;
101 static int evt_index_in
, evt_index_out
;
102 static HANDLE evt_wait_in
, evt_wait_out
;
105 // Map syslog priority to event type
107 static WORD
pri2evtype(int priority
)
111 case LOG_EMERG
: case LOG_ALERT
:
112 case LOG_CRIT
: case LOG_ERR
:
113 return EVENTLOG_ERROR_TYPE
;
115 return EVENTLOG_WARNING_TYPE
;
116 case LOG_NOTICE
: case LOG_INFO
:
118 return EVENTLOG_INFORMATION_TYPE
;
123 // Map syslog priority to string
125 static const char * pri2text(int priority
)
128 case LOG_EMERG
: return "EMERG";
129 case LOG_ALERT
: return "ALERT";
130 case LOG_CRIT
: return "CRIT";
132 case LOG_ERR
: return "ERROR";
133 case LOG_WARNING
: return "Warn";
134 case LOG_NOTICE
: return "Note";
135 case LOG_INFO
: return "Info";
136 case LOG_DEBUG
: return "Debug";
141 // Output cnt events from ring buffer
143 static void report_events(int cnt
)
145 const char * msgs
[3+MAXLINES
];
153 pri
= evt_priorities
[evt_index_out
];
157 msgs
[2] = pri2text(pri
);
158 for (i
= 0; i
< cnt
; i
++) {
159 //assert(evt_priorities[evt_index_out] == pri);
160 msgs
[3+i
] = evt_lines
[evt_index_out
];
161 if (++evt_index_out
>= MAXLINES
)
164 ReportEventA(sl_hevtsrc
,
165 pri2evtype(pri
), // type
166 0, MSG_SYSLOG
+cnt
, // category, message id
167 NULL
, // no security id
168 (WORD
)(3+cnt
), 0, // 3+cnt strings, ...
169 msgs
, NULL
); // ... , no data
173 // Thread to combine several syslog lines into one event log entry
175 static ULONG WINAPI
event_logger_thread(LPVOID arg
)
182 // Wait for first line ...
185 if (WaitForSingleObject(evt_wait_out
, (evt_timeout
? INFINITE
: 0)) != WAIT_OBJECT_0
)
190 // ... wait some time for more lines with same prior
192 prior
= evt_priorities
[i
];
194 while (cnt
< MAXLINES
) {
196 evt_timeout
* ((1000L * (MAXLINES
-cnt
+1))/MAXLINES
);
197 if (WaitForSingleObject(evt_wait_out
, timeout
) != WAIT_OBJECT_0
)
201 if (evt_priorities
[i
] != prior
) {
208 // Output all in one event log entry
212 if (!ReleaseSemaphore(evt_wait_in
, cnt
, NULL
))
220 static void on_exit_event_logger(void)
222 // Output lines immediate if exiting
224 // Wait for thread to finish
225 WaitForSingleObject(evt_hthread
, 1000L);
226 CloseHandle(evt_hthread
);
229 DeregisterEventSource(sl_hevtsrc
); sl_hevtsrc
= 0;
232 // Leave event message source open to prevent losing messages during shutdown
237 static int start_event_logger()
241 if ( !(evt_wait_in
= CreateSemaphore(NULL
, MAXLINES
, MAXLINES
, NULL
))
242 || !(evt_wait_out
= CreateSemaphore(NULL
, 0, MAXLINES
, NULL
))) {
243 fprintf(stderr
,"CreateSemaphore failed, Error=%ld\n", GetLastError());
246 if (!(evt_hthread
= CreateThread(NULL
, 0, event_logger_thread
, NULL
, 0, &tid
))) {
247 fprintf(stderr
,"CreateThread failed, Error=%ld\n", GetLastError());
250 atexit(on_exit_event_logger
);
255 // Write lines to event log ring buffer
257 static void write_event_log(int priority
, const char * lines
)
261 for (i
= 0; lines
[i
]; i
++) {
263 while (lines
[i
+len
] && lines
[i
+len
] != '\n')
268 if (WaitForSingleObject(evt_wait_in
, INFINITE
) != WAIT_OBJECT_0
)
271 evt_priorities
[evt_index_in
] = priority
;
272 memcpy(evt_lines
[evt_index_in
], lines
+i
, (len
< LINELEN
? len
: LINELEN
));
274 evt_lines
[evt_index_in
][len
] = 0;
275 if (++evt_index_in
>= MAXLINES
)
277 // Signal avail if ring buffer full
278 if (++cnt
>= MAXLINES
) {
279 ReleaseSemaphore(evt_wait_out
, cnt
, NULL
);
290 ReleaseSemaphore(evt_wait_out
, cnt
, NULL
);
295 // Write lines to logfile
297 static void write_logfile(FILE * f
, int priority
, const char * lines
)
299 time_t now
; char stamp
[sizeof("2004-04-04 10:00:00")+13];
302 now
= time((time_t*)0);
303 if (!strftime(stamp
, sizeof(stamp
)-1, "%Y-%m-%d %H:%M:%S", localtime(&now
)))
306 for (i
= 0; lines
[i
]; i
++) {
308 while (lines
[i
+len
] && lines
[i
+len
] != '\n')
311 fprintf(f
, "%s %s[%s]: %-5s: ",
312 stamp
, sl_ident
, sl_pidstr
, pri2text(priority
));
313 fwrite(lines
+i
, len
, 1, f
);
323 void openlog(const char *ident
, int logopt
, int facility
)
326 if (sl_logpath
[0] || sl_logfile
|| sl_hevtsrc
)
327 return; // Already open
329 strncpy(sl_ident
, ident
, sizeof(sl_ident
)-1);
330 // logopt==LOG_PID assumed
333 if (snprintf(sl_pidstr
, sizeof(sl_pidstr
)-1, (pid
>= 0 ? "%d" : "0x%X"), pid
) < 0)
334 strcpy(sl_pidstr
,"?");
336 if (facility
== LOG_LOCAL0
) // "ident.log"
337 strcat(strcpy(sl_logpath
, sl_ident
), ".log");
338 else if (facility
== LOG_LOCAL1
) // stdout
340 else if (facility
== LOG_LOCAL2
) // stderr
342 else if (LOG_LOCAL2
< facility
&& facility
<= LOG_LOCAL7
) { // "ident[1-5].log"
343 snprintf(sl_logpath
, sizeof(sl_logpath
)-1, "%s%d.log",
344 sl_ident
, LOG_FAC(facility
)-LOG_FAC(LOG_LOCAL2
));
346 else // Assume LOG_DAEMON, use event log if possible, else "ident.log"
347 if (!(sl_hevtsrc
= RegisterEventSourceA(NULL
/*localhost*/, sl_ident
))) {
348 // Cannot open => Use logfile
349 long err
= GetLastError();
350 strcat(strcpy(sl_logpath
, sl_ident
), ".log");
351 fprintf(stderr
, "%s: Cannot register event source (Error=%ld), writing to %s\n",
352 sl_ident
, err
, sl_logpath
);
355 // Start event log thread
356 start_event_logger();
358 //assert(sl_logpath[0] || sl_logfile || sl_hevtsrc);
368 void vsyslog(int priority
, const char * message
, va_list args
)
372 // Translation of %m to error text not supported yet
373 if (strstr(message
, "%m"))
374 message
= "Internal error: \"%%m\" in log message";
377 if (vsnprintf(buffer
, sizeof(buffer
)-1, message
, args
) < 0)
378 strcpy(buffer
, "Internal Error: buffer overflow");
381 // Write to event log
382 write_event_log(priority
, buffer
);
384 else if (sl_logfile
) {
385 // Write to stdout/err
386 write_logfile(sl_logfile
, priority
, buffer
);
389 else if (sl_logpath
[0]) {
392 if (!(f
= fopen(sl_logpath
, "a")))
394 write_logfile(f
, priority
, buffer
);
403 void syslog(int priority
, const char *message
, ...)
406 va_start(args
, message
);
407 vsyslog(priority
, message
, args
);
411 int main(int argc
, char* argv
[])
414 openlog(argc
< 2 ? "test" : argv
[1], LOG_PID
, (argc
< 3 ? LOG_DAEMON
: LOG_LOCAL1
));
415 syslog(LOG_INFO
, "Info\n");
416 syslog(LOG_WARNING
, "Warning %d\n\n", 42);
417 syslog(LOG_ERR
, "Error %s", "Fatal");
418 for (i
= 0; i
< 100; i
++) {
422 sprintf(buf
, "Log Line %d\n", i
);
423 syslog(i
% 17 ? LOG_INFO
: LOG_ERR
, buf
);