Kendall Frey
Kendall Frey

Reputation: 44326

How can I capture process names using the TraceEvent library?

I'm using the TraceEvent library to capture ETW traces, but I'm not able to determine the name of the process that caused an event.

Here is what I have so far:

var session = new TraceEventSession(sessionName, null);
session.EnableProvider(MyEventSource.Log.Guid, TraceEventLevel.Informational,
    options: TraceEventOptions.Stacks);
Task.Delay(1000).ContinueWith(t => session.Stop()); // for testing, deal with it (⌐■_■)
var src = new ETWTraceEventSource(sessionName, TraceEventSourceType.Session);
TraceLog.CreateFromSource(src, etlxFile, null);
var log = TraceLog.OpenOrConvert(etlxFile);
var process = log.Events.First().ProcessName;
// breakpoint

When the breakpoint at the end is hit, process is "". ProcessID is a proper PID, but that's the only useful information I could find from the processes in the log.

I expected process names to be captured by the log. Am I doing something wrong, or is this API just not available on my OS (Windows 7)?

Upvotes: 2

Views: 1656

Answers (2)

Aaron Hudon
Aaron Hudon

Reputation: 5839

This can be done by enabling the kernel provider, and then maintaining a lookup of process id to process name. Here's a rough example - no error checking, but you get the idea.

// create a lookup collection for future use    
var pidToProcessName = new Dictionary<int, string>();

var session = new TraceEventSession(...);
// enable the kernel provider - note!  this most come first
session.EnableKernelProvider(KernelTraceEventParser.Keywords.Process);
...
session.Source.Kernel.ProcessStart += ProcessStart;
session.Source.Dynamic.All += TraceEvent;
...
session.Source.Procces();    


void ProcessStart(ProcessTraceData obj)
{
    if(obj.OpCode == TraceEventOpcode.Start)
    {
        pidToProcessName[obj.ProcessID] = obj.ProcessName;
    }
}

void TraceEvent(TraceEvent obj)
{
    // pull the process name from our lookup
    var processNameOfEvent = pidToProcessName[obj.ProcessID];    
}

Upvotes: 0

Sergey Baranchenkov
Sergey Baranchenkov

Reputation: 624

I truly believe that process name is not being captured by the ETW log. Etw system event contains only process ID field. Although TraceEvent library declares this one as a part of TraceEvent, this one actually is being populated based on executable image filename and process ID, which is implemented differently for all 4 TraceEventSource implementations.

Another observation is that I was never able to have this one populated (my OS is Windows 8.1).

The simple repro is to use SimpleEventSourceMonitor sample from Microsoft TraceEvent Library Samples package.

If you suspect that this is an issue, then it is better ask its owners Vance Morrison and Cosmin Radu.

Upvotes: 5

Related Questions