write_event!() { /* proc-macro */ }
Expand description

Sends an event to user_events via the specified provider.

write_event!(PROVIDER_SYMBOL, "EventName", options and fields...);

Options:

  • level(Verbose)
  • keyword(0x123)
  • opcode(Info)
  • activity_id(&guid)
  • related_id(&guid)
  • tag(0x123)
  • id_version(23, 0)
  • debug()

Fields:

  • 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 an eventheader-encoded event and sends it to user_events 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) {
    9 // EBADF
} else {
    writev(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 user_events only if the event is enabled, i.e. only if one or more perf 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 an errno result code. If no logging sessions are listening for the event, write_event! immediately returns EBADF (9). Otherwise, it returns the value returned by the underlying writev 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

The Linux perf system is optimized for efficient handling of small events. Events have the following limits:

  • If the total event size (including 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 a struct contains more than 127 fields, the eventheader 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 eventheader as eh;

eh::define_provider!(MY_PROVIDER, "MyCompany_MyComponent");

// Safety: If this is a shared object, you MUST call MY_PROVIDER.unregister() before unload.
unsafe { MY_PROVIDER.register(); }

let message = "We're low on ice cream.";
eh::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 user_events. 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 the 0x2 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 be 0x1 to flag the event as not having any assigned keyword. If the keyword option is specified it must be a constant u64 value. The keyword 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 not have any activity id. If specified, the value must be a reference to a Guid or a reference to a [u8; 16].

  • 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 or a reference to a [u8; 16].

  • tag(event_tag)

    Specifies the tag to use for the event.

    A tag is a 16-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 the tag option.

    If the tag option is not specified the event’s tag will be 0. If specified, the tag must be a constant u16 value.

  • 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 constant u16 value and the version must be a constant u8 value.

  • debug()

    For non-production diagnostics: prints the expanded macro during compilation.

  • For compability with the tracelogging crate, certain other options may be accepted and ignored.

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 the VALUE_REF expression, the eventheader encoding that the field will use in the event, and default format that the field will have when it is decoded. TYPEs include u32, 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 the AsRef<[T]> trait. For example, the str8 field types expect a &[u8] but will also accept &str or &String because those types implement AsRef<[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 16-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 16-bit constant u16 value.

  • format(FORMAT) specifies an FieldFormat that overrides the format that would normally apply for the given TYPE.

    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 a StringJson format, but this is unnecessary because there is already a str8_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 FieldFormat value.

Example:

let message = "We're low on ice cream.";
eh::write_event!(
    MY_PROVIDER,
    "MyWarningEvent",
    level(Warning),
    str8("MyField1", message),                     // No options (normal)
    str8("MyField2", message, format(StringJson)), // Using the format option
    str8("MyField3", message, tag(0x1234)),        // Using the tag option
    str8("MyField4", message, format(StringJson), tag(0x1234)), // Both options
);

Normal field types

Field TypeRust TypeEventHeader Type
binary&[u8]StringLength16Char8 + HexBytes
binaryc&[u8]StringLength16Char8 + HexBytes
bool8&boolValue8 + Boolean
bool8_slice&[bool]Value8 + Boolean
bool32&i32Value32 + Boolean
bool32_slice&[i32]Value32 + Boolean
char8_cp1252&u8Value8 + String8
char8_cp1252_slice&[u8]Value8 + String8
char16&u16Value16 + StringUtf
char16_slice&[u16]Value16 + StringUtf
codepointer&usizeValueSize + HexInt
codepointer_slice&[usize]ValueSize + HexInt
cstr8 1&[u8]ZStringChar8
cstr8_cp1252 1&[u8]ZStringChar8 + String8
cstr8_json 1&[u8]ZStringChar8 + StringJson
cstr8_xml 1&[u8]ZStringChar8 + StringXml
cstr16 1&[u16]ZStringChar16
cstr16_json 1&[u16]ZStringChar16 + StringJson
cstr16_xml 1&[u16]ZStringChar16 + StringXml
cstr32 1&[u32]ZStringChar32
cstr32_json 1&[u32]ZStringChar32 + StringJson
cstr32_xml 1&[u32]ZStringChar32 + StringXml
errno 2&i32Value32 + Errno
errno_slice 2&[i32]Value32 + Errno
f32&f32Value32 + Float
f32_slice&[f32]Value32 + Float
f64&f64Value64 + Float
f64_slice&[f64]Value64 + Float
guid&eventheader::GuidValue128 + Uuid
guid_slice&[eventheader::Guid]Value128 + Uuid
hresult&i32Value32 + HexInt
hresult_slice&[i32]Value32 + HexInt
i8&i8Value8 + SignedInt
i8_slice&[i8]Value8 + SignedInt
i8_hex&i8Value8 + HexInt
i8_hex_slice&[i8]Value8 + HexInt
i16&i16Value16 + SignedInt
i16_slice&[i16]Value16 + SignedInt
i16_hex&i16Value16 + HexInt
i16_hex_slice&[i16]Value16 + HexInt
i32&i32Value32 + SignedInt
i32_slice&[i32]Value32 + SignedInt
i32_hex&i32Value32 + HexInt
i32_hex_slice&[i32]Value32 + HexInt
i64&i64Value64 + SignedInt
i64_slice&[i64]Value64 + SignedInt
i64_hex&i64Value64 + HexInt
i64_hex_slice&[i64]Value64 + HexInt
ipv4&[u8; 4]Value32 + IPv4
ipv4_slice&[[u8; 4]]Value32 + IPv4
ipv6&[u8; 16]Value128 + IPv6
ipv6c&[u8; 16]Value128 + IPv6
isize&isizeValueSize + SignedInt
isize_slice&[isize]ValueSize + SignedInt
isize_hex&isizeValueSize + HexInt
isize_hex_slice&[isize]ValueSize + HexInt
pid&u32Value32 + Pid
pid_slice&[u32]Value32 + Pid
pointer&usizeValueSize + HexInt
pointer_slice&[usize]ValueSize + HexInt
port&u16Value16 + Port
port_slice&[u16]Value16 + Port
socketaddress&[u8]StringLength16Char8 + HexBytes
socketaddressc&[u8]StringLength16Char8 + HexBytes
str8&[u8]StringLength16Char8
str8_cp1252&[u8]StringLength16Char8 + String8
str8_json&[u8]StringLength16Char8 + StringJson
str8_xml&[u8]StringLength16Char8 + StringXml
str16&[u16]StringLength16Char16
str16_json&[u16]StringLength16Char16 + StringJson
str16_xml&[u16]StringLength16Char16 + StringXml
str32&[u32]StringLength16Char32
str32_json&[u32]StringLength16Char32 + StringJson
str32_xml&[u32]StringLength16Char32 + StringXml
systemtime 3&std::time::SystemTimeValue64 + Time
tid&u32Value32 + Pid
tid_slice&[u32]Value32 + Pid
time32&i32Value32 + Time
time64&i64Value64 + Time
u8&u8Value8
u8_slice&[u8]Value8
u8_hex&u8Value8 + HexInt
u8_hex_slice&[u8]Value8 + HexInt
u16&u16Value16
u16_slice&[u16]Value16
u16_hex&u16Value16 + HexInt
u16_hex_slice&[u16]Value16 + HexInt
u32&u32Value32
u32_slice&[u32]Value32
u32_hex&u32Value32 + HexInt
u32_hex_slice&[u32]Value32 + HexInt
u64&u64Value64
u64_slice&[u64]Value64
u64_hex&u64Value64 + HexInt
u64_hex_slice&[u64]Value64 + HexInt
usize&usizeValueSize
usize_slice&[usize]ValueSize
usize_hex&usizeValueSize + HexInt
usize_hex_slice&[usize]ValueSize + HexInt

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 16-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 16-bit constant u16 value.

  • { 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.";
eh::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 eventheader events are encoded. write_event! does not verify that the provided field types or field data are valid.

Note: eventheader 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 FieldFormat::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 “Length16” fields like FieldEncoding::StringLength16Char8 and FieldEncoding::StringLength16Char16) or suffix (e.g. '\0' termination required on FieldEncoding::ZStringChar8 fields).

  • raw_field("NAME", ENCODING, 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 FieldEncoding.

  • raw_field_slice("NAME", ENCODING, 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 FieldEncoding. Note that the provided VALUE_BYTES must include the entire array, including the array element count, which is a u16 element count immediately before the field values.

  • raw_meta("NAME", ENCODING, format(FORMAT), tag(TAG))

    The raw_meta type allows you to add a field definition (name, encoding, format, tag) without immediately adding the field’s data. This allows you to specify multiple raw_meta fields and then provide the data for all of the fields via one or more raw_data fields before or after the corresponding raw_meta fields.

  • raw_meta_slice("NAME", ENCODING, 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 multiple raw_meta fields and then provide the data for all of the fields via one or more raw_data fields (before or after the corresponding raw_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. via raw_meta or raw_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. via raw_meta or raw_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 with raw_meta or raw_meta_slice fields, where the raw_meta or raw_meta_slice fields declare the field names and types and the raw_data field(s) provide the corresponding data (including any array element counts).

    Note that eventheader events contain separate sections for metadata and data. The raw_meta fields add to the compile-time-constant metadata section and the raw_data fields add to the runtime-variable data section. As a result, it doesn’t matter whether the raw_data comes before or after the corresponding raw_meta. In addition, you can use one raw_data to supply the data for any number of fields or you can use multiple raw_data fields to supply the data for one field.

Example:

eh::write_event!(MY_PROVIDER, "MyWarningEvent", level(Warning),

    // Make a Value8 + String8 field containing 1 byte of data.
    raw_field("RawChar8", Value8, &[65], format(String8), tag(200)),

    // Make a Value8 + String8 array containing u16 array-count (3) followed by 3 bytes.
    raw_field_slice("RawChar8s", Value8, &[
        3, 0,       // RawChar8s.Length = 3
        65, 66, 67, // RawChar8s content = [65, 66, 67]
    ], format(String8)),

    // Declare a Value32 + HexInt field, but don't provide the data yet.
    raw_meta("RawHex32", Value32, format(HexInt)),

    // Declare a Value8 + HexInt array, but don't provide the data yet.
    raw_meta_slice("RawHex8s", Value8, format(HexInt)),

    // 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", Value8, &[65], format(String8)),

        // Type and data for second member of RawStruct.
        raw_field_slice("RawChar8s", Value8, &[3, 0, 65, 66, 67], format(String8)),

    // 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", Value8, format(String8)),

        // Declare the second member of RawStructSlice. Type only (no data yet).
        raw_meta_slice("RawChar8s", Value8, format(String8)),

    // 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
    ]),
);

  1. The cstrN types use a 0-terminated 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 first 0 in the string. To avoid the overhead and to ensure you log your entire string (including any '\0' characters), prefer the str types (counted strings) over the cstr types (0-terminated strings) unless you specifically need a 0-terminated event encoding. 

  2. The errno type is intended for use with C-style errno error codes. 

  3. When logging systemtime types, write_event! will convert the provided std::time::SystemTime value into a time64_t value containing the number of seconds since 1970, rounding down to the nearest second.