Mahmoud ElMansy: knowledge meant to be free

Using Log4net for logging with asp.net and MVC log into SQL Table

I will write this article to show how to use Log4net with MVC.
First you need to read about Log4net

And for shower log4net is one of the best solutions for logging.

Now let us start

1) Download the Dlls from the site.

2) Add reference to it into your project.

3) Create The table in the attached project to make log Table.

4) If you are using MVC site add this section into your AssemblyInfo.cs .

using log4net.Config;
// this for Log4net
[assembly: XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]

 

5) If the file “Log4Net.config” will be in a custom folder just use this code.

System.IO.FileInfo l4net = new System.IO.FileInfo(Server.MapPath("~/Log4Net.config"));
//System.IO.FileInfo l4net = new System.IO.FileInfo("Log4Net.config");// if you are using console or desktop application
log4net.Config.XmlConfigurator.ConfigureAndWatch(l4net);

6) To declare the log4net class.

//logger = log4net.LogManager.GetLogger(typeof(Program));//the Program is the name of the current class
// or you can use
logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

logger.Info("Test message for Log4Net");
logger.Warn("Test message for Log4Net");
logger.Error("Test message for Log4Net");
logger.Debug("Test message for Log4Net");

You can download a Consol sample TestLog4net

That is all hope you enjoyed the article.