Sunday, March 1, 2020
How to Do Logging in C# With Log4net
How to Do Logging in C# With Log4net When you write computer code in C#, its a good idea to include logging code. That way, when something goes wrong, you know where to start looking. The Java world has been doing this for years. You can use log4net for this purpose. It is part ofà Apache log4jà 2, a popular open-source logging framework. This isnt the only .NET logging framework; there are many. However, the Apache name is trusted and the original Java logging framework has been around for more thanà 15 years. Why Use a Log4net Logging Framework? When an application or server crashes, you are left wondering why. Was it a hardware failure, malware, maybe a Denial of Service attack, or some odd combination of keys that manages to bypass all your code checks? You just dont know. You need to find out why a crash occurred so it can be corrected. With logging enabled, you might be able to seeà why it happened. Getting Started Download the log4netà file from the Apache log4net website. Verify the integrity of the downloaded files using the PGP signature or MD5 checksums. The checksums are not as strong indicators as the PGP signature. Using Log4net Log4net supports seven levels of logging from none to all in increasing priority. These are: OFFFATALERRORWARNINFODEBUGALL The higher levels include all the lower ones. When debugging, using DEBUGà shows all, but on production, you might only be interested in FATAL. This choice can be made at the component level programmatically or in an XML Config file. Loggers and Appenders Forà flexibility, log4net uses loggers, appenders, and layouts. A logger is an object that controls logging and is an implementation of the ILog interface, which specifies five boolean methods: isDebugEnabled, IsInfoEnabled, IsWarnEnabled, IsErrorEnabled and IsFatalEnabled. It also specifies the five methods- Debug, Info, Warn, Error andFatal- along with overloads and five formatted string versions. You can see the full ILog interface in the log4net online manual. Loggers are assigned one of the levels but not ALL or OFF, only the other five. Appenders control where the logging goes. It can be into a database, to an in-memory buffer, to the console, to a remote host, to a text file with rolling logs, the Windows Event Log, or even to email via SMTP. There are 22à appenders in all, and they can be combined so you have plenty of choices. Appenders are appended (hence the name) to a logger. Appendersà filter events by matching substrings, event level, range of levels and start of the logger name. Layouts Finally, there are seven layouts that can be associated with an Appender. These control how the events message is logged and can include exception text, timestamp layouts, and XML elements. Configuring With XML Although configuring can be done programmatically, it can also be done with XML Config files. Why would you prefer config files over code changes? Simple, its far easier to have a support guy make a change to a config file than have to get a programmer to change code, test and redeploy a new version. So config files are the way to go. The simplest possible path is to addà App.config your project, as shown inà the example below: ?xml version1.0 encodingutf-8 ?configurationà à configSectionsà à à à section namelog4net typelog4net.Config.Log4NetConfigurationSectionHandler,Log4net/à à /configSectionsà à log4netà à à à rootà à à à à à level valueDEBUG/à à à à à à appender-ref refLogFileAppender /à à à à /rootà à à à appender nameLogFileAppender typelog4net.Appender.RollingFileAppender à à à à à à file value log.txt/à à à à à à appendToFile valuetrue /à à à à à à rollingStyle valueSize /à à à à à à maxSizeRollBackups value5 /à à à à à à maximumFileSize value10MB /à à à à à à staticLogFileName valuetrue /à à à à à à layout typelog4net.Layout.PatternLayoutà à à à à à à à conversionPattern value%d [%t] %-5p %c %m%n /à à à à à à /layoutà à à à /appenderà à /log4net/configuration The log4net online documentation explains all the config file fields. à Having set up App.config, add using log4net and this line: [assembly: log4net.Config.XmlConfigurator(Watch true)] Plus the actual logger has to be fetched with a call to LogManager.GetLogger(...). The GetLogger is usually called with the typeof(class) that its used in, but this function call also fetches that: System.Reflection.MethodBase.GetCurrentMethod().DeclaringType This example shows both in with one commented, so you can choose.à using log4net;[assembly: log4net.Config.XmlConfigurator(Watch true)]namespace gvmake{à à à à class Programà à à à {à à à à à à à à private static readonly ILog log LogManager.GetLogger (System.Reflection.MethodBase.GetCurrentMethod().DeclaringType) ;à à à à à à à à //private static readonly ILog log LogManager.GetLogger(typeof (Program)) ;à à à à à à à à static void Main(string[] args)à à à à à à à à {à à à à à à à à à à à à log.Debug(Application Starting) ;à à à à à à à à }à à à à }}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.