使用PostSharp和NLog 2.0的Common.Logging

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")时,它会向我的表添加一条记录。
有人可以帮我吗?

我对NLog一无所知,但是这行代码看起来很可疑:this.logger = LogManager.GetCurrentClassLogger();。在这种情况下,这不会获取与方面类相关的“logger”,而不是修饰类? - RJ Lohan
1
“记录器”没问题,它只是将以当前类名命名。 - Chris
2个回答

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课程中的讲解,切面构造函数不会在运行时执行,因此可能您的记录器没有被正确设置。

是的,我已经用LogMethodAttribute装饰了我的方法。在这种特殊情况下,我只需要记录错误,所以只需以错误级别进行日志记录就可以了。 - Jurgen Vandw
@JurgenVandw:抱歉,我想我还在努力理解你的问题...你是说如果你在控制器方法中手动放置logger.Error(),它就可以工作,但OnEntry/OnExit不起作用?你的OnEntry/OnExit日志记录到调试级别,你没有指定在哪里写入调试消息。如果你在控制器方法中手动使用logger.Debug(),它会工作吗?除非你在这里遗漏了一些代码,否则不应该这样。 - Chris

0
在你的Aspect类中添加一个静态属性logger。
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>();

请不要在多个问题中完全发布相同的答案。如果相同的答案适用于多个问题,则说明这些问题是重复的。您应该标记(如果您拥有足够的声望,则关闭),而不是回答。 - ChrisF

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接