因为是在Drupal中遇到的问题,所以就在Drupal中解决。原因很简单,就是Drupal 6.x不支持PHP 5.3,Drupal 7没有这个问题,解决办法也很多。最简单的莫过于降级到PHP 5.2.x,如果由于一些特别的原因必须使用PHP 5.3+的话,可以尝试下列办法。 打开Drupal安装目录下的includes/common.inc文件,找到590行(如果没有修改过的话),显示的应该是
|
1 |
if ($errno & (E_ALL ^ E_NOTICE)) { |
将这一行替换成
|
1 |
if ($errno & (E_ALL & ~E_NOTICE & ~E_DEPRECATED)) { |
这一句将禁止所有Deprecated错误信息。如果你安装了Developer Tools模块的话,那么还需要修改devel/devel.module的460行,方法相同。 如果这个办法不好用的话,可以尝试修改php.ini。 打开php.ini,找到
|
1 |
error_reporting = E_ALL |
改成
|
1 |
error_reporting = E_ALL & ~E_DEPRECATED |
道理是一样的。 如果还不行,或者因为各种原因改不了以上两处的话,还有办法。 打开drupal\includes\file.inc文件,找到895行,如下。
|
1 |
elseif ($depth >= $min_depth && ereg($mask, $file)) { |
注意,如果895行不是这句的话,就在附近找找,或者直接搜索这句,找到以后把这句改为
|
1 |
elseif ($depth >= $min_depth && mb_ereg($mask, $file)) { |
这样怎么着应该都行了。 养成良好的编程习惯,修改之前务必备份。 from url:http://www.baifeng.me/web/hosting/2010/03/1240/
View Details静态方法的规则和静态变量是相同的。使用ststic关键字可以将方法标识为静态方法,通过类的名称和作用域限定操作符::可以访问静态方法。 静态方法和非静态方法之间有一个很重要的区别,就是在调用静态方法时,我们不需要创建类的实例。 Program List:用类名作为参数 用类名作为参数可以解决非继承的静态问题。 01 <?php 02 classFruit { 03 publicstatic$category= "I'm fruit"; 04 05 staticfunctionfind($class) 06 { 07 $vars= get_class_vars($class) ; 08 echo$vars['category'] ; 09 } 10 } 11 12 classApple extendsFruit { 13 publicstatic$category= "I'm Apple"; 14 } 15 16 Apple::find("Apple"); 17 ?> 程序运行结果: 1 I'm Apple Program List:重写基类方法 在派生类重写基类的方法。 01 <?php 02 classFruit 03 { 04 staticfunctionFoo ( $class= __CLASS__) 05 { 06 call_user_func(array($class, 'Color')); 07 } 08 } 09 10 classApple extendsFruit 11 { 12 staticfunctionFoo ( $class= __CLASS__) 13 { 14 parent::Foo($class); 15 } 16 17 staticfunctionColor() 18 { 19 echo"Apple's color is red"; 20 } 21 } 22 […]
View Details一、 PHP抓取页面的主要方法: 1. file()函数 2. file_get_contents()函数 3. fopen()->fread()->fclose()模式 4.curl方式 5. fsockopen()函数 socket模式 6. 使用插件(如:http://sourceforge.net/projects/snoopy/) 二、PHP解析html或xml代码主要方式: 1. file()函数 <?php $url=’http://t.qq.com’; $lines_array=file($url); $lines_string=implode(”,$lines_array); echo htmlspecialchars($lines_string); ?> 2. file_get_contents() 函数 使用file_get_contents和fopen必须空间开启allow_url_fopen。 方法:编辑php.ini,设置 allow_url_fopen = On,allow_url_fopen关闭时fopen和file_get_contents都不能打开远程文件。 <?php $url=’http://t.qq.com’; $lines_string=file_get_contents($url); echo htmlspecialchars($lines_string); ?>3. fopen()->fread()->fclose()模式 <?php $url=’http://t.qq.com’; $handle=fopen($url,”rb”); $lines_string=”"; do{ $data=fread($handle,1024); if(strlen($data)==0){break;} $lines_string.=$data; }while(true); fclose($handle); echo htmlspecialchars($lines_string); ?>4. curl方式 使用curl必须空间开启curl。方法:windows下修改php.ini,将extension=php_curl.dll前面的分号去掉,而且需 要拷贝ssleay32.dll和libeay32.dll到C:\WINDOWS\system32下;Linux下要安装curl扩展。 <?php $url=’http://t.qq.com’; $ch=curl_init(); $timeout=5; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $lines_string=curl_exec($ch); curl_close($ch); echo htmlspecialchars($lines_string); ?>5. fsockopen()函数 socket模式 socket模式能否正确执行,也跟服务器的设置有关系,具体可以通过phpinfo查看服务器开启了哪些通信协议,比如我的本地php socket没开启http,只能使用udp测试一下了。 <?php $fp = fsockopen(“udp://127.0.0.1″, 13, $errno, $errstr); if (!$fp) { echo […]
View Details一:首先查看一下系统下面有没有字体支持 安装字体:sudo apt-get install msttcorefonts 使用中文字体:simhei.ttf 如果没有GOOGLE下载,放到/usr/share/fonts/truetype/目录下,使用的时候直接调用,也可以放到你的网站目录下。 <?php $im = imagecreate(400,300); $black = imagecolorallocate($im, 255, 0, 255); $white = imagecolorallocate($im, 255, 255, 255); $font = “/usr/share/fonts/truetype/msttcorefonts/simhei.ttf”; $string = “this is my second try”; $chinese = “我的好朋友是谁”; //imagestring($im, 10, 10, 10, $string, $white); //imagestring($im, 30, 30, 20, $chinese, 1); imagettftext($im, 20, 0,10, 10, $white, $font, $chinese); imageline($im, 10, 20, 100, 100, 1); header(“Content-type: image/png”); imagepng($im); imagedestroy($im); ?>转自:http://hi.baidu.com/bowengo/item/4e00acd95d2d15fd93a9743c
View Details$size = 300; $image = imagecreatetruecolor($size,$size); //用白色背景,黑色边框画方框 $back = imagecolorallocate($image,255,255,255); $border = imagecolorallocate($image,0,0,0); imagefilledrectangle($image,0,0,$size,$size,$back); //画出白色背景 imagerectangle($image,0,0,$size-1,$size-1,$border); //画出黑色边框 $yellow_x = 150; $yellow_y = 75; $red_x = 100; $red_y = 160; $blue_x = 200; $blue_y = 160; $radius = 150; $yellow = imagecolorallocatealpha($image,255,255,0,75); //此函数将黄色的alpha值调为75,就是透明度 $red = imagecolorallocatealpha($image,255,0,0,75); $blue = imagecolorallocatealpha($image,0,0,255,75); //画三个交叠的圆 imagefilledellipse($image,$yellow_x,$yellow_y,$radius,$radius,$yellow); //此函数就是我要在$image上画一个圆心($yellow_x,$yellow_y)半径为$radius/2颜色为$yellow的圆 imagefilledellipse($image,$red_x,$red_y,$radius,$radius,$red); imagefilledellipse($image,$blue_x,$blue_y,$radius,$radius,$blue); //输出正确的header header(“Content-type: image/png”); //输出结果 imagepng($image); imagedestroy($image);转自:http://yq329.blog.163.com/blog/static/117379566201131821330796/
View Details(1)date 用法: date(格式,[时间]);如果没有时间参数,则使用当前时间. 格式是一个字符串,其中以下字符有特殊意义: U 替换成从一个起始时间(好象是1970年1月1日)以来的秒数 Y 替换成4位的年号. y 替换成2位的年号. F 替换成月份的英文全称.M 替换成月份的英文简称. m 替换成月份数. z 替换成从当年1月1日以来的天数. d 替换成日数. l 替换成星期几的英文全称. D 替换成星期几的英文简称. w 替换成星期几(数字). H 替换成小时数(24小时制). h 替换成小时数(12小时制). i 替换成分钟数. s 替换成秒数. A 替换成”AM”或”PM”. a 替换成”am”或”pm”. S 替换成序数字后缀,例如:”st”,”nd”,”rd”,”th”. 函数返回作过了替换的格式串.(2)getdate(时间) 返回一个哈希表,各下标是: “seconds” — 秒数 “minutes” — 分数“hours” — 小时数 “mday” — 日数 “mon” — 月份数 “year” — 年号 “yday” — 1月1日以来的天数 “weekday” — 星期几,英文全称 “month” — 月份,英文全名 (3)gmdate与date类似,但先将时间转换成格林威治标准时. (4)mktime 用法: mktime(小时数,分数,秒数,月,日,年);返回一个时间值,可用于其他函数. (5)time 用法: time(); 返回1970年1月1日零点以来的秒数.(6)microtime 用法: microtime(); 返回一个字符串,用空格分成两部分,后一部分相当于time()的返回值,前一部分是微秒数. (7)checkdate 用法: checkdate(月,日,年); 返回逻辑真或逻辑假.如果: [1]年在1900和32767之间(包括1900与32767); [2]月在1到12之间;[3]日在该月的允许日数范围内(考虑了闰年); 则返回逻辑真. (8)set_time_limit 用法:set_time_limit(秒数); 规定从该句运行时起程序必须在指定秒数内运行结束, 超时则程序出错退出.
View Details在eclipse或mycelipse中,启动run on server时或查看项目文件时报错: Resource is out of sync with the file system: ‘/Test_1_Struts_Spring_Hibernate/WebContent/WEB-INF/.struts-config.xml.strutside’. 这是文件系统不同步的问题,是因为在eclipse或mycelipse之外对工程中的resource进行修改引起的(或者是由不同的系统间对文件进行修改引起的);但是,有时没有在eclipse或mycelipse之外进行修改,也会报类似的错误。 解决办法:需要手动刷新一下资源管理器。 ( 1)在eclipse或mycelipse中,工程目录右键,选择F5(refresh) (2)设置eclipse或mycelipse自动刷新。 通过Window->Preferences->General->Workspace,选中Refresh automatically。 http://blog.163.com/hjysys1314@126/blog/static/107903208201021105739351/
View Details在安装PHPCMS出现Deprecated: Function set_magic_quotes_runtime() is deprecated 错误,查了一下网络及资料发现是PHP5.3和PHP6.0之后移除了set_magic_quotes_runtime()函数。 set_magic_quotes_runtime(0)函数作用解释 在php.ini的配置文件中,有个布尔值的设置,就是magic_quotes_runtime,当它打开时,php的大部分函数自动的给从外部引入的(包括数据库或者文件)数据中的溢出字符加上反斜线。 当然如果重复给溢出字符加反斜线,那么字符串中就会有多个反斜线,所以这时就要用set_magic_quotes_runtime()与get_magic_quotes_runtime()设置和检测php.ini文件中magic_quotes_runtime状态。 为了使自己的程序不管服务器是什么设置都能正常执行。可以在程序开始用get_magic_quotes_runtime检测设置状态秋决定是否要手工处理,或者在开始(或不需要自动转义的时候)用set_magic_quotes_runtime(0)关掉。 magic_quotes_gpc设置是否自动为GPC(get,post,cookie)传来的数据中的’”/加上反斜线。可以用get_magic_quotes_gpc()检测系统设置。如果没有打开这项设置,可以使用addslashes()函数添加,它的功能就是给数据库查询语句等的需要在某些字符前加上了反斜线。这些字符是单引号(’)、双引号(”)、反斜线(/)与 NUL(NULL 字符)。 解决办法: //@set_magic_quotes_runtime(0); ini_set(“magic_quotes_runtime”,0); 就是用ini_set()办法替代原有的set_magic_quotes_runtime语法。 转自:http://blog.csdn.net/nstwolf/article/details/5806616
View Details说到PHP环境配置与安装,通常以Apache搭载PHP配置为主,随着PHP版本不断更新,对Windows IIS平台的支持也越来越好,在Windows IIS平台上配置安装PHP环境也越来越方便。 在完成Windows 7上搭建Apache+PHP+Mysql环境搭建后,我在Windows 7 IIS7平台上对PHP5.2和PHP5.3进行了配置安装,PHP5.3之前版本在Windows IIS平台上的PHP配置方式主要以ISAPI方式进行,而PHP5.3支持IIS以FastCgi方式运行PHP,这两个PHP5版本的配置安装还是有不小的区别,下面详细介绍ISAPI和FastCgi两种方式在IIS上进行PHP配置的方法。 准备工作 在完成IIS上进行PHP5安装配置工作之前,首先需要下载PHP5.2和PHP5.3,PHP5.3以php-5.3.2-Win32-VC9-x86为准。 Windows7 IIS7安装 在进行IIS7 PHP安装配置之前,首先需要安装IIS7,Windows7默认并没有安装IIS,安装过程如下: 首先进入控制面板,点击程序和功能,再点击左侧打开和关闭Windows功能,勾选Internet Information Services可承载的Web核心,确定安装。 在完成安装后,在勾选Internet信息服务,选择安装必要的IIS功能,注意由于在配置PHP5.2和PHP5.3时,IIS7中是以ISAPI和FastCgi方式配置PHP的,所以Cgi和ISAPI扩展和ISAPI筛选器务必勾选(此处由于我首先以ISAPI方式配置PHP5.2,我没有勾选Cgi),如图: 安装IIS7 在完成Windows7 IIS7的安装后,即可在控制面板中的管理工具中看到Internet信息服务管理器选项。 ISAPI方式 第一步:php.ini配置 解压php-5.2.13-Win32-VC6-x86.zip,重命名为php52iis,将其复制到C盘根目录下,将php.ini-list文件名更改为php.ini,打开php.ini进行配置,注意extension_dir的目录指向必须准确,即 extension_dir = "C:/php52iis/ext" 另外在PHP5.2版本中没有date.timezone选项,所以无需设置。 在完成PHP5.2中php.ini的配置工作后,将其复制至C:WINDOWS目录下,同时将PHP52iis目录下的libmcrypt.dll,libmysql.dll,php5ts.dll三个文件到C:/windows/System32目录下。 第二步:以ISAPI方式配置PHP5.2 打开IIS,选择网站下的Default Web Site中的ISAPI筛选器进行PHP配置工作,即 添加ISAPI筛选器,选择PHP相应的DLL文件然后选择处理程序映射,进行添加脚本映射操作,即 在完成上述IIS7的PHP5配置后,有需要说明一下,默认IIS7下的网站,其绑定的端口为80端口,网站目录为%SystemDrive%inetpubwwwroot,如果你向我一样在此之前安装配置了Apache+PHP的环境,则需要修改默认网站绑定的端口及网站目录,如将80端口改为8080,网站目录指向D:PHPWeb。或者添加一个新网站,即先添加应用程序池,再添加一个网站。 添加默认文档 在完成新网站添加后,请确保处理程序映射中有添加的脚本映射,如果没有,请重复添加脚本映射操作即可。 第三步:重启IIS7服务器 在D:PHPWeb目录下新建一个index.php文件,内容如下 <? phpinfo(); ?> 在游览器中输入http://localhost:8080/,查看PHP5.2配置信息。 至此在Windows7 IIS7上安装配置PHP5.2就算完成了。 FastCgi方式 在Windows7 IIS7上配置PHP5.3,主要以FastCgi方式进行配置,大体上与PHP5.2的配置基本一样。首先解压php-5.3.2-Win32-VC9-x86,重命名为php53iis并将其复制到C盘根目录。 第一步:添加网站 具体添加过程请参考IIS PHP5.2的配置。 第二步:添加FastCgi模块映射 点击处理程序映射,进行添加模块操作,即 配置IIS以FastCgi方式运行PHP5.3 第三步:php.ini配置 首先将php.ini-development重命名为php.ini,并将 fastcgi.impersonate=1 默认为0,如果使用IIS,你需要开启 cgi.fix_pathinfo=1 cgi.force_redirect=0 默认开启,如果你使用IIS,可以将其关闭 其次指定extension_dir目录和date.timezone,即 extension_dir = "C:/php53iis/ext" date.timezone= Asia/Shanghai 其他PHP.INI配置与PHP5.2的配置一样,区别在于,在Windows7 IIS7上配置安装PHP时,并不需要将php.ini及其他文件复制到C:/windows及C:/windows/System32目录下,简单很多 第四步:重启IIS7服务器 同时访问http://localhost:8080/即可。 FastCGI进程意外退出如何解决? 在使用Windows7 IIS7进行PHP配置安装过程中,如果PHP配置不正确,会出现FastCGI进程意外退出出错信息,此时你可以在DOS下使用 C:php53iisphp.exe -v 进行调试查看,一般情况下会将PHP配置的错误信息报出,你只要根据此信息修改相关PHP配置即可。 至此在Windows7 IIS7平台上进行PHP5.2和PHP5.3的配置安装工作就介绍完了,应该讲随着PHP版本的提高,PHP的配置工作也越来越简单化。
View DetailsAsp.net的NamePipe机制给我们提供了很多扩展性. 使用HttpModule我们可能实现的有: 强制站点范围的Cookie策略 集中化监控与日志 编写设置与删除HTTP头 控制response输出,如删除多余空白字符 Session管理 认证与受权 下面我们来看如何实现自定义异常处理:
|
1 |
1: public class ErrorModule:IHttpModule |
|
1 |
2: { |
|
1 |
3: #region IHttpModule Members |
|
1 |
4: |
|
1 |
5: /// <summary> |
|
1 |
6: /// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>. |
|
1 |
7: /// </summary> |
|
1 |
8: public void Dispose() |
|
1 |
9: { |
|
1 |
10: //do nothing |
|
1 |
11: } |
|
1 |
12: |
|
1 |
13: /// <summary> |
|
1 |
14: /// Initializes a module and prepares it to handle requests. |
|
1 |
15: /// </summary> |
|
1 |
16: /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application</param> |
|
1 |
17: public void Init(HttpApplication context) |
|
1 |
18: { |
|
1 |
19: context.Error += new EventHandler(customcontext_Error); |
|
1 |
20: } |
|
1 |
21: |
|
1 |
22: private void customcontext_Error(object sender, EventArgs e) |
|
1 |
23: { |
|
1 |
24: HttpContext ctx = HttpContext.Current; |
|
1 |
25: HttpResponse response = ctx.Response; |
|
1 |
26: HttpRequest request = ctx.Request; |
|
1 |
27: |
|
1 |
28: Exception exception = ctx.Server.GetLastError(); |
|
1 |
29: |
|
1 |
30: var sboutput = new StringBuilder(); |
|
1 |
31: sboutput.Append("Querystring:<p/>"); |
|
1 |
32: //Get out the query string |
|
1 |
33: int count = request.QueryString.Count; |
|
1 |
34: for (int i = 0; i < count; i++) |
|
1 |
35: { |
|
1 |
36: sboutput.AppendFormat("<br/> {0}:-- {1} ", request.QueryString.Keys[i], request.QueryString[i]); |
|
1 |
37: } |
|
1 |
38: //Get out the form collection info |
|
1 |
39: sboutput.Append("<p>-------------------------<p/>Form:<p/>"); |
|
1 |
40: count = request.Form.Count; |
|
1 |
41: for (int i = 0; i < count; i++) |
|
1 |
42: { |
|
1 |
43: sboutput.AppendFormat("<br/> {0}:-- {1} -- <br/>", request.Form.Keys[i], request.Form[i]); |
|
1 |
44: } |
|
1 |
45: sboutput.Append("<p>-------------------------<p/>ErrorInfo:<p/>"); |
|
1 |
46: sboutput.AppendFormat(@"Your request could not processed. Please press the back button on your browser and try again.<br/> |
|
1 |
47: If the problem persists, please contact technical support<p/> |
|
1 |
48: Information below is for technical support:<p/> |
|
1 |
49: <p/>URL:{0}<p/>Stacktrace:---<br/>{1}<p/>InnerException:<br/>{2}" |
|
1 |
50: , ctx.Request.Url, exception.InnerException.StackTrace, exception.InnerException); |
|
1 |
51: |
|
1 |
52: response.Write(sboutput.ToString()); |
|
1 |
53: |
|
1 |
54: // To let the page finish running we clear the error |
|
1 |
55: ctx.Server.ClearError(); |
|
1 |
56: } |
|
1 |
57: |
|
1 |
58: #endregion |
|
1 |
59: |
|
1 |
60: } |
上面的代码实现了IHttpModule接口, 实现基于HttpApplication.Error事件, 接着我们自定义输出了一些信息,包括Form,QueryString. 最后把原来的Error信息清除了,这样你看到以前那个黄页了. 这个自定义的Module可以用于调试Web应用程序使用. Web.config中配置:
|
1 |
<httpModules> |
|
1 |
<add name="ErrorLoggingModule" type="MyWeb.ErrorModule"/> |
|
1 |
</httpModules> |
实际开发中,我们可以做的事儿很多,对这些信息记日志,发邮件. 如下, 我们演示使用Enterprise Library 做异常处理并日志记录,部分代码如下:
|
1 |
1: /// <summary> |
|
1 |
2: /// Handles the Error event of the EntLibLogging control. |
|
1 |
3: /// </summary> |
|
1 |
4: /// <param name="sender">The source of the event.</param> |
|
1 |
5: /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> |
|
1 |
6: /// <remarks>author Petter Liu http://wintersun.cnblogs.com</remarks> |
|
1 |
7: private void EntLibLogging_Error(object sender, EventArgs e) |
|
1 |
8: { |
|
1 |
9: var builder = new ConfigurationSourceBuilder(); |
|
1 |
10: |
|
1 |
11: builder.ConfigureInstrumentation() |
|
1 |
12: .ForApplicationInstance("MyApp") |
|
1 |
13: .EnableLogging() |
|
1 |
14: .EnablePerformanceCounters(); |
|
1 |
15: |
|
1 |
16: //a single exception handling policy named MyPolicy for exceptions of type ArgumentNullException. |
|
1 |
17: //The handler for this exception policy will log the exception to the General category (defined in the Logging Application Block configuration) |
|
1 |
18: //as a warning with event ID 9000, wrap the ArgumentNullException with an InvalidOperationException, set the new exception message to MyMessage, and then re-throw the exception. |
|
1 |
19: builder.ConfigureExceptionHandling() |
|
1 |
20: .GivenPolicyWithName("MyPolicy") |
|
1 |
21: .ForExceptionType<ArgumentNullException>() |
|
1 |
22: .LogToCategory("Exception") |
|
1 |
23: .WithSeverity(System.Diagnostics.TraceEventType.Warning) |
|
1 |
24: .UsingEventId(9000) |
|
1 |
25: .WrapWith<InvalidOperationException>() |
|
1 |
26: .UsingMessage("MyMessage") |
|
1 |
27: .ThenNotifyRethrow(); |
|
1 |
28: |
|
1 |
29: //logging application |
|
1 |
30: builder.ConfigureLogging() |
|
1 |
31: .WithOptions |
|
1 |
32: .DoNotRevertImpersonation() |
|
1 |
33: .LogToCategoryNamed("Exception") |
|
1 |
34: .SendTo.FlatFile("Exception Logging File") |
|
1 |
35: .FormatWith(new FormatterBuilder() |
|
1 |
36: .TextFormatterNamed("Text Formatter") |
|
1 |
37: . UsingTemplate("Timestamp: {timestamp}{newline}Message: {message}{newline}Category: {category}{newline}")) |
|
1 |
38: .ToFile("d:\\logs\\ExceptionsLog.log") |
|
1 |
39: .SendTo.RollingFile("Rolling Log files") |
|
1 |
40: .RollAfterSize(1024) |
|
1 |
41: .ToFile("d:\\logs\\Rollinglog.log") |
|
1 |
42: .LogToCategoryNamed("General") |
|
1 |
43: .WithOptions.SetAsDefaultCategory() |
|
1 |
44: .SendTo.SharedListenerNamed("Exception Logging File"); |
|
1 |
45: |
|
1 |
46: var configSource = new DictionaryConfigurationSource(); |
|
1 |
47: builder.UpdateConfigurationWithReplace(configSource); |
|
1 |
48: EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource); |
|
1 |
49: |
|
1 |
50: var ex = HttpContext.Current.Server.GetLastError(); |
|
1 |
51: var em = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>(); |
|
1 |
52: em.HandleException(ex.InnerException, "MyPolicy"); |
|
1 |
53: } |
注意上面的代码, 为了运行代码您需要引用以下程序集 Enterprise Library Share Common LibraryMicrosoft.Practices.ServiceLocationLogging Application BlockException Handling Application BlockException Handling Logging Provider 这里我们使用Fluent API配置, 因此没有配置XML文件. 所以不需要Web.Config中配置任何信息. 代码中有注释. 为了测试我们使用一个PAGE故意Throw 一个ArgumentNullException. 通过Server.GetLastError()获取Exception, 这时由名为MyPolicy策略处理异常. 对于ArgumentNullException把它们记录日志到名为Exception分类中,这个日志文件位于d:\\logs\\ExceptionLog.log.实际开发你完全按照你的需要来自定义策略. 然后这个日志文件中写出的内容是这样的:
|
1 |
----------------------------------------Timestamp: 2011-11-12 5:57:08Message: HandlingInstanceID: a99d005d-5f8d-4613-9522-2d60efb089aaAn exception of type 'System.ArgumentNullException' occurred and was caught.----------------------------------------------------------------------------11/12/2011 13:57:08Type : System.ArgumentNullException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Message : Value cannot be null.Parameter name: Demo errorSource : MyWebHelp link : ParamName : Demo errorData : System.Collections.ListDictionaryInternalTargetSite : Void Page_Load(System.Object, System.EventArgs)Stack Trace : at MyWeb.About.Page_Load(Object sender, EventArgs e) in H:\My Project\DotNet40\TDD2010\WebHost\MyWeb\About.aspx.cs:line 14 at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)Additional Info:MachineName : USERTimeStamp : 2011-11-12 5:57:08FullName : Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35AppDomainName : 3e5cb21e-3-129655510216406250ThreadIdentity : WindowsIdentity : USER\PetterCategory: Exception |
由于我们日志模块我们配置还需要写Rollinglog.log文件,内容如下:
|
1 |
----------------------------------------Exception Warning: 9000 : Timestamp: 2011-11-12 5:57:08Message: HandlingInstanceID: a99d005d-5f8d-4613-9522-2d60efb089aaAn exception of type 'System.ArgumentNullException' occurred and was caught.----------------------------------------------------------------------------11/12/2011 13:57:08Type : System.ArgumentNullException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Message : Value cannot be null.Parameter name: Demo errorSource : MyWebHelp link : ParamName : Demo errorData : System.Collections.ListDictionaryInternalTargetSite : Void Page_Load(System.Object, System.EventArgs)Stack Trace : at MyWeb.About.Page_Load(Object sender, EventArgs e) in H:\My Project\DotNet40\TDD2010\WebHost\MyWeb\About.aspx.cs:line 14 at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)Additional Info:MachineName : USERTimeStamp : 2011-11-12 5:57:08FullName : Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35AppDomainName : 3e5cb21e-3-129655510216406250ThreadIdentity : WindowsIdentity : USER\PetterCategory: ExceptionPriority: 0EventId: 9000Severity: WarningTitle:Enterprise Library Exception HandlingMachine: USERApp Domain: 3e5cb21e-3-129655510216406250ProcessId: 2444Process Name: C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\WebDev.WebServer40.exeThread Name: Win32 ThreadId:2748Extended Properties: ---------------------------------------- |
|
1 |
你可以看到上面的EventId=9000与我们之前在CODE中配置是相同的. |
|
1 2 |
在开源社区有一个组件<a href="http://code.google.com/p/elmah/" target="_blank"><span style="color:#E3272D;">ELMAH</span></a>(Error Logging Modules and Handlers for ASP.NET),已实现Error处理发邮件,写DB,发送到SNS等功能. 我们随意来看下它的代码: 它就是基于IHttpModule的扩展,下面代码来ELMAH: |
|
1 |
1: /// <summary> |
|
1 |
2: /// Provides an abstract base class for <see cref="IHttpModule"/> that |
|
1 |
3: /// supports discovery from within partial trust environments. |
|
1 |
4: /// </summary> |
|
1 |
5: public abstract class HttpModuleBase : IHttpModule |
|
1 |
6: { |
|
1 |
7: void IHttpModule.Init(HttpApplication context) |
|
1 |
8: { |
|
1 |
9: if (context == null) |
|
1 |
10: throw new ArgumentNullException("context"); |
|
1 |
11: |
|
1 |
12: if (SupportDiscoverability) |
|
1 |
13: HttpModuleRegistry.RegisterInPartialTrust(context, this); |
|
1 |
14: |
|
1 |
15: OnInit(context); |
|
1 |
16: } |
|
1 |
17: |
|
1 |
18: void IHttpModule.Dispose() |
|
1 |
19: { |
|
1 |
20: OnDispose(); |
|
1 |
21: } |
|
1 |
22: |
|
1 |
23: /// <summary> |
|
1 |
24: /// Determines whether the module will be registered for discovery |
|
1 |
25: /// in partial trust environments or not. |
|
1 |
26: /// </summary> |
|
1 |
27: protected virtual bool SupportDiscoverability |
|
1 |
28: { |
|
1 |
29: get { return false; } |
|
1 |
30: } |
|
1 |
31: |
|
1 |
32: /// <summary> |
|
1 |
33: /// Initializes the module and prepares it to handle requests. |
|
1 |
34: /// </summary> |
|
1 |
35: protected virtual void OnInit(HttpApplication application) {} |
|
1 |
36: |
|
1 |
37: /// <summary> |
|
1 |
38: /// Disposes of the resources (other than memory) used by the module. |
|
1 |
39: /// </summary> |
|
1 |
40: protected virtual void OnDispose() {} |
|
1 |
41: } |
|
1 |
这是ErrorLogModule实现之前HttpModuleBase: |
|
1 |
1: public class ErrorLogModule : HttpModuleBase, IExceptionFiltering |
|
1 |
2: { |
|
1 |
3: public event ExceptionFilterEventHandler Filtering; |
|
1 |
4: public event ErrorLoggedEventHandler Logged; |
|
1 |
5: |
|
1 |
6: /// <summary> |
|
1 |
7: /// Initializes the module and prepares it to handle requests. |
|
1 |
8: /// </summary> |
|
1 |
9: |
|
1 |
10: protected override void OnInit(HttpApplication application) |
|
1 |
11: { |
|
1 |
12: if (application == null) |
|
1 |
13: throw new ArgumentNullException("application"); |
|
1 |
14: |
|
1 |
15: application.Error += new EventHandler(OnError); |
|
1 |
16: ErrorSignal.Get(application).Raised += new ErrorSignalEventHandler(OnErrorSignaled); |
|
1 |
17: } |
|
1 |
18: |
|
1 |
19: /// <summary> |
|
1 |
20: /// Gets the <see cref="ErrorLog"/> instance to which the module |
|
1 |
21: /// will log exceptions. |
|
1 |
22: /// </summary> |
|
1 |
23: protected virtual ErrorLog GetErrorLog(HttpContext context) |
|
1 |
24: { |
|
1 |
25: return ErrorLog.GetDefault(context); |
|
1 |
26: } |
|
1 |
27: |
|
1 |
28: /// <summary> |
|
1 |
29: /// The handler called when an unhandled exception bubbles up to |
|
1 |
30: /// the module. |
|
1 |
31: /// </summary> |
|
1 |
32: protected virtual void OnError(object sender, EventArgs args) |
|
1 |
33: { |
|
1 |
34: HttpApplication application = (HttpApplication) sender; |
|
1 |
35: LogException(application.Server.GetLastError(), application.Context); |
|
1 |
36: } |
|
1 |
37: |
|
1 |
38: /// <summary> |
|
1 |
39: /// The handler called when an exception is explicitly signaled. |
|
1 |
40: /// </summary> |
|
1 |
41: protected virtual void OnErrorSignaled(object sender, ErrorSignalEventArgs args) |
|
1 |
42: { |
|
1 |
43: LogException(args.Exception, args.Context); |
|
1 |
44: } |
|
1 |
45: |
|
1 |
46: /// <summary> |
|
1 |
47: /// Logs an exception and its context to the error log. |
|
1 |
48: /// </summary> |
|
1 |
49: protected virtual void LogException(Exception e, HttpContext context) |
|
1 |
50: { |
|
1 |
51: if (e == null) |
|
1 |
52: throw new ArgumentNullException("e"); |
|
1 |
53: |
|
1 |
54: // |
|
1 |
55: // Fire an event to check if listeners want to filter out |
|
1 |
56: // logging of the uncaught exception. |
|
1 |
57: // |
|
1 |
58: |
|
1 |
59: ExceptionFilterEventArgs args = new ExceptionFilterEventArgs(e, context); |
|
1 |
60: OnFiltering(args); |
|
1 |
61: |
|
1 |
62: if (args.Dismissed) |
|
1 |
63: return; |
|
1 |
64: |
|
1 |
65: // |
|
1 |
66: // Log away... |
|
1 |
67: // |
|
1 |
68: |
|
1 |
69: ErrorLogEntry entry = null; |
|
1 |
70: |
|
1 |
71: try |
|
1 |
72: { |
|
1 |
73: Error error = new Error(e, context); |
|
1 |
74: ErrorLog log = GetErrorLog(context); |
|
1 |
75: string id = log.Log(error); |
|
1 |
76: entry = new ErrorLogEntry(log, id, error); |
|
1 |
77: } |
|
1 |
78: catch (Exception localException) |
|
1 |
79: { |
|
1 |
80: // |
|
1 |
81: // IMPORTANT! We swallow any exception raised during the |
|
1 |
82: // logging and send them out to the trace . The idea |
|
1 |
83: // here is that logging of exceptions by itself should not |
|
1 |
84: // be critical to the overall operation of the application. |
|
1 |
85: // The bad thing is that we catch ANY kind of exception, |
|
1 |
86: // even system ones and potentially let them slip by. |
|
1 |
87: // |
|
1 |
88: |
|
1 |
89: Trace.WriteLine(localException); |
|
1 |
90: } |
|
1 |
91: |
|
1 |
92: if (entry != null) |
|
1 |
93: OnLogged(new ErrorLoggedEventArgs(entry)); |
|
1 |
94: } |
|
1 |
95: |
|
1 |
96: /// <summary> |
|
1 |
97: /// Raises the <see cref="Logged"/> event. |
|
1 |
98: /// </summary> |
|
1 |
99: protected virtual void OnLogged(ErrorLoggedEventArgs args) |
|
1 |
100: { |
|
1 |
101: ErrorLoggedEventHandler handler = Logged; |
|
1 |
102: |
|
1 |
103: if (handler != null) |
|
1 |
104: handler(this, args); |
|
1 |
105: } |
|
1 |
106: |
|
1 |
107: /// <summary> |
|
1 |
108: /// Raises the <see cref="Filtering"/> event. |
|
1 |
109: /// </summary> |
|
1 |
110: protected virtual void OnFiltering(ExceptionFilterEventArgs args) |
|
1 |
111: { |
|
1 |
112: ExceptionFilterEventHandler handler = Filtering; |
|
1 |
113: |
|
1 |
114: if (handler != null) |
|
1 |
115: handler(this, args); |
|
1 |
116: } |
|
1 |
117: |
|
1 |
118: /// <summary> |
|
1 |
119: /// Determines whether the module will be registered for discovery |
|
1 |
120: /// in partial trust environments or not. |
|
1 |
121: /// </summary> |
|
1 |
122: protected override bool SupportDiscoverability |
|
1 |
123: { |
|
1 |
124: get { return true; } |
|
1 |
125: } |
|
1 |
126: } |
|
1 |
更多的功能等待您去挖掘,我们在实际开发中按需选择.希望这篇POST对您开发有帮助. |
转自:http://www.cnblogs.com/wintersun/archive/2011/11/12/2246513.html
View Details