2014-03-25 39 views
1

我有一個MVC 4 application.I嘗試獲取用戶活動日誌記錄。如何在MVC 4中通過Log4Net獲取用戶活動記錄?

我看着這個樣本http://www.oakwoodinsights.com/adding-log4net-mvc-site/

但我failed.Log表是SQL空。

首先,我將log4net.2.0.3包添加到我的項目中。

我在SQL中有這個表。

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] 

我將Log4Net.config添加到我的項目。

http://pastebin.com/RYpq3xTg

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
<log4net> 
<appender name="DbAppender" type="log4net.Appender.ADONetAppender"> 
    <bufferSize value="0" /> 
    <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> 
    <connectionString value="{auto}" /> 
    <commandText value="INSERT INTO Log4Net ([date],[thread],[level],[logger],[message],[exception]) VALUES 
    (@log_date, @thread, @log_level, @logger, @message, @exception)" /> 
    <parameter> 
    <parameterName value="@log_date" /> 
    <dbType value="DateTime" /> 
    <layout type="log4net.Layout.RawTimeStampLayout" /> 
    </parameter> 
    <parameter> 
    <parameterName value="@thread" /> 
    <dbType value="String" /> 
    <size value="255" /> 
    <layout type="log4net.Layout.PatternLayout"> 
     <conversionPattern value="%t" /> 
    </layout> 
    </parameter> 
    <parameter> 
    <parameterName value="@log_level" /> 
    <dbType value="String" /> 
    <size value="10" /> 
    <layout type="log4net.Layout.PatternLayout"> 
     <conversionPattern value="%p" /> 
    </layout> 
    </parameter> 
    <parameter> 
    <parameterName value="@logger" /> 
    <dbType value="String" /> 
    <size value="1000" /> 
    <layout type="log4net.Layout.PatternLayout"> 
     <conversionPattern value="%c" /> 
    </layout> 
    </parameter> 
    <parameter> 
    <parameterName value="@message" /> 
    <dbType value="String" /> 
    <size value="4000" /> 
    <layout type="log4net.Layout.PatternLayout"> 
     <conversionPattern value="%m" /> 
    </layout> 
    </parameter> 
    <parameter> 
    <parameterName value="@exception" /> 
    <dbType value="String" /> 
    <size value="4000" /> 
    <layout type="log4net.Layout.ExceptionLayout" /> 
    </parameter> 
</appender> 

<root> 
    <level value="INFO" /> 
    <appender-ref ref="RollingFileAppender" /> 
    <appender-ref ref="DbAppender" /> 
</root> 

我在控制器中創建一個靜態類

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 && 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; 
    } 
    } 
    } 

在Global.asax.cs中

protected void Application_Start() 
    { 

     Log4NetManager.InitializeLog4Net(); 
     AreaRegistration.RegisterAllAreas(); 

     RegisterGlobalFilters(GlobalFilters.Filters); 
     RegisterRoutes(RouteTable.Routes); 

    } 
調用Log4NetManager.InitializeLog4Net()

最後得到登錄本地主機:1235 /樣品

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(); 

     } 

但我的log4net的表是本地主機的訪問後空:1235 /樣品。

我的錯誤在哪裏?

+0

我想極大地感謝您發佈此代碼,這幫助了我極大! –

回答

0

對不起。我的錯誤是我在SQL中創建了日誌表。

變化

Log 

Log4Net 

它是在MVC用戶活動洛4.

0

如果log4net的表是空的,你可以檢查輸出窗口,以working.Good樣本得到錯誤或警告。

Check Output Windows for Errors on Log4Net

相關問題