Macro tracelogging::write_event
source · write_event!() { /* proc-macro */ }
Expand description
Sends an event to ETW via the specified provider.
write_event!(PROVIDER_SYMBOL, "EventName", options and fields...);
level(Verbose)
keyword(0x123)
opcode(Info)
activity_id(&guid)
related_id(&guid)
task(24)
tag(0x123)
id_version(23, 0)
channel(TraceLogging)
debug()
u32("FieldName", &int_val)
u32_slice("FieldName", &int_vals[..])
str8("FieldName", str_val)
str8_json("FieldName", json_str_val)
struct("FieldName", { str8("NestedField", str_val), ... })
- and many more…
Overview
The write_event
macro creates a TraceLogging-encoded event and sends it to ETW
(Event Tracing for Windows) using a Provider that was created by
define_provider!
.
You can think of write_event!(MY_PROVIDER, "EventName", options and fields...)
as expanding to code that is something like the following:
if !MY_PROVIDER.enabled(event_level, event_keyword) {
0
} else {
EventWriteTransfer(MY_PROVIDER, options and fields...)
}
The PROVIDER_SYMBOL
generated by define_provider!
should be treated as a token,
not a variable. When invoking write_event!
, use the original symbol, not a
reference or alias.
Note: The field value expressions are evaluated and the event is sent to ETW only if the event is enabled, i.e. only if one or more ETW logging sessions are listening to the provider with filters that include the level and keyword of the event.
The write_event!
macro returns a u32
value with a Win32 result code. If no ETW
logging sessions are listening for the event, write_event!
immediately returns 0
(ERROR_SUCCESS
). Otherwise, it returns the value returned by the underlying Windows
EventWriteTransfer
API. Since most components treat logging APIs as fire-and-forget, this value should
normally be ignored in production code. It is generally used only for debugging and
troubleshooting.
Limitations
ETW is optimized for efficient handling of small events. ETW events have the following limits:
- If the total event size (including ETW headers, provider name string, event name string, field name strings, and event data) exceeds 64KB, the event will not be delivered to any sessions.
- If the total event size exceeds the buffer size of a logger session, the event will not be delivered to that session.
- If the event contains more than 128 chunks of data, ETW will not be able to process
the event. The
write_event
macro uses one chunk for every simple field and two chunks for complex fields (binary, string, and slice fields).write_event!
will generate a compile error if it needs more than 128 chunks. You might be able to work around this limitation by merging multiple fields into one chunk using raw field types. - If the event contains more than 128 fields, the Windows Trace Decoding Helper
(TDH) library will be unable to decode the event. A field is anything with a
“FieldName”.
write_event!
will generate a compile error if your event has more than 128 fields. You might be able to work around this limitation by using arrays or by logging a series of simpler events instead of a single complex event. - If a struct contains more than 127 fields, the TraceLogging encoding will be unable
to represent the event. A field is anything with a “FieldName”. The
write_event
macro will generate a compile error if a struct has more than 127 fields. You might be able to work around this limitation by using arrays or by logging a series of simpler events instead of a single complex event.
Example
use tracelogging as tlg;
tlg::define_provider!(MY_PROVIDER, "MyCompany.MyComponent");
// Safety: If this is a DLL, you MUST call MY_PROVIDER.unregister() before unload.
unsafe { MY_PROVIDER.register(); }
let message = "We're low on ice cream.";
tlg::write_event!(
MY_PROVIDER,
"MyWarningEvent",
level(Warning),
str8("MyFieldName", message),
);
MY_PROVIDER.unregister();
Syntax
write_event!(PROVIDER_SYMBOL, "EventName", options and fields...);
Required parameters
-
PROVIDER_SYMBOL
The symbol for the provider that will be used for sending the event to ETW. This is a symbol that was created by
define_provider!
.This should be the original symbol name created by
define_provider!
, not a reference or alias. -
"EventName"
A string literal that specifies a short human-readable name for the event. The name will be included in the event and will be a primary attribute for event identification. It should be unique so that the resulting events will not be confused with other events in the same provider.
Options
-
level(event_level)
Specifies the level (severity) of the event.
Level is important for event filtering so all events should specify a meaningful non-zero level.
If the
level
option is not specified then the event’s level will be Level::Verbose. If the level is specified it must be a constant Level value. -
keyword(event_keyword)
Specifies the keyword (category bits) of the event.
The keyword is a 64-bit value where each bit in the keyword corresponds to a provider-defined category. For example, the “MyCompany.MyComponent” provider might define keyword bit
0x2
to indicate that the event is part of a “networking” event category. In that case, any event in that provider with the0x2
bit set in the keyword is considered as belonging to the “networking” category.Keyword is important for event filtering so all events should specify a meaningful non-zero keyword.
If no
keyword
options are specified then the event’s keyword will be0x1
to flag the event as not having any assigned keyword. If thekeyword
option is specified it must be a constantu64
value. Thekeyword
option may be specified more than once, in which case all provided keyword values will be OR’ed together in the event’s keyword. -
opcode(event_opcode)
Specifies the opcode attribute for the event.
The opcode indicates special event semantics such as “activity start” or “activity stop” that can be used by the event decoder to group events together.
If the
opcode
option is not specified the event’s opcode will be Opcode::Info, indicating no special semantics. If the opcode is specified it must be a constant Opcode value. -
activity_id(&guid)
Specifies the activity id to use for the event.
If not specified, the event will use the current thread’s thread-local activity id. If specified, the value must be a reference to a Guid.
-
related_id(&guid)
Specifies the related activity id to use for the event.
This value is normally set for the activity-start event to record the parent activity of the newly-started activity. This is normally left unset for other events.
If not specified, the event will not have any related activity id. If specified, the value must be a reference to a Guid.
-
task(event_task)
Specifies the task attribute for the event.
Task is a 16-bit value with provider-defined semantics. Task is typically used to indicate semantic event identity, with one or more events using a particular task value to indicate that the event has the specified semantics. For example, task
47
might be assigned semantics “Packet Sent”, and then the “IPv4-Packet-Sent” and “IPv6-Packet-Sent” events might both be set to use task47
.If the
task
option is not specified then the event’s task will be 0. If the task is specified it must be a constantu16
value. -
tag(event_tag)
Specifies the tag to use for the event.
A tag is a 28-bit provider-defined value that is available when the event is decoded. The tag’s semantics are provider-defined, e.g. the “MyCompany.MyComponent” provider might define tag value
0x1
to mean the event contains high-priority information. Most providers do not use tags so most events do not need to specify thetag
option.If the
tag
option is not specified the event’s tag will be 0. If specified, the tag must be a constantu32
value in the range 0 to 0x0FFFFFFF. -
id_version(event_id, event_version)
Specifies a manually-assigned numeric id for this event, along with a version that indicates changes in the event schema or semantics.
Most providers use the event name for event identification so most events do not need to specify the
id_version
option.The version should start at 0 and should be incremented each time a breaking change is made to the event, e.g. when a field is removed or a field changes type.
If the
id_version
option is not specified then the event’s id and version will be 0, indicating that no id has been assigned to the event. If id and version are specified, the id must be a constantu16
value and the version must be a constantu8
value. -
channel(event_channel)
Specifies the channel attribute for the event.
Most events use the default channel (TraceLogging) so most events do not need to specify the
channel
option.If the
channel
option is not specified the event’s channel will be Channel::TraceLogging. If the channel is specified it must be a constant Channel value. -
debug()
For non-production diagnostics: prints the expanded macro during compilation.
Fields
Event content is provided in fields. Each field is added to the event with a field type.
There are three categories of field types:
- Normal field types add a field to the event with a value such as an integer, float, string, slice of i32, etc.
- The struct field type adds a field to the event that contains a group of other fields.
- Raw field types directly add unchecked data (field content) and/or metadata (field name and type information) to the event. They are used in advanced scenarios to optimize event generation or to log complex data types that the other field categories cannot handle.
Normal fields
All normal fields have a type, a name, and a value reference. They may optionally specify a tag and/or a format.
Normal field syntax: TYPE("NAME", VALUE_REF, tag(TAG), format(FORMAT))
-
TYPE
controls the expected type of theVALUE_REF
expression, the ETW encoding that the field will use in the event, and default format that the field will have when it is decoded. TYPEs includeu32
,str8
,str16
,f32_slice
and many others. -
"NAME"
is a string literal that specifies the name of the field. -
VALUE_REF
is a Rust expression that provides a reference to the value of the field.Field types that expect a slice
&[T]
type will also accept types that implement theAsRef<[T]>
trait. For example, thestr8
field types expect a&[u8]
but will also accept&str
or&String
because those types implementAsRef<[u8]>
.The field value expression will be evaluated only if the event is enabled, i.e. only if at least one logging session is listening to the provider and has filtering that includes this event’s level and keyword.
-
tag(TAG)
specifies a 28-bit “field tag” with provider-defined semantics.This is usually omitted because most providers do not use field tags.
If not present, the field tag is
0
. If present, the TAG must be a 28-bit constantu32
value in the range0
to0x0FFFFFFF
. -
format(FORMAT)
specifies an OutType that overrides the format that would normally apply for the givenTYPE
.This is usually omitted because most valid formats are available without the use of the format option. For example, you could specify a
str8
type with aJson
format, but this is unnecessary because there is already astr8_json
type that has the same effect.If not present, the field’s format depends on the field’s
TYPE
. If present, the FORMAT must be a constant OutType value.
Example:
let message = "We're low on ice cream.";
tlg::write_event!(
MY_PROVIDER,
"MyWarningEvent",
level(Warning),
str8("MyField1", message), // No options (normal)
str8("MyField2", message, format(Json)), // Using the format option
str8("MyField3", message, tag(0x1234)), // Using the tag option
str8("MyField4", message, format(Json), tag(0x1234)), // Both options
);
Normal field types
Field Type | Rust Type | ETW Type |
---|---|---|
binary | &[u8] | Binary |
binaryc 1 | &[u8] | BinaryC |
bool8 | &bool | U8 + Boolean |
bool8_slice | &[bool] | U8 + Boolean |
bool32 | &i32 | Bool32 |
bool32_slice | &[i32] | Bool32 |
char8_cp1252 | &u8 | U8 + String |
char8_cp1252_slice | &[u8] | U8 + String |
char16 | &u16 | U16 + String |
char16_slice | &[u16] | U16 + String |
codepointer | &usize | HexSize + CodePointer |
codepointer_slice | &[usize] | HexSize + CodePointer |
cstr8 2 | &[u8] | CStr8 + Utf8 |
cstr8_cp1252 2 | &[u8] | CStr8 |
cstr8_json 2 | &[u8] | CStr8 + Json |
cstr8_xml 2 | &[u8] | CStr8 + Xml |
cstr16 2 | &[u16] | CStr16 |
cstr16_json 2 | &[u16] | CStr16 + Json |
cstr16_xml 2 | &[u16] | CStr16 + Xml |
f32 | &f32 | F32 |
f32_slice | &[f32] | F32 |
f64 | &f64 | F64 |
f64_slice | &[f64] | F64 |
guid | &tracelogging::Guid | Guid |
guid_slice | &[tracelogging::Guid] | Guid |
hresult | &i32 | I32 + HResult |
hresult_slice | &[i32] | I32 + HResult |
i8 | &i8 | I8 |
i8_slice | &[i8] | I8 |
i8_hex | &i8 | U8 + Hex |
i8_hex_slice | &[i8] | U8 + Hex |
i16 | &i16 | I16 |
i16_slice | &[i16] | I16 |
i16_hex | &i16 | U16 + Hex |
i16_hex_slice | &[i16] | U16 + Hex |
i32 | &i32 | I32 |
i32_slice | &[i32] | I32 |
i32_hex | &i32 | Hex32 |
i32_hex_slice | &[i32] | Hex32 |
i64 | &i64 | I64 |
i64_slice | &[i64] | I64 |
i64_hex | &i64 | Hex64 |
i64_hex_slice | &[i64] | Hex64 |
ipv4 | &[u8; 4] | U32 + IPv4 |
ipv4_slice | &[[u8; 4]] | U32 + IPv4 |
ipv6 | &[u8; 16] | Binary + IPv6 |
ipv6c 1 | &[u8; 16] | BinaryC + IPv6 |
isize | &isize | ISize |
isize_slice | &[isize] | ISize |
isize_hex | &isize | HexSize |
isize_hex_slice | &[isize] | HexSize |
pid | &u32 | U32 + Pid |
pid_slice | &[u32] | U32 + Pid |
pointer | &usize | HexSize |
pointer_slice | &[usize] | HexSize |
port | &u16 | U16 + Port |
port_slice | &[u16] | U16 + Port |
socketaddress | &[u8] | Binary + SocketAddress |
socketaddressc 1 | &[u8] | BinaryC + SocketAddress |
str8 | &[u8] | Str8 + Utf8 |
str8_cp1252 | &[u8] | Str8 |
str8_json | &[u8] | Str8 + Json |
str8_xml | &[u8] | Str8 + Xml |
str16 | &[u16] | Str16 |
str16_json | &[u16] | Str16 + Json |
str16_xml | &[u16] | Str16 + Xml |
systemtime 3 | &std::time::SystemTime | FileTime |
tid | &u32 | U32 + Tid |
tid_slice | &[u32] | U32 + Tid |
u8 | &u8 | U8 |
u8_slice | &[u8] | U8 |
u8_hex | &u8 | U8 + Hex |
u8_hex_slice | &[u8] | U8 + Hex |
u16 | &u16 | U16 |
u16_slice | &[u16] | U16 |
u16_hex | &u16 | U16 + Hex |
u16_hex_slice | &[u16] | U16 + Hex |
u32 | &u32 | U32 |
u32_slice | &[u32] | U32 |
u32_hex | &u32 | Hex32 |
u32_hex_slice | &[u32] | Hex32 |
u64 | &u64 | U64 |
u64_slice | &[u64] | U64 |
u64_hex | &u64 | Hex64 |
u64_hex_slice | &[u64] | Hex64 |
usize | &usize | USize |
usize_slice | &[usize] | USize |
usize_hex | &usize | HexSize |
usize_hex_slice | &[usize] | HexSize |
win_error | &u32 | U32 + Win32Error |
win_error_slice | &[u32] | U32 + Win32Error |
win_filetime | &i64 | FileTime |
win_filetime_slice | &[i64] | FileTime |
win_ntstatus | &i32 | Hex32 + NtStatus |
win_ntstatus_slice | &[i32] | Hex32 + NtStatus |
win_sid 4 | &[u8] | Sid |
win_systemtime | &[u16; 8] | SystemTime |
win_systemtime_slice | &[[u16; 8]] | SystemTime |
win_systemtime_utc | &[u16; 8] | SystemTime + DateTimeUtc |
win_systemtime_utc_slice | &[[u16; 8]] | SystemTime + DateTimeUtc |
Struct fields
A struct is a group of fields that are logically considered a single field.
Struct fields have type struct
, a name, and a set of nested fields enclosed in
braces { ... }
. They may optionally specify a tag.
Struct field syntax: struct("NAME", tag(TAG), { FIELDS... })
-
"NAME"
is a string literal that specifies the name of the field. -
tag(TAG)
specifies a 28-bit “field tag” with provider-defined semantics.This is usually omitted because most providers do not use field tags.
If not present, the field tag is
0
. If present, the TAG must be a 28-bit constantu32
value in the range0
to0x0FFFFFFF
. -
{ FIELDS... }
is a list of other fields that will be considered to be part of this field. This list may include normal fields, struct fields, and non-struct raw fields.
Example:
let message = "We're low on ice cream.";
tlg::write_event!(
MY_PROVIDER,
"MyWarningEvent",
level(Warning),
str8("RootField1", message),
str8("RootField2", message),
struct("RootField3", {
str8("MemberField1", message),
str8("MemberField2", message),
struct("MemberField3", tag(0x1234), {
str8("NestedField1", message),
str8("NestedField2", message),
}),
str8("MemberField4", message),
}),
str8("RootField4", message),
);
Raw fields
Advanced: In certain cases, you may need capabilities not directly exposed by the normal field types. For example,
- You might need to log an array of a variable-sized type, such as an array of string.
- You might need to log an array of struct.
- You might want to log several fields in one block of data to reduce overhead.
In these cases, you can use the raw field types. These types are harder to use than
the normal field types. Using these types incorrectly can result in events that
cannot be decoded. To use these types correctly, you must understand how
TraceLogging events are encoded. write_event!
does not verify that the provided
field types or field data are valid.
Note: ETW stores event data tightly-packed with no padding, alignment, or size. If your field data size does not match up with your field type, the remaining fields of the event will decode incorrectly, not just the mismatched field.
Each raw field type has unique syntax and capabilities. However, in all cases,
the format
and tag
options have the same significance as in normal fields and may
be omitted if not needed. If omitted, tag
defaults to 0
and format
defaults to
OutType::Default.
Raw field data is always specified as &[u8]
. The provided VALUE_BYTES must include
the entire field, including prefix (e.g. u16
byte count prefix required on
“Counted” fields like InType::Binary and InType::Str8) or suffix (e.g. '\0'
termination required on InType::CStr8 fields).
-
raw_field("NAME", INTYPE, VALUE_BYTES, format(FORMAT), tag(TAG))
The
raw_field
type allows you to add a field with direct control over the field’s contents. VALUE_BYTES is specified as&[u8]
and you can specify any InType. -
raw_field_slice("NAME", INTYPE, VALUE_BYTES, format(FORMAT), tag(TAG))
The
raw_field
type allows you to add a variable-sized array field with direct control over the field’s contents. VALUE_BYTES is specified as&[u8]
and you can specify any InType. Note that the provided VALUE_BYTES must include the entire array, including the array element count, which is au16
element count immediately before the field values. -
raw_meta("NAME", INTYPE, format(FORMAT), tag(TAG))
The
raw_meta
type allows you to add a field definition (name, intype, format, tag) without immediately adding the field’s data. This allows you to specify multipleraw_meta
fields and then provide the data for all of the fields via one or moreraw_data
fields before or after the correspondingraw_meta
fields. -
raw_meta_slice("NAME", INTYPE, format(FORMAT), tag(TAG))
The
raw_meta_slice
type allows you to add a variable-length array field definition (name, type, format, tag) without immediately adding the array’s data. This allows you to specify multipleraw_meta
fields and then provide the data for all of the fields via one or moreraw_data
fields (before or after the correspondingraw_meta
fields). -
raw_struct("NAME", FIELD_COUNT, tag(TAG))
The
raw_struct
type allows you to begin a struct and directly specify the number of fields in the struct. The struct’s member fields are specified separately (e.g. viaraw_meta
orraw_meta_slice
).Note that the FIELD_COUNT must be a constant
u8
value in the range 0 to 127. It indicates the number of subsequent logical fields that will be considered to be part of the struct. In cases of nested structs, a struct and its fields count as a single logical field. -
raw_struct_slice("NAME", FIELD_COUNT, tag(TAG))
The
raw_struct_slice
type allows you to begin a variable-length array-of-struct and directly specify the number of fields in the struct. The struct’s member fields are specified separately (e.g. viaraw_meta
orraw_meta_slice
).The number of elements in the array is specified as a
u16
value immediately before the array content.Note that the FIELD_COUNT must be a constant
u8
value in the range 0 to 127. It indicates the number of subsequent logical fields that will be considered to be part of the struct. In cases of nested structs, a struct and its fields count as a single logical field. -
raw_data(VALUE_BYTES)
The
raw_data
type allows you to add data to the event without specifying any field. This should be used together withraw_meta
orraw_meta_slice
fields, where theraw_meta
orraw_meta_slice
fields declare the field names and types and theraw_data
field(s) provide the corresponding data (including any array element counts).Note that TraceLogging events contain separate sections for metadata and data. The
raw_meta
fields add to the compile-time-constant metadata section and theraw_data
fields add to the runtime-variable data section. As a result, it doesn’t matter whether theraw_data
comes before or after the correspondingraw_meta
. In addition, you can use oneraw_data
to supply the data for any number of fields or you can use multipleraw_data
fields to supply the data for one field.
Example:
tlg::write_event!(MY_PROVIDER, "MyWarningEvent", level(Warning),
// Make a U8 + String field containing 1 byte of data.
raw_field("RawChar8", U8, &[65], format(String), tag(200)),
// Make a U8 + String array containing u16 array-count (3) followed by 3 bytes.
raw_field_slice("RawChar8s", U8, &[
3, 0, // RawChar8s.Length = 3
65, 66, 67, // RawChar8s content = [65, 66, 67]
]),
// Declare a U32 + Hex field, but don't provide the data yet.
raw_meta("RawHex32", U32, format(Hex)),
// Declare a U8 + Hex array, but don't provide the data yet.
raw_meta_slice("RawHex8s", U8, format(Hex)),
// Provide the data for the previously-declared fields:
raw_data(&[
255, 0, 0, 0, // RawHex32 = 255
3, 0, // RawHex8s.Length = 3
65, 66, 67]), // RawHex8s content = [65, 66, 67]
// Declare a struct with 2 fields. The next 2 logical fields in the event will be
// members of this struct.
raw_struct("RawStruct", 2),
// Type and data for first member of RawStruct.
raw_field("RawChar8", U8, &[65], format(String)),
// Type and data for second member of RawStruct.
raw_field_slice("RawChar8s", U8, &[3, 0, 65, 66, 67], format(String)),
// Declare a struct array with 2 fields.
raw_struct_slice("RawStructSlice", 2),
// Declare the first member of RawStructSlice. Type only (no data yet).
raw_meta("RawChar8", U8, format(String)),
// Declare the second member of RawStructSlice. Type only (no data yet).
raw_meta_slice("RawChar8s", U8, format(String)),
// Provide the data for the array of struct.
raw_data(&[
2, 0, // RawStructSlice.Length = 2
48, // RawStructSlice[0].RawChar8
3, 0, // RawStructSlice[0].RawChar8s.Length = 3
65, 66, 67, // RawStructSlice[0].RawChar8s content
49, // RawStructSlice[1].RawChar8
2, 0, // RawStructSlice[1].RawChar8s.Length = 2
48, 49, // RawStructSlice[1].RawChar8s content
]),
);
The
...
and...c
types are the same except that the...c
types use a newerInType::BinaryC
ETW encoding. TheBinaryC
encoding avoids the extraFieldName.Length
field that sometimes shows up forInType::Binary
fields. This new encoding requires updated decoder support so it may not work with older ETW decoding tools. ↩The
cstrN
types use a0
-terminatedInType::CStrN
string encoding in the event. If the provided field value contains any'\0'
characters then the event will include the value up to the first'\0'
; otherwise the event will include the entire value. There is a small runtime overhead for locating the first0
in the string. To avoid the overhead and to ensure you log your entire string (including any'\0'
characters), prefer thestr
types (counted strings) over thecstr
types (0
-terminated strings) unless you specifically need a0
-terminated ETW encoding. ↩When logging
systemtime
types,write_event!
will convert the providedstd::time::SystemTime
value into a Win32FILETIME
, saturating if the value is out of the range thatFileTimeToSystemTime
can handle: if theSystemTime
value is a date before 1601, the loggedFILETIME
value will be the start of 1601, and if theSystemTime
value is a date after 30827, the loggedFILETIME
value will be the end of 30827. ↩The
win_sid
type requires an input byte-slice value that is at leastGetSidLength(value_bytes)
=value_bytes[1] * 4 + 8
bytes long.write_event!
will panic if the value is smaller than that size. ↩