3

我使用 Common.Logging 作为 NLog 2.0 的包装器。我这样做是为了将来可以用另一个日志记录提供程序替换 NLog。

我还使用 PostSharp 来避免每次需要时都编写 try catch 块。我有一个继承 OnMethodBoundaryAspect 的类:

[Serializable]
public class LogMethodAttribute : OnMethodBoundaryAspect
{
    private ILog logger;

    public LogMethodAttribute()
    {
        this.logger = LogManager.GetCurrentClassLogger();
    }

    public override void OnEntry(MethodExecutionArgs args)
    {
        logger.Debug(string.Format("Entering {0}.{1}.", args.Method.DeclaringType.Name, args.Method.Name));
    }

    public override void OnExit(MethodExecutionArgs args)
    {
        logger.Debug(string.Format("Leaving {0}.{1}.", args.Method.DeclaringType.Name, args.Method.Name));
    }

    public override void OnException(MethodExecutionArgs args)
    {
        logger.Error(args.Exception.Message,args.Exception);
    }
}

我在 web.config 中配置了 Common.Logging,如下所示:

<configSections>
<sectionGroup name="common">
  <section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
</configSections>
<common>
<logging>
  <factoryAdapter type="Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog20">
    <arg key="configType" value="FILE" />
    <arg key="configFile" value="~/NLog.config" />
  </factoryAdapter>
</logging>
</common>

NLog.Config 看起来像这样:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  throwExceptions="true"
  internalLogLevel="Debug"
  internalLogToConsoleError="true"
  internalLogFile="c:\new projects/nlog-app.txt"
>

<!-- 
See http://nlog-project.org/wiki/Configuration_file 
for information on customizing logging rules and outputs.
 -->
<targets>
<target name="database"
        xsi:type="Database"
        commandText="INSERT INTO LogEvent(EventDateTime, EventLevel, UserName, MachineName, EventMessage, ErrorSource, ErrorClass, ErrorMethod, ErrorMessage, InnerErrorMessage) VALUES(@EventDateTime, @EventLevel, @UserName, @MachineName, @EventMessage, @ErrorSource, @ErrorClass, @ErrorMethod, @ErrorMessage, @InnerErrorMessage)"

        dbProvider="System.Data.SqlClient">
  <connectionString>
    Data Source=...;Initial Catalog=myDB;User Id=user;Password=pass;
  </connectionString>
  <installConnectionString>
     Data Source=...;Initial Catalog=myDB;User Id=user;Password=pass;
  </installConnectionString>

    <!-- parameters for the command -->
  <parameter name="@EventDateTime" layout="${date:s}" />
  <parameter name="@EventLevel" layout="${level}" />
  <parameter name="@UserName" layout="${identity}" />
  <parameter name="@MachineName" layout="${machinename}" />
  <parameter name="@EventMessage" layout="${message}" />
  <parameter name="@ErrorSource" layout="${event-context:item=error-source}" />
  <parameter name="@ErrorClass" layout="${event-context:item=error-class}" />
  <parameter name="@ErrorMethod" layout="${event-context:item=error-method}" />
  <parameter name="@ErrorMessage" layout="${event-context:item=error-message}" />
  <parameter name="@InnerErrorMessage" layout="${event-context:item=inner-error-message}" />
  <!-- commands to install database -->
  <install-command>
    <text>CREATE DATABASE myDB</text>
    <connectionString> Data Source=...;Initial Catalog=myDB;User Id=user;Password=pass;</connectionString>
    <ignoreFailures>true</ignoreFailures>
  </install-command>

  <install-command>
    <text>
      CREATE TABLE LogEvent(
      EventId int primary key not null identity(1,1),
      EventDateTime datetime,
      EventLevel nvarchar(50),
      UserName nvarchar(50),
      MachineName nvarchar(1024),
      EventMessage nvarchar(MAX),
      ErrorSource nvarchar(1024),
      ErrorClass nvarchar(1024),
      ErrorMethod nvarchar(1024),
      ErrorMessage nvarchar(MAX),
      InnerErrorMessage nvarchar(MAX));
    </text>
  </install-command>

  <!-- commands to uninstall database -->
  <uninstall-command>
    <text>DROP DATABASE myDB</text>
    <connectionString> Data Source=...;Initial Catalog=myDB;User Id=user;Password=pass;</connectionString>
    <ignoreFailures>true</ignoreFailures>
  </uninstall-command>

</target>
</targets>

<rules>
<logger name="*" levels="Error" writeTo="database" />
</rules>
</nlog>

问题是我的表中没有插入任何内容。例如,当我将记录器放入索引页面上的 HomeController 并调用我的 logger.Error("an error") 时,它会在我的表中添加一条记录。

有人可以帮助我吗?

4

2 回答 2

0

在你的类 Aspect 中添加一个静态属性记录器

public class LogAspect : OnMethodBoundaryAspect
{
    /// <summary>
    /// Gets or sets the logger.
    /// </summary>
    public static ILogger logger { get; set; }

使用 ILogger 类在应用程序初始化方法中设置记录器变量,并使用 AttributeExclude 在此初始化之前排除所有方法。

    [LogAspect(AttributeExclude = true)]
    protected void Application_Start()
    {
        _windsorContainer = new WindsorContainer();
        ApplicationDependencyInstaller.RegisterLoggingFacility(_windsorContainer);
        LogAspect.logger = _windsorContainer.Resolve<ILogger>();
于 2013-03-13T22:16:26.483 回答
0

您是否使用您创建的 LogMethodAttribute 装饰您的控制器方法?

此外,您需要调整您的记录器规则,以包括“错误”之外的更多级别,否则您将记录的就是这些。

试试这个:

<rules>
<logger name="*" minLevel="Trace" writeTo="database" />
</rules>

编辑:

您是否尝试过将记录器初始化移动到您的方法中?

public override void OnEntry(MethodExecutionArgs args)
{
     this.logger = LogManager.GetCurrentClassLogger();
     logger.Debug(string.Format("Entering {0}.{1}.", args.Method.DeclaringType.Name, args.Method.Name));
}

根据 Donald Belcham 的 Pluralsight 课程,方面构造函数不会在运行时执行,因此您的记录器可能没有正确设置。

于 2013-01-30T01:50:49.650 回答