Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp5.0</TargetFramework>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ namespace Demo2
enum MyColor { Red, Yellow, Blue };

[EventSource(Name = "MyCompany")]
class MyCompanyEventSource : EventSource
sealed class MyCompanyEventSource : EventSource
{
//<Snippet2>
//<Snippet3>
public class Keywords
public static class Keywords
{
public const EventKeywords Page = (EventKeywords)1;
public const EventKeywords DataBase = (EventKeywords)2;
Expand All @@ -21,7 +21,7 @@ public class Keywords
//</Snippet3>

//<Snippet4>
public class Tasks
public static class Tasks
{
public const EventTask Page = (EventTask)1;
public const EventTask DBQuery = (EventTask)2;
Expand Down
199 changes: 199 additions & 0 deletions samples/snippets/csharp/VS_Snippets_CLR/etwtracelarge/cs/program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
//<root>
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;

namespace Demo
{
//<InterfaceSource>
public interface IMyLogging
{
void Error(int errorCode, string message);
void Warning(string message);
}

public sealed class MySource : EventSource, IMyLogging
{
public static MySource Log = new();

[Event(1)]
public void Error(int errorCode, string message) => WriteEvent(1, errorCode, message);

[Event(2)]
public void Warning(string message) => WriteEvent(2, message);
}
//</InterfaceSource>

//<UtilitySource>
public abstract class UtilBaseEventSource : EventSource
{
protected UtilBaseEventSource()
: base()
{ }

protected UtilBaseEventSource(bool throwOnEventWriteErrors)
: base(throwOnEventWriteErrors)
{ }

// helper overload of WriteEvent for optimizing writing an event containing
// payload properties that don't align with a provided overload. This prevents
// EventSource from using the object[] overload which is expensive.
protected unsafe void WriteEvent(int eventId, int arg1, short arg2, long arg3)
{
if (IsEnabled())
{
EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
descrs[0] = new EventData { DataPointer = (IntPtr)(&arg1), Size = 4 };
Copy link
Member

@hoyosjs hoyosjs Sep 7, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a safe thing to do in a sample? Here you are getting them from args only on primitives, which makes it OK. Do we have good guidance around fields of classes for things like strings and other ref types?

Copy link
Contributor Author

@josalem josalem Sep 7, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Event methods on EventSource must call WriteEvent and their parameters must match. An exception will be thrown if the event method's parameter list doesn't match the parameter list of the WriteEvent overload used. This code is adding an overload of WriteEvent that knows how to quickly write a payload of int, short, long which isn't a pre-written overload.

The EventData struct can only contain types that are capable of being represented with EventSource metadata:

// A Valid type to log to an EventSource include
//   * Primitive data types
//   * IEnumerable<T> of valid types T (this include arrays)  (* New for V4.6)
//   * Explicitly Opted in class or struct with public property Getters over Valid types.  (* New for V4.6)

EventSource derives its metadata from the parameter list of the event method which must match the call to WriteEvent.

In other words, you can only do this optimization with strings and primitive types. You could theoretically write something like this though:

public class MyType
{
	public string Foo { get; set; }
	public int Bar { get; set; }
	public long Baz { get; set; }
}

public abstract class UtilSource : EventSource
{
	protected UtilSource() : base () { }
	protected UtilSource(bool throwOnEventWriteErrors) : base(throwOnEventWriteErrors) { }

	protected unsafe void WriteEvent(int eventId, string arg1, int arg2, long arg3)
	{
		if (IsEnabled())
		{
			fixed (char* _arg1 = arg1 ?? string.Empty)
			{
				EventSource.EventData* descrs = stackalloc EventSource.EventData[3];
				descrs[0] = new EventData { DataPointer = (IntPtr)(_arg1), Size = ((arg1?.Length ?? 0) + 1) * 2 };
				descrs[1] = new EventData { DataPointer = (IntPtr)(&arg2), Size = 4 };
				descrs[2] = new EventData { DataPointer = (IntPtr)(&arg3), Size = 8 };
				WriteEventCore(eventId, descrs);
			}
		}
	}
}

public sealed MySource : UtilSource
{
	public static MySource Log = new();

	[NonEvent]
	public void LogThing(MyType thing) => DumpMyType(thing.Foo, thing.Bar, thing.Baz);

	[Event(1)]
	public void DumpMyType(string arg1, int arg2, long arg3) => WriteEvent(1, arg1, arg2, arg3);
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly what I meant: should the sample show to save pointers for things that are not safe to assume pinned (strings and other things adhering to the third point of "opted in", including value types that live in the heap like boxed and embedded types). Exactly like the example you have or something like CounterPayload since this is an advanced scenario type of thing.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can't really do this optimization with anything reference typed besides strings and you need to have the fixed scope surround your call to WriteEventCore or you will run into issues.

The "opted in" option is a reference to types decorated with EventDataAttribute which only applies to the Write<T> API which can't be optimized like this.

descrs[1] = new EventData { DataPointer = (IntPtr)(&arg2), Size = 2 };
descrs[2] = new EventData { DataPointer = (IntPtr)(&arg3), Size = 8 };
WriteEventCore(eventId, 3, descrs);
}
}
}

public sealed class OptimizedEventSource : UtilBaseEventSource
{
public static OptimizedEventSource Log = new();

public static class Keywords
{
public const EventKeywords Kwd1 = (EventKeywords)1;
}

[Event(1, Keywords = Keywords.Kwd1, Level = EventLevel.Informational, Message = "LogElements called {0}/{1}/{2}.")]
public void LogElements(int n, short sh, long l) => WriteEvent(1, n, sh, l); // uses the overload we added!
}
//</UtilitySource>

//<ComplexSource>
public class ComplexComponent : IDisposable
{
internal static Dictionary<string,string> _internalState = new();

private string _name;

public ComplexComponent(string name)
{
_name = name ?? throw new ArgumentNullException(nameof(name));
ComplexSource.Log.NewComponent(_name);
}

public void SetState(string key, string value)
{
lock (_internalState)
{
_internalState[key] = value;
ComplexSource.Log.SetState(_name, key, value);
}
}

private void ExpensiveWork1() => System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(250));
private void ExpensiveWork2() => System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(250));
private void ExpensiveWork3() => System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(250));
private void ExpensiveWork4() => System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(250));

public void DoWork()
{
ComplexSource.Log.ExpensiveWorkStart(_name);

ExpensiveWork1();
ExpensiveWork2();
ExpensiveWork3();
ExpensiveWork4();

ComplexSource.Log.ExpensiveWorkStop(_name);
}

public void Dispose()
{
ComplexSource.Log.ComponentDisposed(_name);
}
}

internal sealed class ComplexSource : EventSource
{
public static ComplexSource Log = new();

public static class Keywords
{
public const EventKeywords ComponentLifespan = (EventKeywords)1;
public const EventKeywords StateChanges = (EventKeywords)(1 << 1);
public const EventKeywords Performance = (EventKeywords)(1 << 2);
public const EventKeywords DumpState = (EventKeywords)(1 << 3);
// a utility keyword for a common combination of keywords users might enable
public const EventKeywords StateTracking = ComponentLifespan & StateChanges & DumpState;
}

protected override void OnEventCommand(EventCommandEventArgs args)
{
base.OnEventCommand(args);

if (args.Command == EventCommand.Enable)
{
DumpComponentState();
}
}

[Event(1, Keywords = Keywords.ComponentLifespan, Message = "New component with name '{0}'.")]
public void NewComponent(string name) => WriteEvent(1, name);

[Event(2, Keywords = Keywords.ComponentLifespan, Message = "Component with name '{0}' disposed.")]
public void ComponentDisposed(string name) => WriteEvent(2, name);

[Event(3, Keywords = Keywords.StateChanges)]
public void SetState(string name, string key, string value) => WriteEvent(3, name, key, value);

[Event(4, Keywords = Keywords.Performance)]
public void ExpensiveWorkStart(string name) => WriteEvent(4, name);

[Event(5, Keywords = Keywords.Performance)]
public void ExpensiveWorkStop(string name) => WriteEvent(5, name);

[Event(6, Keywords = Keywords.DumpState)]
public void ComponentState(string key, string value) => WriteEvent(6, key, value);

[NonEvent]
public void DumpComponentState()
{
if (IsEnabled(EventLevel.Informational, Keywords.DumpState))
{
lock (ComplexComponent._internalState)
{
foreach (var (key, value) in ComplexComponent._internalState)
ComponentState(key, value);
}
}
}
}
//</ComplexSource>

//<Main>
class Program
{
static void Main(string[] args)
{
Console.WriteLine($"PID: {System.Diagnostics.Process.GetCurrentProcess().Id}");

long i = 0;
while (true)
{
using ComplexComponent c1 = new($"COMPONENT_{i++}");
using ComplexComponent c2 = new($"COMPONENT_{i++}");
using ComplexComponent c3 = new($"COMPONENT_{i++}");
using ComplexComponent c4 = new($"COMPONENT_{i++}");

c1.SetState("key1", "value1");
c2.SetState("key2", "value2");
c3.SetState("key3", "value3");
c4.SetState("key4", "value4");

c1.DoWork();
c2.DoWork();
c3.DoWork();
c4.DoWork();
}
}
}
//</Main>
}
//</root>
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp5.0</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp5.0</TargetFramework>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
namespace Demo1
{
//<Snippet2>
class MyCompanyEventSource : EventSource
sealed class MyCompanyEventSource : EventSource
{
public static MyCompanyEventSource Log = new MyCompanyEventSource();

Expand Down
70 changes: 51 additions & 19 deletions xml/System.Diagnostics.Tracing/EventSource.xml
Original file line number Diff line number Diff line change
Expand Up @@ -49,29 +49,39 @@
</Attribute>
</Attributes>
<Docs>
<summary>Provides the ability to create events for event tracing for Windows (ETW).</summary>
<summary>Provides the ability to create events for event tracing across platforms.</summary>
<remarks>
<format type="text/markdown"><![CDATA[

## Remarks
This class is intended to be inherited by a user class that provides specific events to be used for ETW. The <xref:System.Diagnostics.Tracing.EventSource.WriteEvent%2A?displayProperty=nameWithType> methods are called to log the events.
This class is intended to be inherited by a user class that provides specific events to be used for event tracing. The <xref:System.Diagnostics.Tracing.EventSource.WriteEvent%2A?displayProperty=nameWithType> methods are called to log the events.

> [!IMPORTANT]
> This type implements the <xref:System.IDisposable> interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its <xref:System.IDisposable.Dispose%2A> method in a `try`/`catch` block. To dispose of it indirectly, use a language construct such as `using` (in C#) or `Using` (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the <xref:System.IDisposable> interface topic.

The basic functionality of <xref:System.Diagnostics.Tracing.EventSource> is sufficient for most applications. If you want more control over the ETW manifest that is created, you can apply the <xref:System.Diagnostics.Tracing.EventAttribute> attribute to the methods. For advanced event source applications, it is possible to intercept the commands being sent to the derived event source and change the filtering, or to cause actions (such as dumping a data structure) to be performed by the inheritor. An event source can be activated with Windows ETW controllers, such as the Logman tool, immediately. It is also possible to programmatically control and intercept the data dispatcher. The <xref:System.Diagnostics.Tracing.EventListener> class provides additional functionality.

Starting with .NET Framework 4.6, <xref:System.Diagnostics.Tracing.EventSource> provides channel support and some of the event source validation rules have been relaxed. This means:

- <xref:System.Diagnostics.Tracing.EventSource> types may now implement interfaces. This enables the use of event source types in advanced logging systems that use interfaces to define a common logging target.

- The concept of a utility event source type has been introduced. This feature enables sharing code across multiple event source types in a project to enable scenarios such as optimized <xref:System.Diagnostics.Tracing.EventSource.WriteEvent%2A> overloads.

For a version of the <xref:System.Diagnostics.Tracing.EventSource> class that provides features such as channel support you are targeting .NET Framework 4.5.1 or earlier, see [Microsoft EventSource Library 1.0.16](https://www.nuget.org/packages/Microsoft.Diagnostics.Tracing.EventSource).



## Examples
The basic functionality of <xref:System.Diagnostics.Tracing.EventSource> is sufficient for most applications. If you want more control over the event metadata that's created, you can apply the <xref:System.Diagnostics.Tracing.EventAttribute> attribute to the methods. For advanced event source applications, it is possible to intercept the commands being sent to the derived event source and change the filtering, or to cause actions (such as dumping a data structure) to be performed by the inheritor. An event source can be activated in-process using <xref:System.Diagnostics.Tracing.EventListener> and out-of-process using EventPipe-based tools such as `dotnet-trace` or Event Tracing for Windows (ETW) based tools like `PerfView` or `Logman`. It is also possible to programmatically control and intercept the data dispatcher. The <xref:System.Diagnostics.Tracing.EventListener> class provides additional functionality.

### Conventions
<xref:System.Diagnostics.Tracing.EventSource>-derived classes should follow the following conventions:

- User-defined classes should implement a singleton pattern. The singleton instance is traditionally named `Log`. By extension, users should not call `IDisposable.Dispose` manually and allow the runtime to clean up the singleton instance at the end of managed code execution.
- A user-defined, derived class should be marked as `sealed` unless it implements the advanced "Utility EventSource" configuration discussed in the Advanced Usage section.
- Call <xref:System.Diagnostics.Tracing.EventSource.IsEnabled> before performing any resource intensive work related to firing an event.
- You can implicitly create <xref:System.Diagnostics.Tracing.EventTask> objects by declaring two event methods with subsequent event IDs that have the naming pattern `<EventName>Start` and `<EventName>Stop`. These events _must_ be declared next to each other in the class definition and the `<EventName>Start` method _must_ come first.
- Attempt to keep <xref:System.Diagnostics.Tracing.EventSource> objects backwards compatible and version them appropriately. The default version for an event is `0`. The version can be can be changed by setting <xref:System.Diagnostics.Tracing.EventAttribute.Version>. Change the version of an event whenever you change properties of the payload. Always add new payload properties to the end of the event declaration. If this is not possible, create a new event with a new ID to replace the old one.
- When declaring event methods, specify fixed-size payload properties before variably sized properties.
- <xref:System.Diagnostics.Tracing.EventKeywords> are used as a bit mask for specifying specific events when subscribing to a provider. You can specify keywords by defining a `public static class Keywords` member class that has `public const EventKeywords` members.
- Associate expensive events with an <xref:System.Diagnostics.Tracing.EventKeywords> using <xref:System.Diagnostics.Tracing.EventAttribute>. This pattern allows users of your <xref:System.Diagnostics.Tracing.EventSource> to opt out of these expensive operations.

### Self-describing (tracelogging) vs. manifest event formats
<xref:System.Diagnostics.Tracing.EventSource> can be configured into to two different modes based on the constructor used or what flags are set on <xref:System.Diagnostics.Tracing.EventSourceOptions>.

Historically, these two formats are derived from two formats that Event Tracing for Windows (ETW) used. While these two modes don't affect your ability to use Event Tracing for Windows (ETW) or EventPipe-based listeners, they do generate the metadata for events differently.

The default event format is <xref:System.Diagnostics.Tracing.EventSourceSettings.EtwManifestEventFormat>, which is set if not specified on <xref:System.Diagnostics.Tracing.EventSourceSettings>. Manifest-based <xref:System.Diagnostics.Tracing.EventSource> objects generate an XML document representing the events defined on the class upon initialization. This requires the <xref:System.Diagnostics.Tracing.EventSource> to reflect over itself to generate the provider and event metadata.

To use self-describing (tracelogging) event format, construct your <xref:System.Diagnostics.Tracing.EventSource> using the <xref:System.Diagnostics.Tracing.EventSource.%23ctor(System.String)> constructor, the <xref:System.Diagnostics.Tracing.EventSource.%23ctor(System.String,System.Diagnostics.Tracing.EventSourceSettings)> constructor, or by setting the `EtwSelfDescribingEventFormat` flag on <xref:System.Diagnostics.Tracing.EventSourceSettings>. Self-describing sources generate minimal provider metadata on initialization and only generate event metadata when <xref:System.Diagnostics.Tracing.EventSource.Write(System.String)> is called.

In practice, these event format settings only affect usage with readers based on Event Tracing for Windows (ETW). They can, however, have a small effect on initialization time and per-event write times due to the time required for reflection and generating the metadata.

### Examples
The following example shows a simple implementation of the <xref:System.Diagnostics.Tracing.EventSource> class.

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR/etwtracesmall/cs/program.cs" id="Snippet1":::
Expand All @@ -82,6 +92,28 @@
:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR/etwtrace/cs/program.cs" id="Snippet1":::
:::code language="vb" source="~/samples/snippets/visualbasic/VS_Snippets_CLR/etwtrace/vb/program.vb" id="Snippet1":::


### Advanced Usage
Traditionally, user-defined <xref:System.Diagnostics.Tracing.EventSource> objects expect to inherit directly from <xref:System.Diagnostics.Tracing.EventSource>. For advanced scenarios, however, you can create `abstract` <xref:System.Diagnostics.Tracing.EventSource> objects, called *Utility Sources*, and implement interfaces. Using one or both of these techniques allows you to share code between different derived sources.

> [!IMPORTANT]
> Abstract <xref:System.Diagnostics.Tracing.EventSource> objects cannot define keywords, tasks, opcodes, channels, or events.

> [!IMPORTANT]
> To avoid name collisions at run time when generating event metadata, don't explicitly implement interface methods when using interfaces with <xref:System.Diagnostics.Tracing.EventSource>.

The following example shows an implementation of <xref:System.Diagnostics.Tracing.EventSource> that uses an interface.

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR/etwtracelarge/cs/program.cs" id="InterfaceSource":::

The following example shows an implementation of <xref:System.Diagnostics.Tracing.EventSource> that uses the Utility EventSource pattern.

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR/etwtracelarge/cs/program.cs" id="UtilitySource":::

The following example shows an implementation of <xref:System.Diagnostics.Tracing.EventSource> for tracing information about a component in a library.

:::code language="csharp" source="~/samples/snippets/csharp/VS_Snippets_CLR/etwtracelarge/cs/program.cs" id="ComplexSource":::

]]></format>
</remarks>
<threadsafe>This type is thread safe.</threadsafe>
Expand Down Expand Up @@ -731,7 +763,7 @@
<AssemblyVersion>4.0.0.0</AssemblyVersion>
</AssemblyInfo>
<AssemblyInfo>
<AssemblyName>netstandard</AssemblyName>
<AssemblyName>netstandard</AssemblyName>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
<AssemblyVersion>2.1.0.0</AssemblyVersion>
</AssemblyInfo>
Expand Down