对于企业库异常处理,这里做个简单的介绍和笔记。
环境
VS2012, .NET Framework 4.0, Microsoft Enterprise Library 6.0
准备工作
1. 下载Enterprise Library配置编辑工具:Microsoft.Practices.EnterpriseLibrary.ConfigConsoleV6.vsix。
下载地址:http://www.microsoft.com/en-us/download/details.aspx?id=38789
2. 通过 NuGet 添加所需要的企业库模块。
异常处理需要添加Microsoft Enterprise Library的ExceptionHandling,如果要写Log就需要添加ExceptionHandling.Logging 模块。
2.1 右键点击需要使用Exception模块的项目,选择Manage NuGet Packeages。或者选择Tools-> Library Package Manager -> Manage NuGet Packages for Solution。
2.2 在Manage NuGet Packeages窗口里面Online查找Enterprise Library,点击需要安装需要的模块。
3. 安装成功后,Enterprise Library Common 和 Logging Reference会自动添加。
如何使用
1. 右键App.config文件选择Edit configuration file v6配置App.config文件。
2. 选择菜单命令Block -> Add Logging Settings。
3. 在Logging Target Listeners里面点加号按钮,然后选择Add Rolling Flat File Trace Listener(生成可以进行自动分割的文本文件)。
4. 设置的参数:Asynchronous(选true则进行异步log),File Name, Formatter Name, Max Archived Files, Roll Size KB。相比Flat File Trace Listener,Rolling Flat File Trace Listener 可以通过Roll Interval来设置新文件自动增加的间隔。
5. 在窗口左侧区域中添加一个新的Category,并修改Name属性。然后点击Listeners选择刚才添加的Rolling Flat File Trace Listener。
6. 通过以下代码代用log功能。Cateogry名字应该和第9步中的名字一样。
Logger.SetLogWriter(new LogWriterFactory().Create()); Logger.Write("Test", "MyLog", 0, 0, System.Diagnostics.TraceEventType.Information); Dictionary<string, object> dic = new Dictionary<string, object>() { { "Projec", "world" }, { "Method", "hello" }, }; Logger.Write("test1", "MyLog", 0, 0, System.Diagnostics.TraceEventType.Error, "", dic);