问题
Assume I have some method that I want to trace performance information for. Using System.Diagnostics.Tracing.EventSource
, I can see two logical ways of doing this; first, one could write two events, one at the start, and one at the end, and then the consumer of the events could compute the duration:
MySource.Log.OperationStart();
RunMyOperation();
MySource.Log.OperatingFinish();
Or, I can compute the duration myself, and only write a single event:
var sw = System.Diagnostics.Stopwatch.StartNew();
RunMyOperation();
sw.Stop();
MySource.Log.OperationFinish(sw.ElapsedTicks);
The upside to this second method is that no math is involved; the downside is that I have to create the stopwatch, manipulate it, and write out the data even when nobody is listening. It's an extra line of code, as well, and it's not as "pretty", subjectively.
Which is the preferred method? What do the "best practices" say?
回答1:
Always log 2 events! Add to the first Method the OpCode Start and the Stop Opcode to the second one to see which event is which Operation.
来源:https://stackoverflow.com/questions/25066944/when-using-eventsource-should-i-log-two-events-or-compute-the-duration-and-log