zoukankan      html  css  js  c++  java
  • log4net配置

    测试环境:vs2012
    步骤1:下载log4net.dll (版本:1.2.10.0;
    步骤2:webconfig配置文件(log4net配置 ):
     1   <!-- log4net配置 begin-->
     2   <configSections>
     3     <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
     4     <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
     5     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
     6   </configSections>
     7   <log4net>
     8     <!--定义输出到文件中-->
     9     <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    10       <!--定义文件存放位置-->
    11       <file value="logs\"/>
    12       <appendToFile value="true"/>
    13       <rollingStyle value="Date"/>
    14       <!--<datePattern value="yyyy\yyyyMM\yyyyMMdd'.txt'"/>-->
    15       <datePattern value="yyyyMMdd'.txt'"/>
    16       <staticLogFileName value="false"/>
    17       <param name="MaxSizeRollBackups" value="100"/>
    18       <layout type="log4net.Layout.PatternLayout">
    19         <!--每条日志末尾的文字说明-->
    20         <!--输出格式-->
    21         <!--样例:2008-03-26 13:42:32,111 [10] INFO  Log4NetDemo.MainClass [(null)] - info-->
    22         <!--<conversionPattern value="%newline %n记录时间:%date %n线程ID:[%thread] %n日志级别:  %-5level %n出错类:%logger property: [%property{NDC}] - %n错误描述:%message%n"/>-->
    23         <!--<conversionPattern value="%date:%message%n"/>-->
    24         <conversionPattern value="%n【记录时间】%date%n【描述】%message%n"/>
    25       </layout>
    26     </appender>
    27     <root>
    28       <!--文件形式记录日志-->
    29       <!--(高) OFF > FATAL > ERROR > WARN > INFO > DEBUG > ALL (低) -->
    30       <level value="ALL"/>
    31       <appender-ref ref="RollingLogFileAppender"/>
    32       <!--<level value="ERROR"/>
    33       --><!--文件形式记录日志--><!--
    34       <appender-ref ref="RollingLogFileAppender"/>
    35       <level value="DEBUG"/>
    36       --><!--文件形式记录日志--><!--
    37       <appender-ref ref="RollingLogFileAppender"/>-->
    38     </root>
    39   </log4net>
    40   <startup>
    41     <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
    42   </startup>
    43   <!-- log4net配置 end-->
    View Code
    附上输出格式的注释:
    %m(message):输出的日志消息,如ILog.Debug(…)输出的一条消息
    %n(new line):換行
    %d(datetime):输出当前语句运行的时刻 
    %r(run time):输出程序从运行到执行到当前语句时消耗的毫秒数 
    %t(thread id):当前语句所在的线程ID
    %p(priority): 日志的当前优先级别,即DEBUG、INFO、WARN…等
    %c(class):当前日志对象的名称
    %L:输出语句所在的行号
    %F:输出语句所在的文件名
    %-数字:表示该项的最小长度,如果不够,则用空格填充

    步骤3:添加log4net封装类(包括注册log4net.dll):
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    [assembly: log4net.Config.XmlConfigurator(Watch = true)]
    namespace WebApp.Helper
    {
        public class LogHelper
        {
            /// <summary>
            /// 输出日志到Log4Net
            /// </summary>
            /// <param name="t"></param>
            /// <param name="ex"></param>
            #region static void WriteLog(Type t, Exception ex)
    
            public static void WriteLog(Type t, Exception ex)
            {
                log4net.ILog log = log4net.LogManager.GetLogger(t);
                log.Error("Error", ex);
            }
    
            #endregion
    
            /// <summary>
            /// 输出日志到Log4Net
            /// </summary>
            /// <param name="t"></param>
            /// <param name="msg"></param>
            #region static void WriteLog(Type t, string msg)
    
            public static void WriteLog(Type t, string msg)
            {
                log4net.ILog log = log4net.LogManager.GetLogger(t);
                log.Error(msg);
            }
    
            #endregion
    
            /// <summary>
            /// 自定义写入日志
            /// </summary>
            /// <param name="msg"></param>
            public static void WriteInfo(string msg)
            {
                log4net.ILog log = log4net.LogManager.GetLogger(typeof(LogHelper));
                log.Error(msg);
     
            }
    
        }
    }
    View Code

    注册log4net.dll:

    方法:在AssemblyInfo.cs 在封装的类(本例为LogHelper)添加如下代码:

    1 //[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]  //读取指定文件log4net.config;此文件必须在跟目录;属性必须是:始终复制
    2 //[assembly: log4net.Config.XmlConfigurator(Watch = true)]     //默认 winform读取App.config;webform读取Web.config
    View Code

    方法b:直接在对应封装的类 写上上面代码

       步骤4:使用:

                ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
                log.Debug("Debug");
                log.Info("Info"); 
    
                WebApp.Helper.LogHelper.WriteInfo("111111111111111");
                 
                //DataCollection.Common.LogHelper.WriteLog("");
                WebApp.Helper.LogHelper. WriteLog(typeof(Test), "测试Log4Net日志是否写入111111111111111");
    View Code

    提示:如果没有写入数据,主要原因是没有配置不正确;

     注意:

    1,可能出现问题,添加了dll,却显示未加载,此时可能是vs项目属性设置的目标框架有关,重新设置即可;

    2,log4net只读取当前运行程序所在项目的config(如下图箭头);

    
    
     

     3,winform程序有时候需要在Program里加上一下代码,初始化用的

     log4net.Config.XmlConfigurator.ConfigureAndWatch(
    new System.IO.FileInfo("log4net.config"));

      ===========================================

    另外一种配置方式:

    log4net配置文件:

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <configuration>
     3     <configSections>
     4         <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
     5     </configSections>
     6     <log4net>
     7         <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
     8             <param name="File" value="E:\log\synchronouslog\" />
     9             <param name="AppendToFile" value="true" />
    10             <param name="MaxSizeRollBackups" value="10" />
    11             <param name="StaticLogFileName" value="false" />
    12             <param name="DatePattern" value="yyyyMMdd/HH&quot;log.log&quot;"  />
    13             <param name="RollingStyle" value="Date" />
    14             <layout type="log4net.Layout.PatternLayout">
    15                 <!--<param name="conversionPattern" value="%d [%t] 日志级别:%-5p 出错类: %l - 描述:%message%newline" />-->
    16                 <param name="ConversionPattern" value="%d [%t] %-5p %l  %m  %n" />
    17             </layout>
    18         </appender>
    19         <root>
    20             <level value="All" />
    21             <appender-ref ref="LogFileAppender" />
    22         </root>
    23     </log4net>
    24 </configuration>
    View Code

    对应的logClass类:

      1 using System;
      2 using System.Collections.Generic;
      3 using System.Text;
      4 [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
      5 
      6 namespace webframework.common
      7 {
      8     public class logclass
      9     {
     10         #region 
     11         /*
     12         #region 私有变量
     13         private static logclass _log = null;
     14         private static string _filepath = System.Configuration.ConfigurationSettings.AppSettings["ErrFile"];
     15         #endregion
     16 
     17         #region 私有初始化
     18         private logclass() { }
     19         #endregion
     20 
     21         #region  初始化
     22         /// <summary>
     23         /// 获取实例
     24         /// </summary>
     25         /// <returns></returns>
     26         public static logclass GetCurrentInstance()
     27         {
     28             if (_log==null)
     29             {
     30                 _log = new logclass();
     31             }
     32             return _log;
     33         }
     34         #endregion
     35 
     36         #region 共有方法
     37         /// <summary>
     38         /// 设置获取要写入的文件地址
     39         /// </summary>
     40         public string FilePath
     41         {
     42             get { if (string.IsNullOrEmpty(_filepath)) _filepath = "c:/urlerr.txt"; return _filepath; }
     43             set { _filepath = value; }
     44         }
     45         /// <summary>
     46         /// 写入文本
     47         /// </summary>
     48         /// <param name="strContent"></param>
     49         public void WriteLog(string strContent)
     50         {
     51             Write(strContent);
     52         }
     53         /// <summary>
     54         /// 写入文本
     55         /// </summary>
     56         /// <param name="strFile"></param>
     57         /// <param name="strContent"></param>
     58         public void WriteLog(string strFile, string strContent)
     59         {
     60             _filepath = strFile;
     61             Write(strContent);
     62         }
     63         #endregion
     64 
     65         #region 私有方法
     66         private void Write(string strContent)
     67         {
     68             lock(this)
     69             {
     70                 if (!File.Exists(_filepath))
     71                 {
     72                     FileStream fs = File.Create(_filepath);
     73                     fs.Flush();
     74                     fs.Close();
     75                 }
     76                 using (StreamWriter sw = File.AppendText(_filepath))
     77                 {
     78                     sw.Write(strContent);
     79                     sw.WriteLine();
     80                     sw.Flush();
     81                     sw.Close();
     82                 }
     83             }
     84         }
     85         #endregion
     86          */
     87         #endregion
     88 
     89         private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
     90         public static void SetConfig()
     91         {
     92             log4net.Config.DOMConfigurator.Configure();
     93         }
     94 
     95 
     96         public static void Debug(string err)
     97         {
     98             log.Debug(err);
     99         }
    100         public static void Debug(string err, Exception e)
    101         {
    102             log.Debug(err, e);
    103         }
    104 
    105         public static void Error(string err)
    106         {
    107             log.Error(err);
    108         }
    109         public static void Error(string err, Exception e)
    110         {
    111             log.Error(err, e);
    112         }
    113 
    114         public static void Warm(string err)
    115         {
    116             log.Warn(err);
    117         }
    118         public static void Warm(string err, Exception e)
    119         {
    120             log.Warn(err, e);
    121         }
    122 
    123         public static void Info(string err)
    124         {
    125             log.Info(err);
    126         }
    127         public static void Info(string err, Exception e)
    128         {
    129             log.Info(err, e);
    130         }
    131 
    132     }
    133 }
    View Code
  • 相关阅读:
    Spring 拦截器postHandle无法修改Response的原因
    使用AShot进行网页全页截图
    60句简短的话 句句在理
    天使
    路过青春的合欢树
    Velocity日期格式化
    高斯模糊的Java实现
    MyBatis架构与源码分析<资料收集>
    柳青(Jean)英文演讲集合
    hive sql 常见异常
  • 原文地址:https://www.cnblogs.com/systemkk/p/4177701.html
Copyright © 2011-2022 走看看