Documentation ¶
Overview ¶
Package etw allows you to receive Event Tracing for Windows (ETW) events.
etw allows you to process events from new TraceLogging providers as well as from classic (aka EventLog) providers, so you could actually listen to anything you can see in Event Viewer window.
For possible usage examples take a look at https://github.com/bi-zone/etw/tree/master/examples
Index ¶
- Constants
- func KillSession(name string) error
- type CompareOperation
- type EnableFlag
- type EnableProperty
- type Event
- type EventCallback
- type EventDescriptor
- type EventFieldType
- type EventFilter
- type EventFilterDescriptor
- type EventFilterType
- type EventHeader
- type EventIdFilter
- type EventInstanceInfo
- type EventPayloadCompare
- type EventPayloadFilter
- type EventStackTrace
- type ExistsError
- type ExtendedEventInfo
- type LogFileMode
- type Provider
- func (p Provider) ListChannels() ([]ProviderField, error)
- func (p Provider) ListEvents() ([]EventDescriptor, error)
- func (p Provider) ListKeywords() ([]ProviderField, error)
- func (p Provider) ListLevels() ([]ProviderField, error)
- func (p Provider) QueryField(fieldValue uint64, fieldType EventFieldType) ([]ProviderField, error)
- func (p Provider) QueryOpcode(taskValue uint16, opcodeValue uint8) (ProviderField, error)
- func (p Provider) QueryTask(taskValue uint16) (ProviderField, error)
- type ProviderField
- type ProviderOption
- type ProviderOptions
- type Session
- type SessionOption
- type SessionOptions
- type SessionStatistics
- type TraceLevel
Constants ¶
const ( TdhIntypeBinary = 14 TdhOuttypeIpv6 = 24 )
const ( TRACE_LEVEL_CRITICAL = TraceLevel(1) TRACE_LEVEL_ERROR = TraceLevel(2) TRACE_LEVEL_WARNING = TraceLevel(3) TRACE_LEVEL_INFORMATION = TraceLevel(4) TRACE_LEVEL_VERBOSE = TraceLevel(5) )
const ( // Include in the ExtendedEventInfo the security identifier (SID) of the user. EVENT_ENABLE_PROPERTY_SID = EnableProperty(0x001) // Include in the ExtendedEventInfo the terminal session identifier. EVENT_ENABLE_PROPERTY_TS_ID = EnableProperty(0x002) // Include in the ExtendedEventInfo a call stack trace for events written // using EventWrite. EVENT_ENABLE_PROPERTY_STACK_TRACE = EnableProperty(0x004) // Filters out all events that do not have a non-zero keyword specified. // By default events with 0 keywords are accepted. EVENT_ENABLE_PROPERTY_IGNORE_KEYWORD_0 = EnableProperty(0x010) // Filters out all events that are either marked as an InPrivate event or // come from a process that is marked as InPrivate. InPrivate implies that // the event or process contains some data that would be considered private // or personal. It is up to the process or event to designate itself as // InPrivate for this to work. EVENT_ENABLE_PROPERTY_EXCLUDE_INPRIVATE = EnableProperty(0x200) )
const ( // EVENT_TRACE_SECURE_MODE specifies that secure mode should be enabled on the session. // This restricts who may log events to the session. EVENT_TRACE_SECURE_MODE = LogFileMode(0x00000080) // EVENT_TRACE_SYSTEM_LOGGER_MODE specifies that the session will receive events from the // SystemTraceProvider. EVENT_TRACE_SYSTEM_LOGGER_MODE = LogFileMode(0x02000000) // EVENT_TRACE_INDEPENDENT_SESSION_MODE specifies that this session should not be affected // by failures in other ETW sessions. EVENT_TRACE_INDEPENDENT_SESSION_MODE = LogFileMode(0x08000000) )
Variables ¶
This section is empty.
Functions ¶
func KillSession ¶
KillSession forces the session with a given @name to stop. Don't having a session handle we can't shutdown it gracefully unsubscribing from all the providers first, so we just stop the session itself.
Use KillSession only to destroy session you've lost control over. If you have a session handle always prefer `.Close`.
Types ¶
type CompareOperation ¶
type CompareOperation uint16
const ( CompareIntegerEqual CompareOperation = iota CompareIntegerNotEqual CompareIntegerLessOrEqual CompareIntegerGreater CompareIntegerLess CompareIntegerGreatorOrEqual CompareIntegerBetween CompareIntegerNotBetween CompareIntegerModulo )
const ( CompareStringContains CompareOperation = 20 CompareStringNotContains CompareOperation = 21 CompareStringEquals CompareOperation = 30 CompareStringNotEquals CompareOperation = 31 )
type EnableFlag ¶
type EnableFlag uint32
const ( EVENT_TRACE_FLAG_PROCESS EnableFlag = 0x00000001 EVENT_TRACE_FLAG_THREAD EnableFlag = 0x00000002 EVENT_TRACE_FLAG_IMAGE_LOAD EnableFlag = 0x00000004 EVENT_TRACE_FLAG_DISK_IO EnableFlag = 0x00000100 EVENT_TRACE_FLAG_DISK_FILE_IO EnableFlag = 0x00000200 EVENT_TRACE_FLAG_MEMORY_PAGE_FAULTS EnableFlag = 0x00001000 EVENT_TRACE_FLAG_MEMORY_HARD_FAULTS EnableFlag = 0x00002000 EVENT_TRACE_FLAG_NETWORK_TCPIP EnableFlag = 0x00010000 EVENT_TRACE_FLAG_REGISTRY EnableFlag = 0x00020000 EVENT_TRACE_FLAG_DBGPRINT EnableFlag = 0x00040000 EVENT_TRACE_FLAG_PROCESS_COUNTERS EnableFlag = 0x00000008 EVENT_TRACE_FLAG_CSWITCH EnableFlag = 0x00000010 EVENT_TRACE_FLAG_DPC EnableFlag = 0x00000020 EVENT_TRACE_FLAG_INTERRUPT EnableFlag = 0x00000040 EVENT_TRACE_FLAG_SYSTEMCALL EnableFlag = 0x00000080 EVENT_TRACE_FLAG_DISK_IO_INIT EnableFlag = 0x00000400 EVENT_TRACE_FLAG_ALPC EnableFlag = 0x00100000 EVENT_TRACE_FLAG_SPLIT_IO EnableFlag = 0x00200000 EVENT_TRACE_FLAG_DRIVER EnableFlag = 0x00800000 EVENT_TRACE_FLAG_PROFILE EnableFlag = 0x01000000 EVENT_TRACE_FLAG_FILE_IO EnableFlag = 0x02000000 EVENT_TRACE_FLAG_FILE_IO_INIT EnableFlag = 0x04000000 EVENT_TRACE_FLAG_DISPATCHER EnableFlag = 0x00000800 EVENT_TRACE_FLAG_VIRTUAL_ALLOC EnableFlag = 0x00004000 EVENT_TRACE_FLAG_VAMAP EnableFlag = 0x00008000 EVENT_TRACE_FLAG_NO_SYSCONFIG EnableFlag = 0x10000000 EVENT_TRACE_FLAG_JOB EnableFlag = 0x00080000 EVENT_TRACE_FLAG_DEBUG_EVENTS EnableFlag = 0x00400000 EVENT_TRACE_FLAG_EXTENSION EnableFlag = 0x80000000 EVENT_TRACE_FLAG_FORWARD_WMI EnableFlag = 0x40000000 EVENT_TRACE_FLAG_ENABLE_RESERVE EnableFlag = 0x20000000 EVENT_TRACE_FLAG_OBTRACE EnableFlag = 0x80000040 // EVENT_TRACE_FLAG_RUNDOWN is not a real flag, but another undefined behavior. // Use to cause a call TraceSetInformation with an empty mask, which activates rundown events. EVENT_TRACE_FLAG_RUNDOWN EnableFlag = 0x00000000 )
type EnableProperty ¶
type EnableProperty uint32
EnableProperty enables a property of a provider session is subscribing for.
For more info about available properties check original API reference: https://docs.microsoft.com/en-us/windows/win32/api/evntrace/ns-evntrace-enable_trace_parameters
type Event ¶
type Event struct { Header EventHeader // contains filtered or unexported fields }
Event is a single event record received from ETW provider. The only thing that is parsed implicitly is an EventHeader (which just translated from C structures mostly 1:1), all other data are parsed on-demand.
Events will be passed to the user EventCallback. It's invalid to use Event methods outside of an EventCallback.
func (*Event) EventProperties ¶
EventProperties returns a map that represents events-specific data provided by event producer. Returned data depends on the provider, event type and even provider and event versions.
The simplest (and the recommended) way to parse event data is to use TDH family of functions that render event data to the strings exactly as you can see it in the Event Viewer.
EventProperties returns a map that could be interpreted as "structure that fit inside a map". Map keys is a event data field names, map values is field values rendered to strings. So map values could be one of the following:
- `[]string` for arrays of any types;
- `map[string]interface{}` for fields that are structures;
- `string` for any other values.
Take a look at `TestParsing` for possible EventProperties values.
func (*Event) ExtendedInfo ¶
func (e *Event) ExtendedInfo() ExtendedEventInfo
ExtendedInfo extracts ExtendedEventInfo structure from native buffers of received event record.
If no ExtendedEventInfo is available inside an event record function returns the structure with all fields set to nil.
func (*Event) UserData ¶
UserData returns the payload of the event as a raw slice. This data usually needs interpretation, as EventProperties does, to map it to single events. However, if for an event the data layout is already known, this can be used to efficiently parse the data. UserData gives a slice that points directly at the data returned by the API. It should not be modified or used after the ETW callback has returned.
type EventCallback ¶
type EventCallback func(e *Event)
EventCallback is any function that could handle an ETW event. EventCallback is called synchronously and sequentially on every event received by Session one by one.
If EventCallback can't handle all ETW events produced, OS will handle a tricky file-based cache for you, however, it's recommended not to perform long-running tasks inside a callback.
N.B. Event pointer @e is valid ONLY inside a callback. You CAN'T copy a whole event, only EventHeader, EventProperties and ExtendedEventInfo separately.
type EventDescriptor ¶
type EventDescriptor struct { ID uint16 Version uint8 Channel uint8 Level uint8 OpCode uint8 Task uint16 Keyword uint64 }
EventDescriptor contains low-level metadata that defines received event. Most of fields could be used to refine events filtration.
For detailed information about fields values refer to EVENT_DESCRIPTOR docs: https://docs.microsoft.com/ru-ru/windows/win32/api/evntprov/ns-evntprov-event_descriptor
type EventFieldType ¶
type EventFieldType uint32
const ( EventKeywordInformation EventFieldType = iota EventLevelInformation EventChannelInformation EventTaskInformation EventOpcodeInformation )
type EventFilter ¶
type EventFilter interface { EventFilterDescriptor() (EventFilterDescriptor, error) Type() EventFilterType Merge(filter EventFilter) (EventFilter, error) }
type EventFilterDescriptor ¶
type EventFilterDescriptor struct { Descriptor eventFilterDescriptorC Close func() error }
type EventFilterType ¶
type EventFilterType uint32
type EventHeader ¶
type EventHeader struct { EventDescriptor ThreadID uint32 ProcessID uint32 TimeStamp time.Time ProviderID windows.GUID ActivityID windows.GUID Flags uint16 KernelTime uint32 UserTime uint32 ProcessorTime uint64 }
EventHeader contains an information that is common for every ETW event record.
EventHeader fields is self-descriptive. If you need more info refer to the original struct docs: https://docs.microsoft.com/en-us/windows/win32/api/evntcons/ns-evntcons-event_header
func (EventHeader) HasCPUTime ¶
func (h EventHeader) HasCPUTime() bool
HasCPUTime returns true if the event has separate UserTime and KernelTime measurements. Otherwise the value of UserTime and KernelTime is meaningless and you should use ProcessorTime instead.
type EventIdFilter ¶
type EventIdFilter struct { // The Event IDs that the filter should look for EventIds []uint16 // True for a filter that accepts only the given Event IDs, False for a filter that rejects the given Event IDs PositiveFilter bool }
EventIdFilter is a simple filter that filters by Event ID. Either a positive filter can be defined that allows only specific Event IDs or a negative filter that disallows specific Event IDs. Specifying both types is not allowed.
func (EventIdFilter) EventFilterDescriptor ¶
func (e EventIdFilter) EventFilterDescriptor() (EventFilterDescriptor, error)
func (EventIdFilter) Merge ¶
func (e EventIdFilter) Merge(other EventFilter) (EventFilter, error)
func (EventIdFilter) Type ¶
func (e EventIdFilter) Type() EventFilterType
type EventInstanceInfo ¶
EventInstanceInfo defines the relationship between events if its provided.
type EventPayloadCompare ¶
type EventPayloadCompare struct { Field string Value string Operation CompareOperation }
type EventPayloadFilter ¶
type EventPayloadFilter struct { FilteredProvider windows.GUID FilteredDescriptor EventDescriptor Comparisons []EventPayloadCompare AnyMatches bool }
func (EventPayloadFilter) EventFilterDescriptor ¶
func (e EventPayloadFilter) EventFilterDescriptor() (EventFilterDescriptor, error)
func (EventPayloadFilter) Merge ¶
func (EventPayloadFilter) Merge(filter EventFilter) (EventFilter, error)
func (EventPayloadFilter) Type ¶
func (EventPayloadFilter) Type() EventFilterType
type EventStackTrace ¶
EventStackTrace describes a call trace of the event occurred.
type ExistsError ¶
type ExistsError struct{ SessionName string }
ExistsError is returned by NewSession if the session name is already taken.
Having ExistsError you have an option to force kill the session:
var exists etw.ExistsError s, err = etw.NewSession(s.guid, etw.WithName(sessionName)) if errors.As(err, &exists) { err = etw.KillSession(exists.SessionName) }
func (ExistsError) Error ¶
func (e ExistsError) Error() string
type ExtendedEventInfo ¶
type ExtendedEventInfo struct { SessionID *uint32 ActivityID *windows.GUID UserSID *windows.SID InstanceInfo *EventInstanceInfo StackTrace *EventStackTrace }
ExtendedEventInfo contains additional information about received event. All ExtendedEventInfo fields are optional and are nils being not set by provider.
Presence of concrete fields is controlled by WithProperty option and an ability of event provider to set the required fields.
More info about fields is available at EVENT_HEADER_EXTENDED_DATA_ITEM.ExtType documentation: https://docs.microsoft.com/en-us/windows/win32/api/evntcons/ns-evntcons-event_header_extended_data_item
type LogFileMode ¶
type LogFileMode uint32
type Provider ¶
func ListProviders ¶
func LookupProvider ¶
func (Provider) ListChannels ¶
func (p Provider) ListChannels() ([]ProviderField, error)
func (Provider) ListEvents ¶
func (p Provider) ListEvents() ([]EventDescriptor, error)
func (Provider) ListKeywords ¶
func (p Provider) ListKeywords() ([]ProviderField, error)
func (Provider) ListLevels ¶
func (p Provider) ListLevels() ([]ProviderField, error)
func (Provider) QueryField ¶
func (p Provider) QueryField(fieldValue uint64, fieldType EventFieldType) ([]ProviderField, error)
func (Provider) QueryOpcode ¶
func (p Provider) QueryOpcode(taskValue uint16, opcodeValue uint8) (ProviderField, error)
type ProviderField ¶
type ProviderOption ¶
type ProviderOption func(cfg *ProviderOptions)
ProviderOption is any function that modifies ProviderOptions. Options will be called on default config in NewSession. Subsequent options that modifies same fields will override each other.
func WithFilter ¶
func WithFilter(f EventFilter) ProviderOption
WithFilter limits the events that the provider sends. Multiple filters can be specified to limit the events even further. If multiple Filters with the same filter type are specified, they are merged; check the filter type on what can be merged.
func WithLevel ¶
func WithLevel(lvl TraceLevel) ProviderOption
WithLevel specifies a maximum level consumer is interested in. Higher levels imply that you get lower levels as well. For example, with TRACE_LEVEL_ERROR you'll get all events except ones with level critical.
func WithMatchKeywords ¶
func WithMatchKeywords(anyKeyword, allKeyword uint64) ProviderOption
WithMatchKeywords allows to specify keywords of receiving events. Each event has a set of keywords associated with it. That keywords are encoded as bit masks and matched with provided @anyKeyword and @allKeyword values.
A session will receive only those events whose keywords masks has ANY of @anyKeyword and ALL of @allKeyword bits sets.
For more info take a look a ProviderOptions docs. To query keywords defined by specific provider identified by <GUID> try:
logman query providers <GUID>
func WithProperty ¶
func WithProperty(p EnableProperty) ProviderOption
WithProperty enables additional provider feature toggled by @p. Subsequent WithProperty options will enable all provided options.
For more info about available properties check EnableProperty doc and original API reference: https://docs.microsoft.com/en-us/windows/win32/api/evntrace/ns-evntrace-enable_trace_parameters
func WithRundown ¶
func WithRundown(withRundown bool) ProviderOption
WithRundown requests a rundown of the current provider state when the provider is added.
type ProviderOptions ¶
type ProviderOptions struct { // Level represents provider-defined value that specifies the level of // detail included in the event. Higher levels imply that you get lower // levels as well. For example, with TRACE_LEVEL_ERROR you'll get all // events except ones with level critical. Check `EventDescriptor.Level` // values for current event verbosity level. Level TraceLevel // MatchAnyKeyword is a bitmask of keywords that determine the category of // events that you want the provider to write. The provider writes the // event if any of the event's keyword bits match any of the bits set in // this mask. // // If MatchAnyKeyword is not set the session will receive ALL possible // events (which is equivalent setting all 64 bits to 1). // // Passed as is to EnableTraceEx2. Refer to its remarks for more info: // https://docs.microsoft.com/en-us/windows/win32/api/evntrace/nf-evntrace-enabletraceex2#remarks MatchAnyKeyword uint64 // MatchAllKeyword is an optional bitmask that further restricts the // category of events that you want the provider to write. If the event's // keyword meets the MatchAnyKeyword condition, the provider will write the // event only if all of the bits in this mask exist in the event's keyword. // // This mask is not used if MatchAnyKeyword is zero. // // Passed as is to EnableTraceEx2. Refer to its remarks for more info: // https://docs.microsoft.com/en-us/windows/win32/api/evntrace/nf-evntrace-enabletraceex2#remarks MatchAllKeyword uint64 // EnableProperties defines a set of provider properties consumer wants to // enable. Properties adds fields to ExtendedEventInfo or asks provider to // sent more events. // // For more info about available properties check EnableProperty doc and // original API reference: // https://docs.microsoft.com/en-us/windows/win32/api/evntrace/ns-evntrace-enable_trace_parameters EnableProperties []EnableProperty // Filters defines a set of filters that limit the events which are sent by the provider. // For a full list of possible filters, see here: // https://docs.microsoft.com/en-us/windows/win32/api/evntprov/ns-evntprov-event_filter_descriptor // If multiple Filters with the same filter type are specified, they are merged; check the filter // type on what can be merged. Filters []EventFilter // TriggerRundown requests a log of the provider's state information. This typically causes a number // of rundown events to be sent at the provider's start. TriggerRundown bool // Ignore any event map information that might have to be parsed from the provider manifest. // This can speed up event formatting considerably, but enums or bit maps will no longer // be formatted. IgnoreMapInfo bool }
ProviderOptions describes subscription options for a single provider.
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Session represents a Windows event tracing session that is ready to start events processing. Session subscribes to the given ETW provider only on `.Process` call, so having a Session without `.Process` called should not affect OS performance.
Session should be closed via `.Close` call to free obtained OS resources even if `.Process` has never been called.
func NewSession ¶
func NewSession(options ...SessionOption) (*Session, error)
NewSession creates a Windows event tracing session instance. Session with no options provided is a usable session, but it could be a bit noisy. It's recommended to refine the session with level and match keywords options to get rid of unnecessary events.
You MUST call `.Close` on session after use to clear associated resources, otherwise it will leak in OS internals until system reboot.
func NewSessionNoCreate ¶
func NewSessionNoCreate(options ...SessionOption) *Session
NewSessionNoCreate will return a new session without trying to create it
You MUST call `.Close` on session after use to clear associated resources, otherwise it will leak in OS internals until system reboot.
func (*Session) AddProvider ¶
func (s *Session) AddProvider(providerGUID windows.GUID, options ...ProviderOption) error
AddProvider adds a provider to the session. This can also be used to change subscription parameters.
func (*Session) Process ¶
func (s *Session) Process(cb EventCallback) error
Process starts processing of ETW events. Events will be passed to @cb synchronously and sequentially. Take a look to EventCallback documentation for more info about events processing.
N.B. Process blocks until `.Close` being called!
func (*Session) Stat ¶
func (s *Session) Stat() (SessionStatistics, error)
Stat queries runtime information about the session.
func (*Session) Update ¶
func (s *Session) Update(options ...SessionOption) error
Update updates the session options with the new options. It is not possible to update the name of a session. Changing log file modes may also fail.
type SessionOption ¶
type SessionOption func(cfg *SessionOptions)
SessionOption is any function that modifies SessionOptions. Options will be called on default config in NewSession. Subsequent options that modifies same fields will override each other.
func EnableFlags ¶
func EnableFlags(flags ...EnableFlag) SessionOption
EnableFlags enables specific flags that specify which events to receive from a kernel session. This option is ignored for non-kernel sessions.
func EnableLogModes ¶
func EnableLogModes(modes ...LogFileMode) SessionOption
EnableLogModes sets flags that specify properties of the session.
func IgnoreMapInfo ¶
func IgnoreMapInfo(ignoreMapInfo bool) SessionOption
IgnoreMapInfo specifies whether event map information should be processed. SessionOptions.IgnoreMapInfo has further information on this.
func WithName ¶
func WithName(name string) SessionOption
WithName specifies a provided @name for the creating session. Further that session could be controlled from other processed by it's name, so it should be unique.
type SessionOptions ¶
type SessionOptions struct { // Name specifies a name of ETW session being created. Further a session // could be controlled from other processed by it's name, so it should be // unique. Name string // Ignore any event map information that might have to be parsed from the provider manifest. // This can speed up event formatting considerably, but enums or bit maps will no longer // be formatted. IgnoreMapInfo bool // Flags to enable on the session. This is only meaningful for a kernel session. Flags []EnableFlag LogFileModes []LogFileMode Kernel bool }
SessionOptions describes Session subscription options.
Most of options will be passed to EnableTraceEx2 and could be refined in its docs: https://docs.microsoft.com/en-us/windows/win32/api/evntrace/nf-evntrace-enabletraceex2
type SessionStatistics ¶
type TraceLevel ¶
type TraceLevel uint8
TraceLevel represents provider-defined value that specifies the level of detail included in the event. Higher levels imply that you get lower levels as well.