0

我已经执行了所有可能的步骤,如 web.config 中的配置、管理 global.aspx 页面等,但记录未存储在数据库表中。当我们输入用户名 =“sameer”和密码是 =“singh123”时,我有一个名为 Account controller 的控制器,但我输入了错误的密码,我想将此错误日志保存在数据库中

  <logger name="SMSBA">
    <appender-ref ref="ADONetAppender" />
  </logger>
  <param name="File" value="log-file.txt" />
  <param name="AppendToFile" value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="10MB" />
  <staticLogFileName value="true" />
  <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  <add name="SMSBA" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=SMSBA;" providerName="System.Data.SqlClient" />
  <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" />
  <parameter>
    <parameterName value="@log_date" />
    <dbType value="DateTime" />
    <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" />
  </parameter>
  <parameter>
    <parameterName value="@thread" />
    <dbType value="String" />
    <size value="255" />
    <layout type="log4net.Layout.PatternLayout" value="%thread" />
  </parameter>
  <parameter>
    <parameterName value="@log_level" />
    <dbType value="String" />
    <size value="50" />
    <layout type="log4net.Layout.PatternLayout" value="%level" />
  </parameter>
  <parameter>
    <parameterName value="@logger" />
    <dbType value="String" />
    <size value="255" />
    <layout type="log4net.Layout.PatternLayout" value="%logger" />
  </parameter>
  <parameter>
    <parameterName value="@message" />
    <dbType value="String" />
    <size value="4000" />
    <layout type="log4net.Layout.PatternLayout" value="%message" />
  </parameter>
</appender>
<root>
  <level value="All"/>
  <appender-ref ref="AdoNetAppender_SqlServer"/>
</root>

这是 web.config 文件

public class MvcApplication : NinjectHttpApplication
{
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        //filters.Add(new log4netExceptionFilter()); 
        filters.Add(new HandleErrorAttribute());

    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Account", action = "LogOn", id = UrlParameter.Optional } // Parameter defaults
        );





    }
    protected override void OnApplicationStarted()
    {
        log4net.Config.XmlConfigurator.Configure();
        log4net.ILog log = log4net.LogManager.GetLogger(this.GetType());
        log.Info("stuff");
        log.Info("stuff");

        log.Debug("log Debug");
            log.Info("log Info");
            log.Warn("log Warn");
            log.Error("log Error");
            log.Fatal("log Fatal"); 
        SMSBAContextInitializer.Init();
        const string userName = "Administrator";
        if (Membership.GetUser(userName) == null)
        {
            Membership.CreateUser(userName, "test##123");
        }
        AreaRegistration.RegisterAllAreas();
        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
        RegisterAllControllersIn(Assembly.GetExecutingAssembly());
    }

    protected override IKernel CreateKernel()
    {
        var modules = new INinjectModule[]
        {
            new ServiceModule()
        };

        return new StandardKernel(modules);
    }
    internal class ServiceModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IFormsAuthenticationService>().To<FormsAuthenticationService>();
            Bind<IMembershipService>().To<AccountMembershipService>();
            Bind<MembershipProvider>().ToConstant(Membership.Provider);
            Bind<IDepartmentRepository>().To<DepartmentRepository>();
            Bind<IPersonnelRepository>().To<PersonnelRepository>();
            Bind<IPersonnelTitleRepository>().To<PersonnelTitleRepository>();
            Bind<IProcessInputRepository>().To<ProcessInputRepository>();
            Bind<ILoggingService>().To<Logging>();
        }
    }
}

这是全局 .asax 文件

public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    if (MembershipService.ValidateUser(model.UserName, model.Password))
                    {
                        FormsService.SignIn(model.UserName, model.RememberMe);
                        if (Url.IsLocalUrl(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            return RedirectToAction("Index", "Department");
                        }
                    }
                    else
                    {
                        _loggingService.Log("Password changed for user " + model.UserName);
                       // AddError("The user name or password provided is incorrect.");
                        ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    }
                }

            }

            catch (Exception ex)
            {
                if (Logger.IsErrorEnabled)
                {
                    AddError(ex.Message);
                    Logger.Error("login error : " + ex.Message);
                }
            }
            return View(model);
        }

这是控制器代码

4

1 回答 1

2

如果没有更多信息,不确定会发生什么,但我会为您提供有关如何排除故障的建议

在 web.config 上添加以下行

<!--Enables log4net internal debugging-->
<appSettings>
    <add key="log4net.Internal.Debug" value="true"/>
</appSettings>

<!--Sets an output file for the internal debugging. Without this, 
 it outpusts to the console-->
<system.diagnostics>
  <trace autoflush="true">
    <listeners>
      <add 
        name="textWriterTraceListener" 
        type="System.Diagnostics.TextWriterTraceListener" 
        initializeData="C:\tmp\log4net.txt" />
    </listeners>
  </trace>
</system.diagnostics>
于 2012-09-13T12:33:18.677 回答