Logging logs in Windows

Richard (Rikki) Andrew Cattermole richard at cattermole.co.nz
Sat Feb 4 14:48:55 UTC 2023


On 05/02/2023 2:31 AM, Alexander Zhirov wrote:
> On Friday, 3 February 2023 at 18:02:59 UTC, Richard (Rikki) Andrew 
> Cattermole wrote:
>> Here is a starting point that I myself have used in the past:
> 
> I understand that programming under Windows is a shame for a programmer, 
> but is there really no ready-made solution for using the system log in 
> Windows?

Not at all.

syslog is the system api for logging on Posix, event log is the Windows 
equivalent system api.

They are both good in their own ways, even if they are not 1:1.

I can't see anything on dub-registry or in Phobos. But its not hard to 
implement.

I.e. here are my functions for syslog and Windows Event log (I won't 
copy it all, it won't be helpful & the file log function is giant compared).

```d
             void syslog() {
                 version (Posix) {
                     import core.sys.posix.syslog : syslog;

                     syslog(prioritySyslogForLevels[level], 
unsafeTextMessageComposite.ptr);
                 }
             }

             void windowsEvents() {
                 version (Windows) {
                     import core.sys.windows.windows : ReportEventA, 
WORD, DWORD, EVENTLOG_INFORMATION_TYPE,
                         EVENTLOG_WARNING_TYPE, EVENTLOG_ERROR_TYPE;

                     static WORD[] WTypes = [
                         EVENTLOG_INFORMATION_TYPE, 
EVENTLOG_INFORMATION_TYPE, EVENTLOG_WARNING_TYPE,
                         EVENTLOG_ERROR_TYPE, EVENTLOG_ERROR_TYPE, 
EVENTLOG_ERROR_TYPE
                     ];

                     static DWORD[] dwEventID = [0, 0, 0, 0, 0, 0];
                     const(char)*[2] messages = [
                         ModuleLine2.ptr,
                         cast(char*)unsafeTextMessageComposite.ptr + 
unsafeDateTime.length + ModuleLine.length
                     ];

                     ReportEventA(windowsEventHandle, WTypes[level], 0, 
dwEventID[level], cast(void*)null, 2, 0,
                             &messages[0], cast(void*)null);
                 }
             }
```

Note: you also need to setup an event source on Windows i.e.

```d
import core.sys.windows.windows : RegisterEventSourceA;
windowsEventHandle = RegisterEventSourceA(null, cast(char*)processName.ptr);
```

and to close it:

```d
import core.sys.windows.windows : DeregisterEventSource;
DeregisterEventSource(windowsEventHandle);
```


More information about the Digitalmars-d-learn mailing list