| 1 |
// Copyright 2012 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
//go:build windows |
| 6 |
|
| 7 |
// Package eventlog implements access to Windows event log. |
| 8 |
package eventlog |
| 9 |
|
| 10 |
import ( |
| 11 |
"errors" |
| 12 |
"syscall" |
| 13 |
|
| 14 |
"golang.org/x/sys/windows" |
| 15 |
) |
| 16 |
|
| 17 |
// Log provides access to the system log. |
| 18 |
type Log struct { |
| 19 |
Handle windows.Handle |
| 20 |
} |
| 21 |
|
| 22 |
// Open retrieves a handle to the specified event log. |
| 23 |
func Open(source string) (*Log, error) { |
| 24 |
return OpenRemote("", source) |
| 25 |
} |
| 26 |
|
| 27 |
// OpenRemote does the same as Open, but on different computer host. |
| 28 |
func OpenRemote(host, source string) (*Log, error) { |
| 29 |
if source == "" { |
| 30 |
return nil, errors.New("Specify event log source") |
| 31 |
} |
| 32 |
var hostPointer *uint16 |
| 33 |
if host != "" { |
| 34 |
var err error |
| 35 |
hostPointer, err = syscall.UTF16PtrFromString(host) |
| 36 |
if err != nil { |
| 37 |
return nil, err |
| 38 |
} |
| 39 |
} |
| 40 |
sourcePointer, err := syscall.UTF16PtrFromString(source) |
| 41 |
if err != nil { |
| 42 |
return nil, err |
| 43 |
} |
| 44 |
h, err := windows.RegisterEventSource(hostPointer, sourcePointer) |
| 45 |
if err != nil { |
| 46 |
return nil, err |
| 47 |
} |
| 48 |
return &Log{Handle: h}, nil |
| 49 |
} |
| 50 |
|
| 51 |
// Close closes event log l. |
| 52 |
func (l *Log) Close() error { |
| 53 |
return windows.DeregisterEventSource(l.Handle) |
| 54 |
} |
| 55 |
|
| 56 |
func (l *Log) report(etype uint16, eid uint32, msg string) error { |
| 57 |
msgPointer, err := syscall.UTF16PtrFromString(msg) |
| 58 |
if err != nil { |
| 59 |
return err |
| 60 |
} |
| 61 |
ss := []*uint16{msgPointer} |
| 62 |
return windows.ReportEvent(l.Handle, etype, 0, eid, 0, 1, 0, &ss[0], nil) |
| 63 |
} |
| 64 |
|
| 65 |
// Info writes an information event msg with event id eid to the end of event log l. |
| 66 |
// When EventCreate.exe is used, eid must be between 1 and 1000. |
| 67 |
func (l *Log) Info(eid uint32, msg string) error { |
| 68 |
return l.report(windows.EVENTLOG_INFORMATION_TYPE, eid, msg) |
| 69 |
} |
| 70 |
|
| 71 |
// Warning writes an warning event msg with event id eid to the end of event log l. |
| 72 |
// When EventCreate.exe is used, eid must be between 1 and 1000. |
| 73 |
func (l *Log) Warning(eid uint32, msg string) error { |
| 74 |
return l.report(windows.EVENTLOG_WARNING_TYPE, eid, msg) |
| 75 |
} |
| 76 |
|
| 77 |
// Error writes an error event msg with event id eid to the end of event log l. |
| 78 |
// When EventCreate.exe is used, eid must be between 1 and 1000. |
| 79 |
func (l *Log) Error(eid uint32, msg string) error { |
| 80 |
return l.report(windows.EVENTLOG_ERROR_TYPE, eid, msg) |
| 81 |
} |