概述

本文主要简单说明如何使用Log4Net进行日志记录,在程序开发过程中记录日志的优点:

  • 它可以提供应用程序运行时的精确环境,可供开发人员尽快找到应用程序中的Bug;
  • 一旦在程序中加入了Log 输出代码,程序运行过程中就能生成并输出日志信息而无需人工干预。
  • 日志信息可以输出到不同的地方(控制台,文件等)以备以后研究之用。

关于Log4Net的官方说明:

The Apache log4net library is a tool to help the programmer output log statements to a variety of output targets. log4net is a port of the excellent Apache log4j™ framework to the Microsoft® .NET runtime. We have kept the framework similar in spirit to the original log4j while taking advantage of new features in the.NET runtime。

【粗略翻译】Apache log4net 类库是一个帮助程序员输出日志状态到多种目标平台。log4net 是优秀的 Apache log4jTM 框架在微软.Net平台的一个实现。在保持原有log4j的思想的前提下,同时利用.Net的新特性。

Log4Net 在程序中使用,可以通过配置文件,进行配置,也可以通过程序代码进行定义。本文主要讲解一下通过配置的方式实现

配置文件结构,如下图所示:

C# 利用Log4Net进行日志记录

配置文件可以配置在App.config中【编译后会生成对应的[程序名].exe.config】,也可以配置在独立的xml文件中。

如果配置在独立的xml文件中,需要在Assembly.cs中增加一句说明,如下所示:

[assembly: log4net.Config.DOMConfigurator(ConfigFile = "Log4NetConfig.xml", ConfigFileExtension = "xml", Watch = true)]

如果配置在App.config中,除了配置log4net节点外,还要对节点进行声明,即要增加configSection节点【放在根节点的第一个元素】,如下所示

  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
  </configSections>

生成的日志文件内容,如下图所示:

C# 利用Log4Net进行日志记录

核心代码

代码如下:

 1 using log4net;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 [assembly: log4net.Config.XmlConfigurator(Watch = true)]
 9 namespace DemoLog4Net
10 {
11     /// <summary>
12     /// 日志记录
13     /// </summary>
14     public class LogHelper
15     {
16         /// <summary>
17         /// 日志实例
18         /// </summary>
19         private static ILog logInstance=LogManager.GetLogger("testApp");
20 
21         public static void WriteLog(string message ,LogLevel level) {
22             switch (level) {
23                 case LogLevel.Debug:
24                     logInstance.Debug(message);
25                     break;
26                 case LogLevel.Error:
27                     logInstance.Error(message);
28                     break;
29                 case LogLevel.Fatal:
30                     logInstance.Fatal(message);
31                     break;
32                 case LogLevel.Info:
33                     logInstance.Info(message);
34                     break;
35                 case LogLevel.Warn:
36                     logInstance.Warn(message);
37                     break;
38                 default:
39                     logInstance.Info(message);
40                     break;
41             }
42         }
43     }
44 
45     public enum LogLevel {
46         Debug=0,
47         Error=1,
48         Fatal=2,
49         Info=3,
50         Warn=4
51     }
52 }
View Code

相关文章:

  • 2022-12-23
  • 2021-08-27
  • 2021-09-03
  • 2021-10-13
  • 2022-02-14
猜你喜欢
  • 2021-06-03
  • 2021-05-16
  • 2021-08-17
  • 2021-10-07
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案