常见的.使用PostSharp和NLog 2.0进行日志记录
本文关键字:日志 记录 NLog 使用 PostSharp 常见 | 更新日期: 2023-09-27 17:54:24
我使用Common。日志作为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中记录如下:
<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。配置如下:
<?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我调用记录器。错误("一个错误"),它添加一个记录到我的表。
有人能帮我吗?
您是否使用您创建的LogMethodAttribute来装饰您的控制器方法?
另外,你需要调整你的日志规则,以包括更多的级别,而不仅仅是"Error",否则你将记录所有的日志。
试一试:
<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 belham的Pluralsight课程,方面构造函数不会在运行时执行,所以可能您的记录器没有正确设置。
在类Aspect中添加一个静态属性记录器
public class LogAspect : OnMethodBoundaryAspect
{
/// <summary>
/// Gets or sets the logger.
/// </summary>
public static ILogger logger { get; set; }
使用ILogger类在应用程序初始化方法中设置logger变量,并使用AttributeExclude排除初始化之前的所有方法。
[LogAspect(AttributeExclude = true)]
protected void Application_Start()
{
_windsorContainer = new WindsorContainer();
ApplicationDependencyInstaller.RegisterLoggingFacility(_windsorContainer);
LogAspect.logger = _windsorContainer.Resolve<ILogger>();