log.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. // +build windows
  5. // Package eventlog implements access to Windows event log.
  6. //
  7. package eventlog
  8. import (
  9. "errors"
  10. "syscall"
  11. "golang.org/x/sys/windows"
  12. )
  13. // Log provides access to the system log.
  14. type Log struct {
  15. Handle windows.Handle
  16. }
  17. // Open retrieves a handle to the specified event log.
  18. func Open(source string) (*Log, error) {
  19. return OpenRemote("", source)
  20. }
  21. // OpenRemote does the same as Open, but on different computer host.
  22. func OpenRemote(host, source string) (*Log, error) {
  23. if source == "" {
  24. return nil, errors.New("Specify event log source")
  25. }
  26. var s *uint16
  27. if host != "" {
  28. s = syscall.StringToUTF16Ptr(host)
  29. }
  30. h, err := windows.RegisterEventSource(s, syscall.StringToUTF16Ptr(source))
  31. if err != nil {
  32. return nil, err
  33. }
  34. return &Log{Handle: h}, nil
  35. }
  36. // Close closes event log l.
  37. func (l *Log) Close() error {
  38. return windows.DeregisterEventSource(l.Handle)
  39. }
  40. func (l *Log) report(etype uint16, eid uint32, msg string) error {
  41. ss := []*uint16{syscall.StringToUTF16Ptr(msg)}
  42. return windows.ReportEvent(l.Handle, etype, 0, eid, 0, 1, 0, &ss[0], nil)
  43. }
  44. // Info writes an information event msg with event id eid to the end of event log l.
  45. // When EventCreate.exe is used, eid must be between 1 and 1000.
  46. func (l *Log) Info(eid uint32, msg string) error {
  47. return l.report(windows.EVENTLOG_INFORMATION_TYPE, eid, msg)
  48. }
  49. // Warning writes an warning event msg with event id eid to the end of event log l.
  50. // When EventCreate.exe is used, eid must be between 1 and 1000.
  51. func (l *Log) Warning(eid uint32, msg string) error {
  52. return l.report(windows.EVENTLOG_WARNING_TYPE, eid, msg)
  53. }
  54. // Error writes an error event msg with event id eid to the end of event log l.
  55. // When EventCreate.exe is used, eid must be between 1 and 1000.
  56. func (l *Log) Error(eid uint32, msg string) error {
  57. return l.report(windows.EVENTLOG_ERROR_TYPE, eid, msg)
  58. }