Automatic logging in windows application
I need to enable loggi开发者_如何学Gong in my Windows Appplication. Which logging framework is the best recommended one? Is there any framework which doesnt require the user to enter each and every log entry manually?
logger.Info("I don't want to write a log entry like this.");
logger.Debug("I don't want to write a log entry like this also.");
logger.Fatal("Is there any way to avoid this kind of manual log entry writing?");
Is there any other logger framework other than log4net so that I can achieve this? Or is log4net capable of doing this?
@user762730 : Are you asking how to log messages to the machines' event log? If so, you can accomplish with very few lines of code.
if (!EventLog.SourceExists("Application Name"))
EventLog.CreateEventSource("Application Name", "Application");
var myLog = new EventLog { Source = "Application Name" };
myLog.WriteEntry(errorMsg + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace);
The EventLog type is found within the System.Diagnostics namespace.
Logging doesn't happen "automatically" in that you always have to tell the system what to log (no matter where you are logging to). The "automatic" part is that you can log items using variables. For example, log4net (and other logging engines) allows you to log an exception and even the entire stack trace to the log repository of your choice. In this way, you could log all types of errors without writing out the text of the error by hand. However, you still need to put the logger.Error(...
statement in your catch
block.
You can also use the built-in string format to fill your messages from custom sources. For example, I have an application that creates accounts. I have an INFO log message that logs who is getting created. I do this by building a string in a manner similar to this:
logger.Info("Creating account for {0}", textblockUserName.Text);
where the textblock contains the username of the person being created. That way I have one entry that differs every time it is written. This makes your logging more agile but it still comes down to adding an entry that writes to the logger.
If you want to imitate what Microsoft does with the information they write to the event log, this is the way to do it. Microsoft doesn't have any automated system that tracks what they are doing. They have to specifically tell their applications what to log and when. You will need to do the same thing in your application.
精彩评论