Log4Net与Log2Console配合时中文问题的解决

时间:2022-04-23
本文章向大家介绍Log4Net与Log2Console配合时中文问题的解决,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

二者搭配,非常好用,但必须要用log4net.Layout.XmlLayoutSchemaLog4j才能有效果:区分不同的级别,把不同的属性列都显示出来…

关于Layout参见:http://www.cnblogs.com/wangchunlan2004/articles/609100.html

排版员 特长 ExceptionLayout 对LoggingEvent中的异常信息message进行排版 PatternLayout 最常用的排版员,通过一堆标识符来决定版式。 如:"%date %-5level- %message" 表示要以此输出日志日期、级别(5个字母的宽度)、信息 SimpleLayout 最简单的版式:  [level] - [message] XmlLayout 把日志写到XML文件中去,写成一个Element XmlLayoutSchemaLog4j 把日志写到XML文件中去,写成一个Element,其格式需符合log4j对事件定义的DTD. ----------------------------------------------------------------------------------------------- 用常用的patterlayout只能显示一个内容。 这个帖子提到了重新构造一个自己的Layout,http://www.cnblogs.com/seekerlee/archive/2009/06/01/1494067.html,还提供了源码,下载下来试了半天,有一个LogMessage找不到,总是通不过。改了代码后,编译出dll来,用了也没有效果。

发现有人遇到类似问题http://www.yacosoft.com/article.asp?id=44

问题出现原因:源代码问题出在 UtilTransform.cs 文件 public static string MaskXmlInvalidCharacters ( string textData, string mask ) 这个函数上. 这个函数本意是将输出消息中的无效字符替换为"?".但是不幸的是这个正则写的有问题 private static Regex INVALIDCHARS = new Regex ( @"[^x09x0Ax0Dx20-xFFu00FF-u07FFuE000-uFFFD]", RegexOptions.Compiled ); 这个正则将很大一部分字符都替换掉了,其中就包含中文,还有日文韩文等 解决办法:我直接把正则替换那句话注释掉了.然后重新编译生成,搞定

还有Japanese也有类似问题,https://issues.apache.org/jira/browse/LOG4NET-229。解决办法都提到了源码的Transform.cs。

但是,这个开源的东西是1.0的老代码,我试了很多次,反复研究http://logging.apache.org/log4net/release/building.html才算搞定。

Visual Studio 2005 Open the Visual Studio .NET 2002 solution file as above. Visual Studio will convert the solution and project files to Visual Studio .NET 2003 format. After converting the log4net project you must change the Conditional compilation symbols specified for the log4net project. Open the project properties page and select the Build sheet. Replace the NET_1_0 symbol with NET_2_0. Remember to do this for both Debug and Release configurations. In addition the log4net project requires the following new references:

  • System.Configuration

要点是:

  1. 转换项目(src下的sln)
  2. 删除test项目,没有心情搞nunit了
  3. 右键单击log4net项目,配置中的NET_1_0改为NET_2_0
  4. 引用中添加一个System.configuration

编译就能通过了。