2023-04-22 10:17:51 +00:00
|
|
|
//go:build windows
|
|
|
|
|
|
|
|
// Package eventlog provides a Logger that writes to Windows Event Log.
|
|
|
|
package eventlog
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
|
|
|
|
"golang.org/x/sys/windows"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// NeLogOemCode is a generic error log entry for OEMs to use to
|
|
|
|
// elog errors from OEM value added services.
|
|
|
|
// See: https://github.com/microsoft/win32metadata/blob/2f3c5282ce1024a712aeccd90d3aa50bf7a49e27/generation/WinSDK/RecompiledIdlHeaders/um/LMErrlog.h#L824-L845
|
|
|
|
neLogOemCode = uint32(3299)
|
|
|
|
)
|
|
|
|
|
2024-09-10 22:34:10 +00:00
|
|
|
// Interface guard.
|
|
|
|
var _ io.Writer = (*Writer)(nil)
|
2023-04-22 10:17:51 +00:00
|
|
|
|
2024-09-10 22:34:10 +00:00
|
|
|
type Writer struct {
|
|
|
|
handle windows.Handle
|
2023-04-22 10:17:51 +00:00
|
|
|
}
|
|
|
|
|
2024-09-10 22:34:10 +00:00
|
|
|
// NewEventLogWriter returns a new Writer which writes to Windows EventLog.
|
|
|
|
func NewEventLogWriter(handle windows.Handle) *Writer {
|
|
|
|
return &Writer{handle: handle}
|
2023-04-22 10:17:51 +00:00
|
|
|
}
|
|
|
|
|
2024-09-10 22:34:10 +00:00
|
|
|
func (w *Writer) Write(p []byte) (int, error) {
|
|
|
|
var eType uint16
|
2024-08-05 13:50:41 +00:00
|
|
|
|
2024-09-10 22:34:10 +00:00
|
|
|
switch {
|
|
|
|
case bytes.Contains(p, []byte(" level=error")) || bytes.Contains(p, []byte(`"level":"error"`)):
|
|
|
|
eType = windows.EVENTLOG_ERROR_TYPE
|
|
|
|
case bytes.Contains(p, []byte(" level=warn")) || bytes.Contains(p, []byte(`"level":"warn"`)):
|
|
|
|
eType = windows.EVENTLOG_WARNING_TYPE
|
|
|
|
default:
|
|
|
|
eType = windows.EVENTLOG_INFORMATION_TYPE
|
2023-04-22 10:17:51 +00:00
|
|
|
}
|
|
|
|
|
2024-09-10 22:34:10 +00:00
|
|
|
msg, err := windows.UTF16PtrFromString(string(p))
|
2023-04-22 10:17:51 +00:00
|
|
|
if err != nil {
|
2024-09-10 22:34:10 +00:00
|
|
|
return 0, fmt.Errorf("error convert string to UTF-16: %w", err)
|
2023-04-22 10:17:51 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
ss := []*uint16{msg, nil, nil, nil, nil, nil, nil, nil, nil}
|
|
|
|
|
2024-09-10 22:34:10 +00:00
|
|
|
return len(p), windows.ReportEvent(w.handle, eType, 0, neLogOemCode, 0, 9, 0, &ss[0], nil)
|
2023-04-22 10:17:51 +00:00
|
|
|
}
|