You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

81 lines
2.3 KiB

  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
  6. import (
  7. "errors"
  8. "golang.org/x/sys/windows"
  9. "golang.org/x/sys/windows/registry"
  10. )
  11. const (
  12. // Log levels.
  13. Info = windows.EVENTLOG_INFORMATION_TYPE
  14. Warning = windows.EVENTLOG_WARNING_TYPE
  15. Error = windows.EVENTLOG_ERROR_TYPE
  16. )
  17. const addKeyName = `SYSTEM\CurrentControlSet\Services\EventLog\Application`
  18. // Install modifies PC registry to allow logging with an event source src.
  19. // It adds all required keys and values to the event log registry key.
  20. // Install uses msgFile as the event message file. If useExpandKey is true,
  21. // the event message file is installed as REG_EXPAND_SZ value,
  22. // otherwise as REG_SZ. Use bitwise of log.Error, log.Warning and
  23. // log.Info to specify events supported by the new event source.
  24. func Install(src, msgFile string, useExpandKey bool, eventsSupported uint32) error {
  25. appkey, err := registry.OpenKey(registry.LOCAL_MACHINE, addKeyName, registry.CREATE_SUB_KEY)
  26. if err != nil {
  27. return err
  28. }
  29. defer appkey.Close()
  30. sk, alreadyExist, err := registry.CreateKey(appkey, src, registry.SET_VALUE)
  31. if err != nil {
  32. return err
  33. }
  34. defer sk.Close()
  35. if alreadyExist {
  36. return errors.New(addKeyName + `\` + src + " registry key already exists")
  37. }
  38. err = sk.SetDWordValue("CustomSource", 1)
  39. if err != nil {
  40. return err
  41. }
  42. if useExpandKey {
  43. err = sk.SetExpandStringValue("EventMessageFile", msgFile)
  44. } else {
  45. err = sk.SetStringValue("EventMessageFile", msgFile)
  46. }
  47. if err != nil {
  48. return err
  49. }
  50. err = sk.SetDWordValue("TypesSupported", eventsSupported)
  51. if err != nil {
  52. return err
  53. }
  54. return nil
  55. }
  56. // InstallAsEventCreate is the same as Install, but uses
  57. // %SystemRoot%\System32\EventCreate.exe as the event message file.
  58. func InstallAsEventCreate(src string, eventsSupported uint32) error {
  59. return Install(src, "%SystemRoot%\\System32\\EventCreate.exe", true, eventsSupported)
  60. }
  61. // Remove deletes all registry elements installed by the correspondent Install.
  62. func Remove(src string) error {
  63. appkey, err := registry.OpenKey(registry.LOCAL_MACHINE, addKeyName, registry.SET_VALUE)
  64. if err != nil {
  65. return err
  66. }
  67. defer appkey.Close()
  68. return registry.DeleteKey(appkey, src)
  69. }