PostSharp 結合 log4net 自動記錄日志


環境:

VS 2012

PostSharp-4.1.28  (下載地址)https://visualstudiogallery.msdn.microsoft.com/a058d5d3-e654-43f8-a308-c3bdfdd0be4a/file/89212/69/PostSharp-4.1.28.exe

log4net 2.0.3

 

 

首先搭建環境:

下載好PostSharp 之后進行安裝。之后創建項目

1、引用PoastSharp

PoastSharp引用方式如下:

VS工具 —>> NuGet 程序包管理 —>> 管理解決方案的NuGet程序包       出現如下圖:

搜索PostSharp 安裝等待...

安裝完成之后會在項目的解決方案同級目錄下出現下列文件:

同時解決方案里面的項目會自動出現PostSharp的引用、

如果沒有自動引用,我們就手動引用下就好了。 根據.NET Framework的版本,選擇對應的dll

PostSharp.dll  安裝引用已經OK了。

 

2、log4net安裝引用

打開 VS工具 —>> NuGet 程序包管理 —>>  程序包管理器控制台

在控制台中輸入 PM> Install-Package log4net  (PM> 是已經有了的)敲回車鍵

然后安心等待...(上面的紅色的Error是因為網速比較慢,沒有Load出來, 沒有關系再來一次)

下面第二次可以看見已經安裝成功,並且把我的機器上老版本替換掉了。   干得漂亮!!!

如PostSharp 一樣,也會在解決方案下面出現lib文件, 如果項目里面沒有引用的就手動引用好了。

 

接下來開始真正的干活了......

首先配置好log4net.config

下面是我習慣的步驟:

1、在應用程序下創建 App.config 文件

2、修改App.config 文件的內容(直接復制替換好了,詳細的配置項就不說明了)

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>

  <log4net>
    <!-- You can add your own appender here. -->
    <!-- Define some output appenders -->
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <!--
    This appender is used for writing application log.
    -->
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <!-- Log file name, you can find the file in the application startup directory. -->
      <param name="File" type="log4net.Util.PatternString" value="Log\Client_%date{yyyyMMddHHmmss}.log"/>
      <param name="Encoding" value="UTF-8"/>
      <param name="AppendToFile" value="true"/>
      <param name="MaxSizeRollBackups" value="10"/>
      <!-- 
      The maximum size of the log file, 
      when the log file size exceed this size, 
      a new log.txt will created and the old one will rename to log.txt.1.
      -->
      <param name="MaximumFileSize" value="2MB"/>
      <param name="RollingStyle" value="Size"/>
      <param name="StaticLogFileName" value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date [%thread] %logger %-5level - %message%newline"/>
      </layout>
    </appender>
    <!-- 
    The root logger.
    Set the level to log the necessary log information only.
    The level can be set to: ALL, DEBUG, INFO, WARN, ERROR, Fatal
    The appender-ref can be set the any appender name in this configuration file.
    -->
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingFileAppender"/>
      <appender-ref ref="ConsoleAppender"/>

    </root>
  </log4net>
</configuration>
View Code

3、接着很重要的一步,不然配置的都白干了...

打開AssemblyInfo.cs文件,在文件最后添加一行代碼

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

 

好的,到此。log4net 已經配置完成。  可以先測試一下log4net 是否可以正常工作

創建一個空的WinForm,添加如下代碼

using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using log4net;

namespace PostSharp.Demo
{
    public partial class TestLog4netFrm : Form
    {
        public static log4net.ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public TestLog4netFrm()
        {
            InitializeComponent();
        }

        private void TestLog4netFrm_Load(object sender, EventArgs e)
        {
            _logger.Debug("test log4net ");
        }
    }
}
View Code

然后生成運行。

運行成功之后,關掉Form。  打開bin/Debug 可以看見有一個Log文件夾里面會生成一個日志文件,打開可以看見我們剛才寫的 test log4net

好的。 干得漂亮!!! 已經成功一半了。即使不用postSharp也可以完成日常的打Log了。 

 

為了繼續完善,把PostSharp使用起來,讓它給我們自動的打Log。

1、創建項目 PostSharp.Core ,創建文件TraceAttribute.cs 

 TraceAttribute.cs  代碼如下:(格式可以根據需要自己調整的...)

using System;
using System.Collections.Generic;
using System.Text;
using PostSharp.Aspects;
using PostSharp.Extensibility; 
using System.Reflection;

namespace PostSharp.Core
{
    [Serializable]
    public sealed class TraceAttribute : OnMethodBoundaryAspect
    {
        // Create a logger for use in this class, called only once
        private static readonly log4net.ILog _logger;

        private string _methodName;

        // These fields are initialized at runtime. They do not need to be serialized.
        [NonSerialized]
        private int _hashCode;

        static TraceAttribute()
        {
            if (!PostSharpEnvironment.IsPostSharpRunning)
            {
                _logger =
                    log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
            }
        }


        // Default constructor, invoked at build time.
        public TraceAttribute()
        {
            // Do nothing
        }

        // Invoked only once at runtime from the static constructor of type declaring the target method.
        public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
        {
            _methodName = method.DeclaringType.Name + "." + method.Name;
        }


        // Invoked only once at runtime from the static constructor of type declaring the target method.
        public override void RuntimeInitialize(MethodBase method)
        {
            _hashCode = this.GetHashCode();
        }

        // Invoked at runtime before that target method is invoked.
        public override void OnEntry(MethodExecutionArgs args)
        {
            _logger.DebugFormat(">>> Entry [{0}] {1}", _hashCode, _methodName);
        }

        // Invoked at runtime after the target method is invoked (in a finally block).
        public override void OnExit(MethodExecutionArgs args)
        {
            _logger.DebugFormat("<<< Exit [{0}] {1}", _hashCode, _methodName);
        }

        // Invoked at runtime when there is unhandled exception from the target method
        public override void OnException(MethodExecutionArgs args)
        {
            string expMsg = string.Format("!!! Exception [{0}] {1} {2}", _hashCode, _methodName, args.Exception.Message);
            _logger.ErrorFormat(expMsg, args.Exception);
        }

        // Invoked at runtime when await starts in the target method
        public override void OnYield(MethodExecutionArgs args)
        {
            _logger.DebugFormat("--- OnYield [{0}] {1}", _hashCode, _methodName);
        }

        // Invoked at runtime when await resumed in the target method
        public override void OnResume(MethodExecutionArgs args)
        {
            _logger.DebugFormat("--- OnResume [{0}] {1}", _hashCode, _methodName);
        }
    }
}
View Code

2、很重要的一步,PostSharp.Core 項目的 AssemblyInfo.cs 文件也需要在最后加上一句代碼。同上

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

好了,到此。  安裝,引用,配置已經全部結束。 開始測試...

 

創建新的Form,(什么都不需要寫,就使用Load事件好了)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using log4net;
using PostSharp.Core;
using System.Reflection;

namespace PostSharp.Demo
{
    public partial class TestPostSharpFrm : Form
    {
        public static log4net.ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public TestPostSharpFrm()
        {
            InitializeComponent();
        }

        [Trace]
        private void TestPostSharpFrm_Load(object sender, EventArgs e)
        {

        }
    }
}
View Code

然后直接運行、可以看見下面就是我們在TraceAttribute.cs 中配置好的輸出格式

全部OK。  干的非常漂亮!!!

From需要應用下面的命名空間

using log4net;
using PostSharp.Core;
using System.Reflection;

 

 

 

可以看看編譯過后的代碼:

1、未使用PostSharp 的代碼

2、使用PostSharp 打過標簽的代碼

 

不難看出,PostSharp,會在編譯之后把Log注入到代碼中去。

同時每個方法的執行位置一目了然...

 

源碼下載地址:http://files.cnblogs.com/files/chris-zeng/PostSharp.Demo.rar

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM