winlog

package module
v1.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 15, 2022 License: MIT Imports: 7 Imported by: 4

README

gowinlog

Go Build CodeQL

Go library for subscribing to the Windows Event Log.

Godocs

PkgGoDev

Installation

just go get the thing

Features

  • Includes wrapper for wevtapi.dll, and a high level API
  • Supports bookmarks for resuming consumption
  • Filter events using XPath expressions

Usage

package main

import (
	"fmt"
	"time"

	winlog "github.com/ofcoursedude/gowinlog"
)

func main() {
	fmt.Println("Starting...")
	watcher, err := winlog.NewWinLogWatcher()
	if err != nil {
		fmt.Printf("Couldn't create watcher: %v\n", err)
		return
	}
	// Recieve any future messages on the Application channel
	// "*" doesn't filter by any fields of the event
	watcher.SubscribeFromNow("Application", "*")
	for {
		select {
		case evt := <-watcher.Event():
			// Print the event struct
			// fmt.Printf("\nEvent: %v\n", evt)
			// or print basic output
			fmt.Printf("\n%s: %s: %s\n", evt.LevelText, evt.ProviderName, evt.Msg)
		case err := <-watcher.Error():
			fmt.Printf("\nError: %v\n\n", err)
		default:
			// If no event is waiting, need to wait or do something else, otherwise
			// the the app fails on deadlock.
			<-time.After(1 * time.Millisecond)
		}
	}
}

Low-level API

winevt.go provides wrappers around the relevant functions in wevtapi.dll.

Documentation

Rendered for windows/amd64

Overview

Winlog hooks into the Windows Event Log and streams events through channels

Index

Constants

View Source
const (
	EvtVarTypeNull = iota
	EvtVarTypeString
	EvtVarTypeAnsiString
	EvtVarTypeSByte
	EvtVarTypeByte
	EvtVarTypeInt16
	EvtVarTypeUInt16
	EvtVarTypeInt32
	EvtVarTypeUInt32
	EvtVarTypeInt64
	EvtVarTypeUInt64
	EvtVarTypeSingle
	EvtVarTypeDouble
	EvtVarTypeBoolean
	EvtVarTypeBinary
	EvtVarTypeGuid
	EvtVarTypeSizeT
	EvtVarTypeFileTime
	EvtVarTypeSysTime
	EvtVarTypeSid
	EvtVarTypeHexInt32
	EvtVarTypeHexInt64
	EvtVarTypeEvtHandle
	EvtVarTypeEvtXml
)
View Source
const (
	EvtSubscribeToFutureEvents
	EvtSubscribeStartAtOldestRecord
	EvtSubscribeStartAfterBookmark
)
View Source
const (
	EvtSystemProviderName = iota
	EvtSystemProviderGuid
	EvtSystemEventID
	EvtSystemQualifiers
	EvtSystemLevel
	EvtSystemTask
	EvtSystemOpcode
	EvtSystemKeywords
	EvtSystemTimeCreated
	EvtSystemEventRecordId
	EvtSystemActivityID
	EvtSystemRelatedActivityID
	EvtSystemProcessID
	EvtSystemThreadID
	EvtSystemChannel
	EvtSystemComputer
	EvtSystemUserID
	EvtSystemVersion
)
View Source
const (
	EvtFormatMessageEvent
	EvtFormatMessageLevel
	EvtFormatMessageTask
	EvtFormatMessageOpcode
	EvtFormatMessageKeyword
	EvtFormatMessageChannel
	EvtFormatMessageProvider
	EvtFormatMessageId
	EvtFormatMessageXml
)
View Source
const (
	EvtRenderEventValues = iota
	EvtRenderEventXml
	EvtRenderBookmark
)
View Source
const (
	EvtRenderContextValues = iota
	EvtRenderContextSystem
	EvtRenderContextUser
)
View Source
const (
	EvtQueryChannelPath         = 0x1
	EvtQueryFilePath            = 0x2
	EvtQueryForwardDirection    = 0x100
	EvtQueryReverseDirection    = 0x200
	EvtQueryTolerateQueryErrors = 0x1000
)

Variables

This section is empty.

Functions

func CancelEventHandle

func CancelEventHandle(handle uint64) error

Cancel pending actions on the event handle.

func CloseEventHandle

func CloseEventHandle(handle uint64) error

Close an event handle.

func EvtCancel

func EvtCancel(handle syscall.Handle) error

func EvtClose

func EvtClose(Object syscall.Handle) error

func EvtCreateBookmark

func EvtCreateBookmark(BookmarkXml *uint16) (syscall.Handle, error)

func EvtCreateRenderContext

func EvtCreateRenderContext(ValuePathsCount uint32, ValuePaths uintptr, Flags uint32) (syscall.Handle, error)

func EvtFormatMessage

func EvtFormatMessage(PublisherMetadata, Event syscall.Handle, MessageId, ValueCount uint32, Values *byte, Flags, BufferSize uint32, Buffer *uint16, BufferUsed *uint32) error

func EvtNext

func EvtNext(ResultSet syscall.Handle, EventArraySize uint32, EventArray *syscall.Handle, Timeout, Flags uint32, Returned *uint32) error

func EvtOpenPublisherMetadata

func EvtOpenPublisherMetadata(Session syscall.Handle, PublisherIdentity, LogFilePath *uint16, Locale, Flags uint32) (syscall.Handle, error)

func EvtQuery

func EvtQuery(Session syscall.Handle, Path, Query *uint16, Flags uint32) (syscall.Handle, error)

func EvtRender

func EvtRender(Context, Fragment syscall.Handle, Flags, BufferSize uint32, Buffer *uint16, BufferUsed, PropertyCount *uint32) error

func EvtSubscribe

func EvtSubscribe(Session, SignalEvent syscall.Handle, ChannelPath, Query *uint16, Bookmark syscall.Handle, context uintptr, Callback uintptr, Flags uint32) (syscall.Handle, error)

func EvtUpdateBookmark

func EvtUpdateBookmark(Bookmark, Event syscall.Handle) error

func FormatMessage

func FormatMessage(eventPublisherHandle PublisherHandle, eventHandle EventHandle, format EVT_FORMAT_MESSAGE_FLAGS) (string, error)

Get the formatted string that represents this message. This method wraps EvtFormatMessage.

func GetLastError

func GetLastError() error

Get the formatted string for the last error which occurred. Wraps GetLastError and FormatMessage.

func RenderBookmark

func RenderBookmark(bookmarkHandle BookmarkHandle) (string, error)

Serialize the bookmark as XML

func RenderEventXML

func RenderEventXML(eventHandle EventHandle) (string, error)

Render the event as XML.

func UTF16ToString

func UTF16ToString(s []uint16) string

func UpdateBookmark

func UpdateBookmark(bookmarkHandle BookmarkHandle, eventHandle EventHandle) error

Update a bookmark to store the channel and ID of the given event

Types

type BookmarkHandle

type BookmarkHandle uint64

func CreateBookmark

func CreateBookmark() (BookmarkHandle, error)

Create a new, empty bookmark. Bookmark handles must be closed with CloseEventHandle.

func CreateBookmarkFromXml

func CreateBookmarkFromXml(xmlString string) (BookmarkHandle, error)

Create a bookmark from a XML-serialized bookmark. Bookmark handles must be closed with CloseEventHandle.

type EVT_FORMAT_MESSAGE_FLAGS

type EVT_FORMAT_MESSAGE_FLAGS int

Formatting modes for GetFormattedMessage

type EVT_QUERY_FLAGS

type EVT_QUERY_FLAGS uint32

type EVT_RENDER_CONTEXT_FLAGS

type EVT_RENDER_CONTEXT_FLAGS uint32

type EVT_RENDER_FLAGS

type EVT_RENDER_FLAGS uint32

type EVT_SUBSCRIBE_FLAGS

type EVT_SUBSCRIBE_FLAGS int

type EVT_SYSTEM_PROPERTY_ID

type EVT_SYSTEM_PROPERTY_ID int

Fields that can be rendered with GetRendered*Value

type EventHandle

type EventHandle uint64

type EvtVariant

type EvtVariant []byte

func NewEvtVariant

func NewEvtVariant(buffer []byte) EvtVariant

Given a byte array from EvtRender, make an EvtVariant.

EvtVariant wraps an array of variables.

func RenderEventValues

func RenderEventValues(renderContext SysRenderContext, eventHandle EventHandle) (EvtVariant, error)

Render the system properties from the event and returns an array of properties.

Properties can be accessed using RenderStringField, RenderIntField, RenderFileTimeField,
or RenderUIntField depending on type. This buffer must be freed after use.

func (EvtVariant) FileTime

func (e EvtVariant) FileTime(index uint32) (time.Time, error)

Return the FileTime at `index`, converted to Time.time. If the

variable isn't a FileTime an error is returned

func (EvtVariant) Int

func (e EvtVariant) Int(index uint32) (int64, error)

Return the integer value at `index`. If the variable

isn't a SByte, Int16, Int32 or Int64 an error is returned.

func (EvtVariant) IsNull

func (e EvtVariant) IsNull(index uint32) bool

Return whether the variable was actually set, or whether it

has null type

func (EvtVariant) String

func (e EvtVariant) String(index uint32) (string, error)

Return the string value of the variable at `index`. If the

variable isn't a string, an error is returned

func (EvtVariant) Uint

func (e EvtVariant) Uint(index uint32) (uint64, error)

Return the unsigned integer value at `index`. If the variable

isn't a Byte, UInt16, UInt32 or UInt64 an error is returned.

type ListenerHandle

type ListenerHandle uint64

func CreateListener

func CreateListener(channel, query string, startpos EVT_SUBSCRIBE_FLAGS, watcher *LogEventCallbackWrapper) (ListenerHandle, error)

Get a handle for a event log subscription on the given channel.

`query` is an XPath expression to filter the events on the channel - "*" allows all events.
The resulting handle must be closed with CloseEventHandle.

func CreateListenerFromBookmark

func CreateListenerFromBookmark(channel, query string, watcher *LogEventCallbackWrapper, bookmarkHandle BookmarkHandle) (ListenerHandle, error)

Get a handle for an event log subscription on the given channel. Will begin at the

bookmarked event, or the closest possible event if the log has been truncated.
`query` is an XPath expression to filter the events on the channel - "*" allows all events.
The resulting handle must be closed with CloseEventHandle.

type LogEventCallback

type LogEventCallback interface {
	PublishError(error)
	PublishEvent(EventHandle, string)
}

type LogEventCallbackWrapper

type LogEventCallbackWrapper struct {
	// contains filtered or unexported fields
}

type PublisherHandle

type PublisherHandle uint64

func GetEventPublisherHandle

func GetEventPublisherHandle(renderedFields EvtVariant) (PublisherHandle, error)

Get a handle that represents the publisher of the event, given the rendered event values.

type SysRenderContext

type SysRenderContext uint64

func GetSystemRenderContext

func GetSystemRenderContext() (SysRenderContext, error)

Get a handle to a render context which will render properties from the System element.

Wraps EvtCreateRenderContext() with Flags = EvtRenderContextSystem. The resulting
handle must be closed with CloseEventHandle.

type WinLogEvent

type WinLogEvent struct {
	// XML
	Xml    string
	XmlErr error

	// From EvtRender
	ProviderName      string
	EventId           uint64
	Qualifiers        uint64
	Level             uint64
	Task              uint64
	Opcode            uint64
	Created           time.Time
	RecordId          uint64
	ProcessId         uint64
	ThreadId          uint64
	Channel           string
	ComputerName      string
	Version           uint64
	RenderedFieldsErr error

	// From EvtFormatMessage
	Msg                string
	LevelText          string
	TaskText           string
	OpcodeText         string
	Keywords           string
	ChannelText        string
	ProviderText       string
	IdText             string
	PublisherHandleErr error

	// Serialied XML bookmark to
	// restart at this event
	Bookmark string

	// Subscribed channel from which the event was retrieved,
	// which may be different than the event's channel
	SubscribedChannel string
}

Stores the common fields from a log event

func (*WinLogEvent) CreateMap added in v1.0.4

func (ev *WinLogEvent) CreateMap() map[string]interface{}

CreateMap converts the WinLogEvent to a map[string]interface{}

type WinLogWatcher

type WinLogWatcher struct {

	// Optionally render localized fields. EvtFormatMessage() is slow, so
	// skipping these fields provides a big speedup.
	RenderKeywords bool
	RenderMessage  bool
	RenderLevel    bool
	RenderTask     bool
	RenderProvider bool
	RenderOpcode   bool
	RenderChannel  bool
	RenderId       bool
	// contains filtered or unexported fields
}

Watches one or more event log channels and publishes events and errors to Go channels

func NewWinLogWatcher

func NewWinLogWatcher() (*WinLogWatcher, error)

NewWinLogWatcher creates a new watcher

func (*WinLogWatcher) Error

func (wlw *WinLogWatcher) Error() <-chan error

Channel for receiving errors (not "error" events)

func (*WinLogWatcher) Event

func (wlw *WinLogWatcher) Event() <-chan *WinLogEvent

Event Channel for receiving events

func (*WinLogWatcher) PublishError

func (self *WinLogWatcher) PublishError(err error)

Publish the received error to the errChan, but discard if shutdown is in progress

func (*WinLogWatcher) PublishEvent

func (self *WinLogWatcher) PublishEvent(handle EventHandle, subscribedChannel string)

Publish a new event

func (*WinLogWatcher) RemoveSubscription

func (self *WinLogWatcher) RemoveSubscription(channel string) error

Remove subscription from channel

func (*WinLogWatcher) Shutdown

func (self *WinLogWatcher) Shutdown()

Remove all subscriptions from this watcher and shut down.

func (*WinLogWatcher) SubscribeFromBeginning

func (self *WinLogWatcher) SubscribeFromBeginning(channel, query string) error

Subscribe to a Windows Event Log channel, starting with the first event in the log. `query` is an XPath expression for filtering events: to recieve all events on the channel, use "*" as the query.

func (*WinLogWatcher) SubscribeFromBookmark

func (self *WinLogWatcher) SubscribeFromBookmark(channel, query string, xmlString string) error

Subscribe to a Windows Event Log channel, starting with the first event in the log after the bookmarked event. There may be a gap if events have been purged. `query` is an XPath expression for filtering events: to recieve all events on the channel, use "*" as the query

func (*WinLogWatcher) SubscribeFromNow

func (self *WinLogWatcher) SubscribeFromNow(channel, query string) error

Subscribe to a Windows Event Log channel, starting with the next event that arrives. `query` is an XPath expression for filtering events: to recieve all events on the channel, use "*" as the query.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL