为什么ETW在2秒后记录日志

时间:2019-02-25 13:57:58

标签: c# unit-testing etw

我正在使用ETW日志记录。这是我的代码:

SELECT value FROM xx WHERE code=2 AND site="xyzzy";

我正在尝试为此编写单元测试。为了从事件查看器获取日志,我使用了EventLogReader和EventRecord:

SELECT value FROM xx WHERE code=2 and site IS NULL;

也是MyApp类:

 [EventSource(Name = "MyEventSource")]
public sealed class MyEventSource : EventSource
{
    public static MyEventSource Log { get; set; } = new MyEventSource();

    [NonEvent]
    public void Register()
    {
        Registrator eventSourceRegistrator = new Registrator(this);
        eventSourceRegistrator.Register();
    }


    [Event(120, Message = "App started.Process path: {0}", Level = EventLevel.Informational, Channel = EventChannel.Admin)]
    public void ServerStarted(string proccessPath)
    {
        Register();
        WriteEvent(120, proccessPath);
    }

}

当我从事件查看器中清除日志并运行EventLogTest时,它将失败。但是在测试失败后,我再次检查了事件查看器,并且有我的日志:

Log in Event Viewer

然后我更改了测试:

    [TestMethod]
    public void EventLogTest()
    {
        MyApp myApp = new MyApp();
        var appStartedLog = GetEventRecordFromEventID(120);
        Assert.IsNotNull(appStartedLog);
    }

    EventRecord GetEventRecordFromEventID(int eventID)
    {
        string source = "MyEventSource/Admin";
        string query = $"*[System/EventID={eventID}]";
        var elQuery = new EventLogQuery(source, PathType.LogName, query);
        using (var elReader = new EventLogReader(elQuery))
        {
            List<EventRecord> eventRecords = new List<EventRecord>();
            for (EventRecord eventInstance = elReader.ReadEvent(); eventInstance != null; eventInstance = elReader.ReadEvent())
            {
                eventRecords.Add(eventInstance);
            }
            var res = eventRecords.OrderBy(a => a.TimeCreated).LastOrDefault();
            return res;
        }
    }

现在,我清除日志并运行测试。它通过了。我的问题是:为什么它会在2秒后记录日志,以及如何为此编写单元测试?

0 个答案:

没有答案