System.Diagnostics.Debug namespace vs Other loggin

2019-03-14 15:56发布

问题:

I'm currently investigating various logging possibilities for .net projects and I can't decide between System.Diagnostics.Debug/Trace features and third party libraries like log4net, MS Enterprise Library, NLog, etc.
At the moment I have found out this:

  • System.Diagnostics is rather difficult to configure and to use since you need to explicitly configure all the listeners, filters, sources, etc. It seems that it also lacks the bulk insertion to the DB (think about writing 100'000 log entries each with its own Insert, horrifying, isn't it?). But by some people it is considered to be 'cool' not to use additional libs for such a "rudimentary" thing as Logging (of course, at some point, it makes sense to reduce the amount of 3rd party libraries your project relies on, but not this time, I suppose)
  • 3rd parties are much more powerful, often quicker, much easier to use, but configuration sometimes can be also painful and often these libs are less reliable (like mysterious sudden stop of logging by EntLib, etc.)
  • what about Common.Logging? is it worth trying (since, as I've heard, it offers plugging-in various logging frameworks and act like an interface between the app and the desired lib)?


I would be really grateful if somebody could point me to the right direction or correct (or add something) to my comparison given above! Maybe if you would encourage me to use 3rd parties, you could advise some particular one (taking into account that our applications most probably won't need any fancy stuff like UDP, rolling files, etc.- just plain file, email, DB and eventlog)?
Thanks in advance!

回答1:

You can find plenty of information about log4net and NLog either here on StackOverflow on by more generally googling.

You can also find a lot of info about System.Diagnostics. One thing to note about System.Diagnostics, I think that you will find a lot of references here on StackOverflow about using Debug.Write/WriteLine and Trace.Write/WriteLine. An arguably "better" way is to use TraceSources. TraceSources are analogous to loggers in log4net and NLog. TraceSources allow you to have a higher degree of granularity for your logging messages, making it easier to turn some logging on and some off (by class or category, in addition to by level). TraceSources to have a drawback, as compared to log4net and NLog, in that each TraceSource that you create in your code must be explicitly configured in the app.config (if you want it to actually log).

log4net and NLog have a hierarchical concept where if the exact logger you asked for is not explicitly configured, its "ancestry" is checked to see if any "ancestors" are configured and, if so, the requested logger "inherits" those settings. Ancestors are simply the portions of the logger name delimited by ".". (So, if you request a logger called "ABC.DEF.GHI", the ancestors would be "ABC.DEF", and "ABC"). It is also possible (required?) to have a "root" logger configuration in the app.config that ALL logger requests will fall back to if they are not explicitly configured and no ancestors are configured. So, you could configure only a "root" logger to log at a certain level and all of your loggers in your code would log at that level. Alternatively, you could configure the "root" logger to be "off" and then turn on one or more loggers explicitly (or by configuring an ancestor). In this way, NO loggers would log EXCEPT for those that are configured.

If you look here, you will find an interesting wrapper around System.Diagnostics TraceSources that provides an inheritance capability very similar to log4net and NLog.

To illustrate:

A common usage pattern for loggers in log4net and NLog is to get a logger like this:

//log4net
static ILog logger = LogManager.GetLogger(
                     System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); 

//NLog
static Logger logger = LogManager.GetCurrentClassLogger();

In both cases the logger's name will be the fully qualified type name.

In the app.config file, you can, if you desire, configure just the "root" logger and both loggers would inherit the root logger's settings (level, appenders/targets, etc). Alternatively you could configure a logger for some namespace. Any loggers whose type is defined in that namespace will inherit those logger settings.

Enough of log4net and NLog, you probably already know how they work.

The link above illustrates a TraceSource-based wrapper that allows similar configuration. So, if you wanted, you could do something like this in your classes:

static TraceSource ts = new TraceSource(
               System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

With the wrapper linked above, you could configure a TraceSource at a higher level (class/namespace hierarchy-wise, not level) and inherit those settings in lower level loggers.

So, if your full-qualified type name is something like this: ABC.DEF.GHI, then you can configure a TraceSource for ABC or ABC.DEF (namespace level) and class "GHI" would inherit the settings. This could really reduce the amount of configuration that you have to do.

Note that you are not limited (with any of these logging platforms) to using the class's type or type name to get the logger. You could define your own logger naming scheme, possibly based on functional areas ("Communication", "Communication.Send", "Communication.Receive", etc). Again, you could request a logger/TraceSource at the highest degree of granualarity (or not) and then configure at whatever level of granularity makes sense.

So, you could request loggers in your code like this:

ILog logger = LogManager.GetLogger("Communication.Receive");
ILog logger = LogManager.GetLogger("Communication.Send");

Logger logger = LogManager.GetLogger("Communication.Receive");
Logger logger = LogManager.GetLogger("Communication.Send");

TraceSource ts = new TraceSource("Communication.Receive");
TraceSource ts = new TraceSource("Communication.Send");

If you configure only "Communication" in your app.config file, then all loggers will inherit those settings (since they are descendents of "Communication"). If you configure only "Commuincation.Receive", then only the "Communication.Receive" loggers will log. The "Communication.Send" loggers will be disabled. If you configure both "Communication" and "Commuincation.Receive", then the "Communication.Receive" loggers will log at the "Communication.Receive" settings while the "Communication.Sender" loggers will log at the "Communication" settings. In log4net and NLog there can be more to inheritance than that, but I don't know enough to go into it.

One thing that you miss when using System.Diagnostics is the flexibility to format your logging output format very easily. There is a third party library that provides very nice configurable formatting for TraceSource-based logging. You can find it here.

I have used Common.Logging some. Mainly in prototyping, but I might use it in our next project. It works pretty well and it is relatively easy to write your own logging abstraction to plug into it (such as if you wanted to write a TraceSource abstraction similar to what I linked above). Two important things that are missing from Common.Logging right now (although their website says that they are scheduled for the "next" release) are logging contexts (like log4net and NLog NDC/MDC/GDC objects and System.Diagnostics.CorrelationManger.LogicalOperationStack) and Silverlight compatibility. You can still interact with the log4net or NLog context objects in your code while using Common.Logging, but that kind of defeats the purpose of it, doesn't it.

I don't know if I helped or not!

Here are some main points that I would make about log4net, NLog, and TraceSource:

log4net - very popular, probably in need of some updates - at least being built on .NET 4.0, last release a few years ago, very flexible.

NLog - very similar to log4net in many respects, new version now (beta of NLog 2.0 just came out)

TraceSource - no third party dependency, without some effort on your part (or someone's) not as powerful as log4net or NLog (key deficiencies - logger hierarchy, output formatting - both easily addressable via a links above), Microsoft instruments a many of their components with System.Diagnostics so you can get Microsoft's logging output and your logging output interleaved. (Generally, it is easy enough to capture System.Diagnostics in other logging systems so might not be huge issue).

While I have not used either log4net or NLog a lot, between the two I would lean towards NLog, mainly because of the new version that just came out (beta). I think that TraceSource is also a reasonable, if more rudimentary, choice, especially if you implement the logger hierarchy and use the Ukadc.Diagnostics libary linked above.

Or, use Common.Logging and you can avoid or delay making the decision for your underlying logging platform until you are ready. One very useful aspect of Common.Logging, to me anyway, is that you can "test-drive" logging platforms as you are developing your product without every having to change any of your application code. You don't have to wait until you have decided on a specific logging platform to add logging to your code. Add it now via the Common.Logging api. When you get close to delivery, you should have narrowed down your logging platform choice. Deliver with that platform (if you redistribute the logging platform) and you are done. You can still change later on if you want to.



回答2:

I know this is old, but System.Diagnostics.Trace is pretty easy to configure if you keep it simple. I've been using the simple text writer config block for years, copied right out of the MSDN docs.

No one mentions this very often, but in your code, you can use the built-in Trace.TraceInformation, Trace.TraceWarning, and Trace.TraceError to easily segregate 3 levels of trace output and then in the config file choose which level to output (see config below). If you choose Information in the config's "EventTypeFilter", you get all 3 in your output. If you choose Error, you'll only get TraceError messages in your output. Most of the time, I just leave mine on Error, so if something does happen in my application, I'll already have that output in my trace file. Inside my Catch blocks, I'll add TraceError code to output useful info. TraceInformation is good for outputting things like timing or spots in code which you've passed through, and dumping variable values along the way. TraceWarning is good for things which are handleable, but not desirable - like maybe a web service is taking a long time to complete, or the number of data records returned exceeds a threshold that might cause future issues.

There is a small downside, in that all these lines of trace code still execute regardless of compile level. If they are set to not output, that should reduce the overhead quite a bit. But if you're writing high-performance code, you may want to wrap those lines in conditional compile markers.

<system.diagnostics>
  <sharedListeners>
    <add name="MyTraceListener" traceOutputOptions="DateTime" type="System.Diagnostics.TextWriterTraceListener, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" initializeData="MyApplicationName_Trace.log">
     <!--
        Off - Does not allow any events through. 
        Error - Allows Error events through. 
        Warning - Allows Error, and Warning events through. 
        Information - Allows Error, Warning, and Information events through. 
     -->
     <filter type="System.Diagnostics.EventTypeFilter" initializeData="Error" />
    </add>
  </sharedListeners>
  <trace autoflush="true" indentsize="4">
    <listeners>
       <add name="MyTraceListener" />
    </listeners>
  </trace>
</system.diagnostics>


回答3:

From a developer point of view concerns like logging, similar to orm, shouldn't be hand written. There are plenty of good solid third party libraries. Sure there is sometimes a bit of configuration work to be done but compare that to hand rolling you're own solutions it's a mere drop in the water.

My personal preference is log4net but it depends on your needs. My best advice is have a look at the documentation of solutions such as log4net or EntLib Logging Application Block and make a decision about what is best for you.



回答4:

Logging and tracing are different concerns. Logging pertains to operational feedback. Tracing (including that provided by the Debug methods) pertain to development and testing. Tracing code shouldn't be compiled into the release assemblies. The Trace and Debug classes achieve this with compiler annotations (ConditionalAttribute). Such code should be optimized to collect lots of data, not for performance. On the other hand, operational logging needs to be optimized for performance and for a wider variety of storage mechanisms as required by the sysadmin/operations team.

So I recommend using both Trace/Debug for development as well as more robust logging packages for operations.