如果在项目当中需要使用log4net来记录日志,大致分为以下三步
    1,创建log4net配置文件
    2,读取配置文件节点
    3,记录日志信息

    第一步:

    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. <logger name="logerror">
    8. <level value="ERROR"/>
    9. <appender-ref ref="ErrorAppender"/>
    10. </logger>
    11. <logger name="loginfo">
    12. <level value="INFO"/>
    13. <appender-ref ref="InfoAppender"/>
    14. </logger>
    15. <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
    16. <param name="File" value="..//..//Log//Error//"/>
    17. <param name="AppendToFile" value="true"/>
    18. <param name="MaxSizeRollBackups" value="100"/>
    19. <param name="MaxFileSize" value="1024"/>
    20. <param name="StaticLogFileName" value="false"/>
    21. <param name="DatePatten" value="yyyy-MM-dd&quot;.txt&quot;"/>
    22. <param name="RollingStyle" value="Date"/>
    23. <layout type="log4net.Layout.PatternLayout">
    24. <param name="ConversionPattern" value="异常时间:date %n 异常位置:[ %thread]
    25. ( %file: %line) %消息描述: %message % 异常: %exception %n %n
    26. "/>
    27. </layout>
    28. </appender>
    29. <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
    30. <param name="File" value="..//..//Log//Info//"/>
    31. <param name="AppendToFile" value="true"/>
    32. <param name="MaxSizeRollBackups" value="100"/>
    33. <param name="MaxFileSize" value="1024"/>
    34. <param name="StaticLogFileName" value="false"/>
    35. <param name="DatePatten" value="yyyy-MM-dd&quot;.txt&quot;"/>
    36. <param name="RollingStyle" value="Date"/>
    37. <layout type="log4net.Layout.PatternLayout">
    38. <param name="ConversionPattern" value=" %n异常时间: %date 消息描述: %m"/>
    39. </layout>
    40. </appender>
    41. </log4net>
    42. </configuration>

    第二步:

    1. public class LogHelper
    2. {
    3. private readonly log4net.ILog logInfo;
    4. private readonly log4net.ILog logError;
    5. public LogHelper
    6. {
    7. log4net.Config.XmlConfigure (new System.IO.FileInfo("配置文件的位置"));
    8. ///读取配置文件节点,实例化记录信息对象和错误对象
    9. logInfo = log4net.LogManager.GetLogger("loginfo");
    10. logError = log4net.LogManager.GetLogger("logerror");
    11. }
    12. public static void WriteInfo(string message)
    13. {
    14. try
    15. {
    16. if(loginfo.IsInfoEnabled)
    17. {
    18. loginfo.Info(message);
    19. }
    20. }
    21. catch{}
    22. }
    23. public static void WriteError(string error,Exception ex)
    24. {
    25. try
    26. {
    27. if(logError.IsErrorEnabled)
    28. {
    29. loginfo.Info(error,ex);
    30. }
    31. }
    32. catch
    33. {
    34. }
    35. }
    36. }

    第三步
    LogHelper logHelper = new LogHelper();
    logHelper.WriteInfo(“输出记录信息”);

    也可以把第二步和第三步合并一起来写
    log4net.LogManager.GetLogger(“loginfo”).Info(“输出记录信息”);