PostSharp在window8中的使用

本文指导如何在C#项目中安装并配置PostSharp,通过实现自定义属性来记录方法执行日志。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、安装NuGet工具。

     打开VS,在菜单“工具”->"扩展管理器",选择联机库,选择安装NuGet程序包管理器

2、安装PostSharp3.0.0版本。下载地址:http://www.postsharp.net/download 

3、打开VS,创建控制台应用程序。

      右击项目,可以看到PostSharp选项。给这个项目添加PostSharp。完成这些动作之后,这个项目就可以使用PostSharp了。

     代码如下:

class Program
    {
        static void Main(string[] args)
        {
            Describe();
            Console.Read();
        }

        [Exception]
        public static void Describe()
        {
            Console.WriteLine(String.Format("hello PostSharp"));
        }
    }
}
[Serializable]
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class ExceptionAttribute : OnMethodBoundaryAspect
    {

        public override void OnEntry(MethodExecutionArgs eventArgs)
        {
            Util.Writelog("开始执行");
        }

        public override void OnExit(MethodExecutionArgs eventArgs)
        {
            Util.Writelog("成功完成");
        }

    }


 

 public class Util
    {
        private const String _errLogFilePath = @"log.txt";

        public static void Writelog(String message)
        {
            StreamWriter sw = new StreamWriter(_errLogFilePath, true);
            String logContent = String.Format("[{0}]{1}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"), message);
            sw.WriteLine(logContent);
            sw.Flush();
            sw.Close();
        }

    }



 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值