Log4Net – Logging for .NET

Before I was thinking of rewriting my own logging for my application but after having a careful thought, I decided just to get one from NuGet package instead of reinventing the wheel. I heard a lot about Log4Net and decided to try that out. It’s really simple to get this logging up and running on your application

This is what you need to do:

1. install Log4Net from NuGet

2. Modify your web.config to add a new section and new configuration – In this case, I decided to use FileLogger. but you can have different type logger if you want (e.g event log, console, etc) or you can even build your own one that implemented ILog, this configuration allow you to create a new log file when the log file already reached the limit

Code Snippet
  1. <configSections>
  2.     <section name=log4nettype=log4net.Config.Log4NetConfigurationSectionHandler, log4net />
  3.   </configSections>
  4.   <log4net>
  5.     <root>
  6.       <levelvalue=DEBUG />
  7.       <appender-ref ref=LogFileAppender />
  8.     </root>
  9.     <appender name=LogFileAppender type=log4net.Appender.RollingFileAppender >
  10.       <param name=Filevalue=C:\\log.txt />
  11.       <param name=AppendToFilevalue=true />
  12.       <rollingStyle value=Size />
  13.       <maxSizeRollBackups value=10 />
  14.       <maximumFileSize value=10MB />
  15.       <staticLogFileName value=true />
  16.       <layout type=log4net.Layout.PatternLayout>
  17.         <param name=ConversionPattern value=%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n />
  18.       </layout>
  19.     </appender>
  20.   </log4net>

3. Code implementation – in this case I decided to register it in my global container and retrieve it later. You need to call log4net.Config.XmlConfigurator.Configure in order for Log4Net to get the settings from web.config – This is very important otherwise you will find that there is no log being generated

Code Snippet
  1. protected void Application_Start()
  2.         {
  3.             AreaRegistration.RegisterAllAreas();
  4.             RegisterGlobalFilters(GlobalFilters.Filters);
  5.             RegisterRoutes(RouteTable.Routes);
  6.             BundleTable.Bundles.RegisterTemplateBundles();
  7.             RegisterDependency();
  8.         }
  9.         #region “Dependency Injection”
  10.         private static Container Container;
  11.         public static T GetInstance<T>() where T : class
  12.         {
  13.             return Container.GetInstance<T>();
  14.         }
  15.         protected void RegisterDependency()
  16.         {
  17.             //Create a main containers
  18.             var container = new Container();
  19.             // 2. Configure the container (register)
  20.             container.RegisterPerWebRequest<IUnitOfWork>(() => new UnitOfWork(new PosDataContext()));
  21.             //Register logger
  22.             log4net.Config.XmlConfigurator.Configure();
  23.             container.Register<ILog>(() => log4net.LogManager.GetLogger(typeof(MvcApplication)));
  24.             container.Verify();
  25.             Container = container;
  26.         }
  27.         #endregion

calling the logger from my code (controller in this context)

Code Snippet
  1. public ActionResult Index()
  2.         {
  3.             ViewBag.Message = “Menu”;
  4.             MvcApplication.GetInstance<ILog>().Info(“Test Info”);
  5.             MvcApplication.GetInstance<ILog>().Error(“Test Error”);
  6.             MvcApplication.GetInstance<ILog>().Debug(“Test Debug”);
  7.             return View();
  8.         }

PS: if you want to implement your own logger, then I’d recommend you to have your logger to implement ILog interface and change it through web.config but don’t wrap/call Log4Net inside your custom logger because you don’t want to limit the rich functionality of Log4Net with your custom logger

Another tips, is when you started to add logging in your application then there should be some performance overhead eventhough it is minor. In the example below MyFunctionOutput function will still be called eventhough you disabled the logging on the config, in order to make sure the debugging code only executed

Code Snippet
  1. MvcApplication.GetInstance<ILog>().Debug(“My Function Output:” + MyFunctionOutput());

When you want to have the debug/logging omitting the log whenever the logging is enabled then you can wrap around the logging with this property (there are another properties IsErrorEnabled, IsInfoEnabled, etc)

Code Snippet
  1. if (MvcApplication.GetInstance<ILog>().IsDebugEnabled)
  2.             {
  3.                 MvcApplication.GetInstance<ILog>().Debug(“My Function Output:” + MyFunctionOutput());
  4.             }

2 thoughts on “Log4Net – Logging for .NET

    1. Just looked at it and will try that, seems more interesting than log4net

      apart from that, do you know is there any .NET handler that can intercept any exception without requiring code changes? e.g let’s say website is down and no logging, etc can I just plug ELMAH and get the exception?Because It is AXD which is HTTP handler then I assume it should be able to trap some error right without making changes to the code?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s