예제 #1
0
        public override void EventSourceCommand(string eventSourceName, EventCommand command, FilteringOptions options = null)
        {
            if (command == EventCommand.Enable)
            {
                if (options == null)
                {
                    options = new FilteringOptions();
                }

                _session.EnableProvider(eventSourceName, (TraceEventLevel)options.Level, (ulong)options.Keywords,
                                        new TraceEventProviderOptions()
                {
                    Arguments = options.Args
                });
            }
            else if (command == EventCommand.Disable)
            {
                _session.DisableProvider(TraceEventProviders.GetEventSourceGuidFromName(eventSourceName));
            }
            else
            {
                throw new NotImplementedException();
            }
            Thread.Sleep(200);          // Calls are async, give them time to work.
        }
예제 #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EventSourceSettings" /> class.
        /// </summary>
        /// <param name="name">The friendly event source name.</param>
        /// <param name="eventSourceId">The event source id.</param>
        /// <param name="level">The level.</param>
        /// <param name="matchAnyKeyword">The match any keyword.</param>
        /// <param name="arguments">The arguments for the event source.</param>
        /// <param name="processNameFilters">The the process filters.</param>
        /// <exception cref="ConfigurationException">A validation exception.</exception>
        public EventSourceSettings(
            string name                   = null,
            Guid?eventSourceId            = null,
            EventLevel level              = EventLevel.LogAlways,
            EventKeywords matchAnyKeyword = Keywords.All,
            IEnumerable <KeyValuePair <string, string> > arguments = null,
            IEnumerable <string> processNameFilters = null)
        {
            // If no Id, Name should not be optional so we may derive an Id from it.
            if (!eventSourceId.HasValue || eventSourceId == Guid.Empty)
            {
                if (string.IsNullOrWhiteSpace(name))
                {
                    throw new ConfigurationException(Properties.Resources.MissingEventSourceNameAndId);
                }

                eventSourceId = TraceEventProviders.GetEventSourceGuidFromName(name);
            }
            else if (!string.IsNullOrWhiteSpace(name))
            {
                // throw and both name & Id specified
                throw new ConfigurationException(Properties.Resources.EventSourceAmbiguityError);
            }

            this.EventSourceId        = eventSourceId.Value;
            this.Name                 = name ?? eventSourceId.ToString(); // Set a not null value for later use
            this.Level                = level;
            this.MatchAnyKeyword      = matchAnyKeyword;
            this.Arguments            = arguments ?? Enumerable.Empty <KeyValuePair <string, string> >();
            this.ProcessNamesToFilter = processNameFilters ?? Enumerable.Empty <string>();
        }
        public EtwTracingInterceptorTest()
        {
            eventSession = new TraceEventSession(Guid.NewGuid().ToString());
            var eventSourceGuid = TraceEventProviders.GetEventSourceGuidFromName("Microsoft-WindowsAzure");

            eventSession.EnableProvider(eventSourceGuid);
        }
예제 #4
0
        public void Start()
        {
            etwSession = new TraceEventSession("RequestSession");
            etwSession.Source.Dynamic.All += HandleEtwEvent;
            var eventSourceProviderGuid = TraceEventProviders.GetEventSourceGuidFromName(EventSource.GetName(typeof(EtwSource)));

            etwSession.EnableProvider(eventSourceProviderGuid);
            Task.Factory.StartNew(() => etwSession.Source.Process());
        }
예제 #5
0
        public void Writing_Message_To_Etw()
        {
            var fpath = Path.Combine(Path.GetTempPath(), "_etwnlogtest.etl");

            using (var session = new TraceEventSession("SimpleMonitorSession", fpath)) {
                //var eventSourceGuid = TraceEventProviders.GetEventSourceGuidFromName("MyEventSource");
                var eventSourceGuid = TraceEventProviders.GetEventSourceGuidFromName("LowLevelDesign-NLogEtwSource");
                session.EnableProvider(eventSourceGuid);

                // send events to session
                var logger = LogManager.GetLogger("A");
                logger.Debug("test-debug");
                logger.Info("test-info");
                logger.Warn("test-warn");
                logger.Error("test-error");
                logger.Fatal("test-fatal");

                Thread.Sleep(5000);
            }

            var collectedEvents = new List <ExtendedEtwEvent>(5);

            using (var source = new ETWTraceEventSource(fpath)) {
                var parser = new DynamicTraceEventParser(source);
                parser.All += delegate(TraceEvent data) {
                    collectedEvents.Add(new ExtendedEtwEvent {
                        EventId    = (int)data.ID,
                        Level      = data.Level,
                        LoggerName = (String)data.PayloadByName("LoggerName"),
                        Message    = (String)data.PayloadByName("Message")
                    });
                };
                source.Process();
            }
            File.Delete(fpath);

            // assert collected events
            var expectedEvents = new ExtendedEtwEvent[] {
                new ExtendedEtwEvent {
                    EventId = 1, LoggerName = "A", Level = TraceEventLevel.Verbose, Message = "DEBUG|A|test-debug"
                },
                new ExtendedEtwEvent {
                    EventId = 2, LoggerName = "A", Level = TraceEventLevel.Informational, Message = "INFO|A|test-info"
                },
                new ExtendedEtwEvent {
                    EventId = 3, LoggerName = "A", Level = TraceEventLevel.Warning, Message = "WARN|A|test-warn"
                },
                new ExtendedEtwEvent {
                    EventId = 4, LoggerName = "A", Level = TraceEventLevel.Error, Message = "ERROR|A|test-error"
                },
                new ExtendedEtwEvent {
                    EventId = 5, LoggerName = "A", Level = TraceEventLevel.Critical, Message = "FATAL|A|test-fatal"
                }
            };

            Assert.Equal(collectedEvents, expectedEvents);
        }
        protected override void EnableProviders(TraceEventSession session)
        {
            var options = new TraceEventProviderOptions()
            {
                ProcessNameFilter = new string[] { "Quadrant.exe" }
            };

            Guid eventSource = TraceEventProviders.GetEventSourceGuidFromName(QuadrantProvider);

            session.EnableProvider(eventSource, options: options);

            EnabledDefaultProviders(session, options);
        }
예제 #7
0
        public static void X()
        {
            // Create a new session, turn on some events, and get the stream of events
            var session = new TraceEventSession("MySession");

            session.EnableProvider(TraceEventProviders.GetEventSourceGuidFromName("MyEventSource"));
            var eventStream = session.Source;

            // Create an in memory GENERIC list of parsed (basically string) records that can hold the results
            GenericEventSource eventSource = new GenericEventSource();

            // Hook up the ETW eventStream to the generic in memory event source.
            var dynamicParser = new DynamicTraceEventParser(eventStream);
            Action <TraceEvent> sendToEventStore = delegate(TraceEvent data)
            {
                var processName = data.ProcessName;
                if (!processName.StartsWith("("))
                {
                    processName += " (" + data.ProcessID + ")";
                }

                var fieldNames = data.PayloadNames;
                var fields     = new string[fieldNames.Length];
                for (int i = 0; i < fields.Length; i++)
                {
                    fields[i] = data.PayloadString(i);
                }

                var genericRecord = new GenericEventRecord(data.EventName, data.ProcessName, data.TimeStampRelativeMSec, fieldNames, fields);
                eventSource.Records.AddRecord(genericRecord);
            };

            dynamicParser.All += sendToEventStore;
            var registeredParser = new RegisteredTraceEventParser(eventStream);

            registeredParser.All        += sendToEventStore;
            eventStream.UnhandledEvents += sendToEventStore;

            // Start processing ETW events and filling the in-memory list (which the GUI is observing).
            var thread = new Thread(delegate()
            {
                session.Source.Process();
            });

            thread.Start();

            var window = new EventWindow(GuiApp.MainWindow, eventSource);

            window.Show();
        }
예제 #8
0
        public TraceEventProvider(string nameOrGuid, TraceEventLevel level = TraceEventLevel.Verbose)
        {
            Guid guid;

            if (!Guid.TryParse(nameOrGuid, out guid))
            {
                this.Guid = TraceEventProviders.GetEventSourceGuidFromName(nameOrGuid);
            }
            else
            {
                this.Guid = guid;
            }
            this.Level = level;
        }
예제 #9
0
파일: Program.cs 프로젝트: lepinay/myedit
        static void Main(string[] args)
        {
            using (var session = new TraceEventSession("MyRealTimeSession3"))        // Create a session to listen for events
            {
                session.Source.Dynamic.All += delegate(TraceEvent data)              // Set Source (stream of events) from session.
                {                                                                    // Get dynamic parser (knows about EventSources)
                    // Subscribe to all EventSource events
                    Console.WriteLine(data.FormattedMessage);                        // Print each message as it comes in
                };

                var eventSourceGuid = TraceEventProviders.GetEventSourceGuidFromName("MyEdit3"); // Get the unique ID for the eventSouce.
                session.EnableProvider(eventSourceGuid);                                         // Enable MyEventSource.
                session.Source.Process();                                                        // Wait for incoming events (forever).
            }
        }
예제 #10
0
        public static Guid GetProviderGuidFromProviderName(string name)
        {
            if (String.IsNullOrEmpty(name))
            {
                return(Guid.Empty);
            }

            // Legacy GUID lookups (events which existed before the current Guid generation conventions)
            if (name == TplEtwProviderTraceEventParser.ProviderName)
            {
                return(TplEtwProviderTraceEventParser.ProviderGuid);
            }
            else if (name == ClrTraceEventParser.ProviderName)
            {
                return(ClrTraceEventParser.ProviderGuid);
            }
            else if (name == ClrPrivateTraceEventParser.ProviderName)
            {
                return(ClrPrivateTraceEventParser.ProviderGuid);
            }
            else if (name == ClrRundownTraceEventParser.ProviderName)
            {
                return(ClrRundownTraceEventParser.ProviderGuid);
            }
            else if (name == ClrStressTraceEventParser.ProviderName)
            {
                return(ClrStressTraceEventParser.ProviderGuid);
            }
            else if (name == FrameworkEventSourceTraceEventParser.ProviderName)
            {
                return(FrameworkEventSourceTraceEventParser.ProviderGuid);
            }
            // Needed as long as eventpipeinstance v1 objects are supported
            else if (name == SampleProfilerTraceEventParser.ProviderName)
            {
                return(SampleProfilerTraceEventParser.ProviderGuid);
            }

            // Hash the name according to current event source naming conventions
            else
            {
                return(TraceEventProviders.GetEventSourceGuidFromName(name));
            }
        }
예제 #11
0
        public static EventSourceDefinition Parse(string providerName, ulong matchAnyKeywords, int traceLevel, IEnumerable <int> ids, IEnumerable <int> processIds, IEnumerable <string> processNames)
        {
            Guid providerGuid = TraceEventProviders.GetProviderGuidByName(providerName);

            if (providerGuid == Guid.Empty)
            {
                providerGuid = TraceEventProviders.GetEventSourceGuidFromName(providerName);
                if (providerGuid == Guid.Empty)
                {
                    throw new ArgumentException(string.Format("Provider name doesn't exist: {0}", providerName));
                }
            }

            var definition = new EventSourceDefinition()
            {
                ProviderName = providerName,
                ProviderGuid = providerGuid,
                Keywords     = matchAnyKeywords,
                TraceLevel   = (TraceEventLevel)traceLevel,
            };

            if (ids != null)
            {
                var idList = new List <int>(ids);
                definition.Ids = idList.Count > 0 ? idList : null;
            }

            if (processIds != null)
            {
                var processIdList = new List <int>(processIds);
                definition.ProcessIds = processIdList.Count > 0 ? processIdList : null;
            }

            if (processNames != null)
            {
                var processNameList = new List <string>(processNames);
                definition.ProcessNames = processNameList.Count > 0 ? processNameList : null;
            }

            return(definition);
        }
예제 #12
0
        static void Main(string[] args)
        {
            Console.WriteLine("\n Auth0 Claims Provider Logs on {0}\n\n", Environment.MachineName);

            using (var session = new TraceEventSession("Auth0.ClaimsProvider.LogsProcessor"))
            {
                session.Source.Dynamic.All += delegate(TraceEvent data)
                {
                    if (!String.IsNullOrEmpty(data.FormattedMessage))
                    {
                        // Get the process name.
                        var processName = "Unknown process";
                        try
                        {
                            var process = Process.GetProcessById(data.ProcessID);
                            if (process != null)
                            {
                                processName = process.ProcessName;
                                process.Dispose();
                            }
                        }
                        catch (Exception)
                        {
                        }

                        // Display the process.
                        Console.WriteLine(" {0} - {1} [{2}]", data.TimeStamp.ToString("HH:mm:ss"), data.FormattedMessage, processName);
                    }
                };

                session.EnableProvider(
                    TraceEventProviders.GetEventSourceGuidFromName("Auth0-ClaimsProviderEventSource"));
                session.Source.Process();
            }

            Console.ReadLine();
        }
        public void Writing_Message_To_Etw()
        {
            var resetEvent      = new ManualResetEvent(false);
            var collectedEvents = new List <NLogEtwEventData>(5);

            var providerName = etwTarget.ProviderName.Render(LogEventInfo.CreateNullEvent());

            using (var session = new TraceEventSession("SimpleMonitorSession"))
            {
                // Dynamic-Parser does not work with pure EventSource-objects
                session.Source.Registered.All += delegate(TraceEvent data)
                {
                    if (data.Level == TraceEventLevel.Always)
                    {
                        return;   // Not ours
                    }
                    collectedEvents.Add(new NLogEtwEventData(data)
                    {
                        EventId    = 0, // Raw EventSource gives "random" EventId
                        LoggerName = (string)data.PayloadByName("LoggerName"),
                        Message    = (string)data.PayloadByName("Message"),
                    });

                    if (collectedEvents.Count == 5)
                    {
                        resetEvent.Set();
                    }
                };
                session.Source.UnhandledEvents += delegate(TraceEvent data)
                {
                    if ((int)data.ID == 0xFFFE)
                    {
                        return; // The EventSource manifest events show up as unhanded, filter them out.
                    }
                };

                var task = System.Threading.Tasks.Task.Run(() => session.Source.Process());

                Thread.Sleep(1000);

                session.EnableProvider(providerName);

                Thread.Sleep(1000);

                // send events to session
                var logger = LogManager.GetLogger("A");
                logger.Debug("test-debug");
                logger.Info("test-info");
                logger.Warn("test-warn");
                logger.Error("test-error");
                logger.Fatal("test-fatal");

                try
                {
                    var eventSourceGuid = TraceEventProviders.GetEventSourceGuidFromName(providerName);
                    session.DisableProvider(eventSourceGuid);
                }
                catch
                {
                    Thread.Sleep(1000);
                    var eventSourceGuid = TraceEventProviders.GetEventSourceGuidFromName(providerName);
                    session.DisableProvider(eventSourceGuid);
                }

                Thread.Sleep(1000);

                logger.Fatal("don't log this one");
                resetEvent.WaitOne(20000);
            }

            // assert collected events
            var expectedEvents = new NLogEtwEventData[] {
                new NLogEtwEventData {
                    EventId = 0, ProviderName = providerName, TaskName = "Debug", Level = TraceEventLevel.Verbose, LoggerName = "A", Message = "DEBUG|A|test-debug"
                },
                new NLogEtwEventData {
                    EventId = 0, ProviderName = providerName, TaskName = "Info", Level = TraceEventLevel.Informational, LoggerName = "A", Message = "INFO|A|test-info"
                },
                new NLogEtwEventData {
                    EventId = 0, ProviderName = providerName, TaskName = "Warn", Level = TraceEventLevel.Warning, LoggerName = "A", Message = "WARN|A|test-warn"
                },
                new NLogEtwEventData {
                    EventId = 0, ProviderName = providerName, TaskName = "Error", Level = TraceEventLevel.Error, LoggerName = "A", Message = "ERROR|A|test-error"
                },
                new NLogEtwEventData {
                    EventId = 0, ProviderName = providerName, TaskName = "Fatal", Level = TraceEventLevel.Critical, LoggerName = "A", Message = "FATAL|A|test-fatal"
                }
            };

            Assert.Equal(collectedEvents, expectedEvents);
        }
예제 #14
0
 public TraceEventProvider(string nameOrGuid, TraceEventLevel level = TraceEventLevel.Verbose, ulong keywords = ulong.MaxValue)
 {
     Guid     = !Guid.TryParse(nameOrGuid, out var guid) ? TraceEventProviders.GetEventSourceGuidFromName(nameOrGuid) : guid;
     Level    = level;
     Keywords = keywords;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="EtwEventDynamicProcessor"/> class.
 /// </summary>
 /// <param name="providerName">The name of the provider which events we are going to consume.</param>
 /// <param name="traceEventHandler">The callback which is called every time new event appears.</param>
 internal EtwEventDynamicProcessor(string providerName, Action <TraceEvent> traceEventHandler)
 {
     this.providerName      = providerName;
     providerGuid           = TraceEventProviders.GetEventSourceGuidFromName(providerName);
     this.traceEventHandler = traceEventHandler;
 }
예제 #16
0
        private void TraceEvents()
        {
            // will attempt to create a session named "MySession"
            using (var session = new TraceEventSession("MySession"))
            {
                // set up Ctrl-C to stop the session
                SetupCtrlCHandler(() => { session.Stop(); });

                // set up parser to read CLR events
                var clrParser = new ClrTraceEventParser(session.Source);

                if (ExceptionEnabled == 1)
                {
                    // subscribe to all exception start events
                    clrParser.ExceptionStart += delegate(ExceptionTraceData data)
                    {
                        // if exception was in user process, add it to list of exceptions
                        if (data.ProcessID == myProcess.Id)
                        {
                            Exceptions e = new Exceptions();
                            e.type      = data.ExceptionType;
                            e.timestamp = DateTime.Now;
                            e.App       = instance;
                            lock (lockObject)
                            {
                                ExceptionVals.Add(e);
                            }
                        }
                    };
                }

                if (ContentionEnabled == 1)
                {
                    // subscribe to all contention start events
                    clrParser.ContentionStart += delegate(ContentionTraceData data)
                    {
                        if (data.ProcessID == myProcess.Id)
                        {
                            Contention c = new Contention();
                            c.type      = "Start";
                            c.id        = data.ActivityID;
                            c.timestamp = DateTime.Now;
                            c.App       = instance;
                            lock (lockObject)
                            {
                                ContentionVals.Add(c);
                            }
                        }
                    };
                    // subscribe to all contention stop events
                    clrParser.ContentionStop += delegate(ContentionTraceData data)
                    {
                        if (data.ProcessID == myProcess.Id)
                        {
                            Contention c = new Contention();
                            c.type      = "Stop";
                            c.id        = data.ActivityID;
                            c.timestamp = DateTime.Now;
                            c.App       = instance;
                            lock (lockObject)
                            {
                                ContentionVals.Add(c);
                            }
                        }
                    };
                }

                if (GCEnabled == 1)
                {
                    // subscribe to all GC start events
                    clrParser.GCStart += delegate(GCStartTraceData data)
                    {
                        if (data.ProcessID == myProcess.Id)
                        {
                            GC gc = new GC();
                            gc.type      = "Start";
                            gc.timestamp = DateTime.Now;
                            gc.id        = data.ThreadID;
                            gc.App       = instance;
                            lock (lockObject)
                            {
                                GCVals.Add(gc);
                            }
                        }
                    };
                    // subscribe to all GC stop events
                    clrParser.GCStop += delegate(GCEndTraceData data)
                    {
                        if (data.ProcessID == myProcess.Id)
                        {
                            GC gc = new GC();
                            gc.type      = "Stop";
                            gc.timestamp = DateTime.Now;
                            gc.id        = data.ThreadID;
                            gc.App       = instance;
                            lock (lockObject)
                            {
                                GCVals.Add(gc);
                            }
                        }
                    };
                    // subscribe to all GC memory allocation ticks
                    clrParser.GCAllocationTick += delegate(GCAllocationTickTraceData data)
                    {
                        if (data.ProcessID == myProcess.Id)
                        {
                            GC gc = new GC();
                            gc.type      = "Allocation Tick";
                            gc.timestamp = DateTime.Now;
                            gc.id        = data.ThreadID;
                            gc.App       = instance;
                            lock (lockObject)
                            {
                                GCVals.Add(gc);
                            }
                        }
                    };
                    // subscribe to all creations of concurrent threads for GC
                    clrParser.GCCreateConcurrentThread += delegate(GCCreateConcurrentThreadTraceData data)
                    {
                        if (data.ProcessID == myProcess.Id)
                        {
                            GC gc = new GC();
                            gc.type      = "Create Concurrent Thread";
                            gc.timestamp = DateTime.Now;
                            gc.id        = data.ThreadID;
                            gc.App       = instance;
                            lock (lockObject)
                            {
                                GCVals.Add(gc);
                            }
                        }
                    };
                    // subscribe to all restart stops
                    clrParser.GCRestartEEStop += delegate(GCNoUserDataTraceData data)
                    {
                        if (data.ProcessID == myProcess.Id)
                        {
                            GC gc = new GC();
                            gc.type      = "Restart EE Stop";
                            gc.timestamp = DateTime.Now;
                            gc.id        = data.ThreadID;
                            gc.App       = instance;
                            lock (lockObject)
                            {
                                GCVals.Add(gc);
                            }
                        }
                    };
                    // subscribe to all suspension starts
                    clrParser.GCSuspendEEStart += delegate(GCSuspendEETraceData data)
                    {
                        if (data.ProcessID == myProcess.Id)
                        {
                            GC gc = new GC();
                            gc.type      = "Suspend EE Start";
                            gc.timestamp = DateTime.Now;
                            gc.id        = data.ThreadID;
                            gc.App       = instance;
                            lock (lockObject)
                            {
                                GCVals.Add(gc);
                            }
                        }
                    };
                    // subscribe to all concurrent thread terminations
                    clrParser.GCTerminateConcurrentThread += delegate(GCTerminateConcurrentThreadTraceData data)
                    {
                        if (data.ProcessID == myProcess.Id)
                        {
                            GC gc = new GC();
                            gc.type      = "Concurrent Thread Termination";
                            gc.timestamp = DateTime.Now;
                            gc.id        = data.ThreadID;
                            gc.App       = instance;
                            lock (lockObject)
                            {
                                GCVals.Add(gc);
                            }
                        }
                    };
                    // subscribe to all GC triggers
                    clrParser.GCTriggered += delegate(GCTriggeredTraceData data)
                    {
                        if (data.ProcessID == myProcess.Id)
                        {
                            GC gc = new GC();
                            gc.type      = "Triggered";
                            gc.timestamp = DateTime.Now;
                            gc.id        = data.ThreadID;
                            gc.App       = instance;
                            lock (lockObject)
                            {
                                GCVals.Add(gc);
                            }
                        }
                    };
                }

                if (JitEnabled == 1)
                {
                    // subscribe to all Jit start events
                    clrParser.MethodJittingStarted += delegate(MethodJittingStartedTraceData data)
                    {
                        if (data.ProcessID == myProcess.Id)
                        {
                            Jit j = new Jit();
                            j.method    = data.MethodName;
                            j.timestamp = DateTime.Now;
                            j.App       = instance;
                            lock (lockObject)
                            {
                                JitVals.Add(j);
                            }
                        }
                    };
                }

                if (HttpEnabled == 1)
                {
                    // subscribe to all dynamic events (used for HTTP request event tracking)
                    session.Source.Dynamic.All += delegate(TraceEvent data) {
                        if (data.ProcessID == myProcess.Id && data.EventName == "Request/Start")
                        {
                            Http_Request request = new Http_Request();
                            request.type       = "Start";
                            request.timestamp  = DateTime.Now;
                            request.activityID = data.ActivityID;
                            request.App        = instance;
                            request.method     = data.PayloadString(0);
                            request.path       = data.PayloadString(1);
                            lock (lockObject)
                            {
                                RequestVals.Add(request);
                            }
                        }
                        else if (data.ProcessID == myProcess.Id && data.EventName == "Request/Stop")
                        {
                            Http_Request request = new Http_Request();
                            request.type       = "Stop";
                            request.timestamp  = DateTime.Now;
                            request.activityID = data.ActivityID;
                            request.App        = instance;
                            lock (lockObject)
                            {
                                RequestVals.Add(request);
                            }
                        }
                    };
                }

                // set up providers for events using GUIDs - first EnableProvider command is to receive activity IDs for associated events
                session.EnableProvider(new Guid("2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5"), TraceEventLevel.Informational, 0x80);
                var AspSourceGuid = TraceEventProviders.GetEventSourceGuidFromName("Microsoft-AspNetCore-Hosting");
                session.EnableProvider(AspSourceGuid);
                session.EnableProvider(ClrTraceEventParser.ProviderGuid, TraceEventLevel.Verbose, (0x8000 | 0x4000 | 0x1 | 0x10));
                session.Source.Process();    // call the callbacks for each event
            }
        }
예제 #17
0
        public void Writing_Message_To_Etw()
        {
            var providerName = "LowLevelDesign-NLogEtwSource";
            var resetEvent   = new ManualResetEvent(false);
            var fpath        = Path.Combine(Path.GetTempPath(), "_etwnlogtest.etl");

            using (var session = new TraceEventSession("SimpleMonitorSession", fpath))
            {
                Thread.Sleep(1000);

                var eventSourceGuid = TraceEventProviders.GetEventSourceGuidFromName(providerName);

                try
                {
                    session.EnableProvider(eventSourceGuid);
                    Thread.Sleep(1000);
                }
                catch
                {
                    Thread.Sleep(1000);
                    eventSourceGuid = TraceEventProviders.GetEventSourceGuidFromName(providerName);
                    session.EnableProvider(eventSourceGuid);
                }

                // send events to session
                var logger = LogManager.GetLogger("A");
                logger.Debug("test-debug");
                logger.Info("test-info");
                logger.Warn("test-warn");
                logger.Error("test-error");
                logger.Fatal("test-fatal");

                try
                {
                    Thread.Sleep(1000);
                    session.DisableProvider(eventSourceGuid);
                }
                catch
                {
                    Thread.Sleep(1000);
                    session.DisableProvider(eventSourceGuid);
                }

                Thread.Sleep(1000);

                logger.Fatal("don't log this one");
            }

            var collectedEvents = new List <NLogEtwEventData>(5);

            using (var source = new ETWTraceEventSource(fpath))
            {
                var parser = new DynamicTraceEventParser(source);
                parser.All += delegate(TraceEvent data)
                {
                    if (data.Level == TraceEventLevel.Always)
                    {
                        return;   // Not ours
                    }
                    collectedEvents.Add(new NLogEtwEventData(data)
                    {
                        LoggerName = (string)data.PayloadByName("LoggerName"),
                        Message    = (string)data.PayloadByName("Message")
                    });

                    if (collectedEvents.Count == 5)
                    {
                        resetEvent.Set();
                    }
                };
                source.Process();
            }
            File.Delete(fpath);

            // assert collected events
            var expectedEvents = new NLogEtwEventData[] {
                new NLogEtwEventData {
                    EventId = 1, ProviderName = providerName, TaskName = "Verbose", LoggerName = "A", Level = TraceEventLevel.Verbose, Message = "DEBUG|A|test-debug"
                },
                new NLogEtwEventData {
                    EventId = 2, ProviderName = providerName, TaskName = "Info", LoggerName = "A", Level = TraceEventLevel.Informational, Message = "INFO|A|test-info"
                },
                new NLogEtwEventData {
                    EventId = 3, ProviderName = providerName, TaskName = "Warn", LoggerName = "A", Level = TraceEventLevel.Warning, Message = "WARN|A|test-warn"
                },
                new NLogEtwEventData {
                    EventId = 4, ProviderName = providerName, TaskName = "Error", LoggerName = "A", Level = TraceEventLevel.Error, Message = "ERROR|A|test-error"
                },
                new NLogEtwEventData {
                    EventId = 5, ProviderName = providerName, TaskName = "Critical", LoggerName = "A", Level = TraceEventLevel.Critical, Message = "FATAL|A|test-fatal"
                }
            };

            resetEvent.WaitOne(20000);
            Assert.Equal(collectedEvents, expectedEvents);
        }