title: How to get user activity logging by Log4Net in MVC 4?
body: <p>I have a MVC 4 application.I tried get user activity logging.</p>
  
  <p>I looked this sample <a href="http://www.oakwoodinsights.com/adding-log4net-mvc-site/" rel="nofollow">http://www.oakwoodinsights.com/adding-log4net-mvc-site/</a></p>
  
  <p>But I failed.Log table is empty in SQL.</p>
  
  <p>Firstly I added log4net.2.0.3 package to my project.</p>
  
  <p>I have this table in SQL.</p>
  
  <pre><code>CREATE TABLE [dbo].[Log4Net] (
  [ID] [int] IDENTITY (1, 1) NOT NULL ,
  [Date] [datetime] NOT NULL ,
  [Thread] [varchar] (255) NOT NULL ,
  [Level] [varchar] (10) NOT NULL ,
  [Logger] [varchar] (1000) NOT NULL ,
  [Message] [varchar] (4000) NOT NULL ,
  [Exception] [varchar] (4000) NOT NULL
  
  ) ON [PRIMARY]
  </code></pre>
  
  <p>I added Log4Net.config to my project.</p>
  
  <p><a href="http://pastebin.com/RYpq3xTg" rel="nofollow">http://pastebin.com/RYpq3xTg</a></p>
  
  <pre><code> &lt;?xml version="1.0" encoding="utf-8" ?&gt;
   &lt;configuration&gt;
   &lt;log4net&gt;
  &lt;appender name="DbAppender" type="log4net.Appender.ADONetAppender"&gt;
    &lt;bufferSize value="0" /&gt;
    &lt;connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /&gt;
    &lt;connectionString value="{auto}" /&gt;
    &lt;commandText value="INSERT INTO Log4Net ([date],[thread],[level],[logger],[message],[exception]) VALUES
      (@log_date, @thread, @log_level, @logger, @message, @exception)" /&gt;
    &lt;parameter&gt;
      &lt;parameterName value="@log_date" /&gt;
      &lt;dbType value="DateTime" /&gt;
      &lt;layout type="log4net.Layout.RawTimeStampLayout" /&gt;
    &lt;/parameter&gt;
    &lt;parameter&gt;
      &lt;parameterName value="@thread" /&gt;
      &lt;dbType value="String" /&gt;
      &lt;size value="255" /&gt;
      &lt;layout type="log4net.Layout.PatternLayout"&gt;
        &lt;conversionPattern value="%t" /&gt;
      &lt;/layout&gt;
    &lt;/parameter&gt;
    &lt;parameter&gt;
      &lt;parameterName value="@log_level" /&gt;
      &lt;dbType value="String" /&gt;
      &lt;size value="10" /&gt;
      &lt;layout type="log4net.Layout.PatternLayout"&gt;
        &lt;conversionPattern value="%p" /&gt;
      &lt;/layout&gt;
    &lt;/parameter&gt;
    &lt;parameter&gt;
      &lt;parameterName value="@logger" /&gt;
      &lt;dbType value="String" /&gt;
      &lt;size value="1000" /&gt;
      &lt;layout type="log4net.Layout.PatternLayout"&gt;
        &lt;conversionPattern value="%c" /&gt;
      &lt;/layout&gt;
    &lt;/parameter&gt;
    &lt;parameter&gt;
      &lt;parameterName value="@message" /&gt;
      &lt;dbType value="String" /&gt;
      &lt;size value="4000" /&gt;
      &lt;layout type="log4net.Layout.PatternLayout"&gt;
        &lt;conversionPattern value="%m" /&gt;
      &lt;/layout&gt;
    &lt;/parameter&gt;
    &lt;parameter&gt;
      &lt;parameterName value="@exception" /&gt;
      &lt;dbType value="String" /&gt;
      &lt;size value="4000" /&gt;
      &lt;layout type="log4net.Layout.ExceptionLayout" /&gt;
    &lt;/parameter&gt;
  &lt;/appender&gt;
  
  &lt;root&gt;
    &lt;level value="INFO" /&gt;
    &lt;appender-ref ref="RollingFileAppender" /&gt;
    &lt;appender-ref ref="DbAppender" /&gt;
  &lt;/root&gt;
  </code></pre>
  
  <p>
  </p>
  
  <p>I created a static class in Controller</p>
  
  <pre><code>namespace MyApp.Controllers
  
  {
  
  public static class Log4NetManager
  {
  
  
      public static void InitializeLog4Net()
  
      {
          XmlConfigurator.ConfigureAndWatch(new FileInfo(System.AppDomain.CurrentDomain.BaseDirectory + @"\Log4Net.config"));
  
          Hierarchy hier = log4net.LogManager.GetRepository() as Hierarchy;
  
          if (hier != null)
          {
              AdoNetAppender adoAppender = (from appender in hier.GetAppenders()
                                            where appender.Name.Equals("DbAppender", StringComparison.InvariantCultureIgnoreCase)
                                            select appender).FirstOrDefault() as AdoNetAppender;
  
              if (adoAppender != null &amp;&amp; adoAppender.ConnectionString.Contains("{auto}"))
              {
                  adoAppender.ConnectionString = ExtractConnectionStringFromEntityConnectionString(
                          GetEntitiyConnectionStringFromWebConfig());
  
                  //refresh settings of appender
                  adoAppender.ActivateOptions();
  
              }
          }
  
      }
  
  
      private static string GetEntitiyConnectionStringFromWebConfig()
      {
          return ConfigurationManager.ConnectionStrings["MemberEntities"].ConnectionString;
  
   //MemberEntities is like this in  Web.Config : http://pastebin.com/R9wCwRar
  
  
    }
  
  
      private static string ExtractConnectionStringFromEntityConnectionString(string entityConnectionString)
      {
          // create a entity connection string from the input
          EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(entityConnectionString);
  
          // read the db connectionstring
          return entityBuilder.ProviderConnectionString;
      }
     }
    }
  </code></pre>
  
  <p>Called Log4NetManager.InitializeLog4Net() in Global.asax.cs</p>
  
  <pre><code>protected void Application_Start()
      {
  
          Log4NetManager.InitializeLog4Net();
          AreaRegistration.RegisterAllAreas();
  
          RegisterGlobalFilters(GlobalFilters.Filters);
          RegisterRoutes(RouteTable.Routes);
  
      }
  </code></pre>
  
  <p>And finally get log in localhost:1235/Sample</p>
  
  <pre><code>    public class SampleController : Controller
  
    {
      //
      // GET: /Sample/
  
      public ActionResult Index()
      {
          ILog logger = LogManager.GetLogger(typeof(SampleController));
  
          // get current user
          string user = HttpContext.User.Identity.ToString();
  
          logger.Debug("Debug messages are not recorded due to log level");
          logger.Info("User : "+" "+user.ToString()+" "+"was here");
  
  
          try
          {
              throw new InvalidOperationException();
          }
  
          catch (Exception ex)
          {
  
              logger.Error("An Error Happened! ", ex);
  
          }
  
          }
  
         return View();
  
          }
  </code></pre>
  
  <p>But my Log4Net Table is empty after visit localhost:1235/Sample.</p>
  
  <p>Where is my mistake ? </p>