Is it possible to use System.Diagnostics.Trace as a form of commons logging for .net?
I was wondering if there is any way that I could leverage the methods on System.Diagnostics.Trace, as a form of commons logging for my .Net libraries. Rather than include dependencies in those libraries for log4net or CommonsNet (which appears to be a similar project to commons logging for java in .Net), can I use the built in methods?
I see that it is possible to add listeners to this trace output, however are there going to be performanc开发者_StackOverflow中文版e penalties for calling Trace.TraceError
, Trace.TraceWarning
or Trace.TraceInformation
from performance critical code?
They are already designed for this purpose so using them for what they were meant to be is perfectly valid. Just add this to your app.config file:
<configuration>
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="TextWriterOutput.log" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
On the other hand, yes they will affect the performance of your application in performance sensitive area. If you're so concerned about that, rather use Common.Logging like below:
log.Trace(m=>m("value= {0}", obj.Value));
This way, only if the LogLevel.Trace is enabled this function will be evaluated. When disabled, there will be minimal performance penalty.
The answer to both your questions is 'Yes'. For the first, you would need to implement (or use existing) TraceListener.
For the second, there will be performance penalties, as to whether or not the penalty is meaningful really depends on the perf reqs and the performance of your logger.
精彩评论