If you are writing server code in C# or to a lesser extent desktop/client then it's a good idea to include logging code so when something goes wrong you know where to start looking. The Java world has done the same for years and Apache
log4j
 is a very popular open source logging framework.

If you shorten that url to Apache
logging services
 you'll see that there are versions for C++, .NET, and php. In this article I'll show you how to use Apache log4net.

This isn't the only .NET logging framework, there are very many. I chose the Apache one because (a) it's a well trusted name and the original Java logging framework has been around over 15 years, (b) it's one I've used and (c) you can log with UDP messages.

If you want to find others, take a look at the excellent German website (It's in English!) .NET
logging
. They are selling a commercial logging system but their listing and comparison of features of logging systems is very good and disclaimer: I have no connection at all with them, financial or otherwise.

Why Use A Logging Framework?

If an application or server crashes, you are left wondering why. Was it a hardware failure, malware, maybe a Denial of Service attack, or some very odd combination of keys that manages to bypass all your code checks? You just don't know. Even worse is if it
fails when starting.

When an application or server crashes you need to find out why so it can be corrected. With logging enabled you might see why it happened though there is one situation you should watch out for; I've seen this happen once or twice. A server crashed at work because
the log file had filled the disk!

Sending an email in response to an unforeseen exception would avoid a full disk.

Getting Started

If you have Visual Studio, you can just install the binaries from Nuget into
an open project or else download the log4net zip file from the Apache log4net website and unzip somewhere.

If you download the sources, there are two solution files for Visual Studio 2008 and 2010 in the log4net src folder so open the appropriate one and build it. In Visual Studio Express you may have to remove the test sub-project or it'll generate nearly 400 errors
due to always compiling the test sub project first.

After successfully compiling it leaves a log4net.dll in the build/bin/net/2.0 debug or release folder. Just add a reference to that into your project.

Using log4net

This supports seven levels of logging from none to all. These are:

  1. OFF
  2. FATAL
  3. ERROR
  4. WARN
  5. INFO
  6. DEBUG
  7. ALL

The idea is that the higher levels include all the lower ones. When debugging, using DEBUG will show all but on production you might only be interested in FATAL. Also this can be done at the component level programmatically or in an XML Config file.

Loggers and Appenders

For great flexibility, log4net uses loggers, appenders and layouts. A logger is an object that controls logging and is an implementation of the ILog interface which specifies five boolean methods (isDebugEnabled, IsInfoEnabled etc) and five methods (Debug,
Info, Warn, Eror, Fatal) along with overloads and five Formatted String version. You can see the full ILog interface in the log4net
online manual
.

Loggers are assigned one of the levels but not ALL or OFF, only the other five.

Appenders control where the logging goes. It can be into a database via ADO, to an in memory buffer, to the console, to a remote host, to a text file with rolling logs, the WIndows Event Log, or even to email via SMTP. There are 22 different appenders in all
and they can be combined so plenty of choice. Appenders are appended (hence the name) to a logger.

Filtering Events

Appenders can filter events by matching substrings, event level etc to be accepted or rejected.

Finally there are seven layouts. These control how the event's message is logged and can include exception text, timestamp layouts, even XmlLayout.

Configuring With XML

Although configuring can be done programmatically, it can also be done with XML Config files. Why would you prefer config files over code changes? Simple, it's far easier to have a support guy make a change to a config file than have to get a programmer to
change code, test and redeploy a new version. So config files are definitely best.

We'll go for the simplest possible and use just App.config. You can add it to your project with right click on the Project Name (under the word Solution if its the first or only project) then Add -> New Item. Select General under Visual C# Items then Application
Configuration File.

This is the App.config file I used:

  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. <root>
  8. <level value="DEBUG"/>
  9. <appender-ref ref="LogFileAppender" />
  10. </root>
  11. <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
  12. <file value=" log.txt"/>
  13. <appendToFile value="true" />
  14. <rollingStyle value="Size" />
  15. <maxSizeRollBackups value="5" />
  16. <maximumFileSize value="10MB" />
  17. <staticLogFileName value="true" />
  18. <layout type="log4net.Layout.PatternLayout">
  19. <conversionPattern value="%d [%t] %-5p %c %m%n" />
  20. </layout>
  21. </appender>
  22. </log4net>
  23. </configuration>

I'm not going to explain the config file fields as I would write a dozen articles to fully cover the variations with all the different appenders but the log4net online documentation will explain. I recommend you get config
file examples from this log4net
config examples page
.

Having setup App.config, the log4net configuration can be configured using assembly-level attributes:

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

Orspecified programmatically using
apis such asXmlConfigurator.ConfigureXXX():

XmlConfigurator.ConfigureAndWatch(configFile);

Plus the actual logger has to be fetched with a call to LogManager.GetLogger(...). The GetLogger is usually called with the typeof(class) that it's used in but this function call also fetches that:

System.Reflection.MethodBase.GetCurrentMethod().DeclaringType

I've left both in with one commented, so you can choose. Here is the code to use it.

  1. using log4net;
  2. [assembly: log4net.Config.XmlConfigurator(Watch = true)]
  3. namespace TestLog4net
  4. {
  5.     class Program
  6.     {
  7.         private static readonly ILog log = LogManager.GetLogger (System.Reflection.MethodBase.GetCurrentMethod
  8. ().DeclaringType) ;
  9.         //private static readonly ILog log = LogManager.GetLogger(typeof (Program)) ;
  10.         static void Main(string[] args)
  11.         {
  12. 			 //// Set up a simple configuration that logs on the console.
  13. 			 // BasicConfigurator.Configure();
  14. 			 // Type type = typeof(Program);
  15. 			 // string assemblyPath = Assembly.GetAssembly(type).EscapedCodeBase;
  16. 			 // string path = assemblyPath + ".config";
  17. 			 // FileInfo configFile = new FileInfo(new Uri(path).LocalPath);
  18. 			 // XmlConfigurator.ConfigureAndWatch(configFile);
  19.             log.Debug("Application Starting") ;
  20.         }
  21.     }
  22. }
  23. 												
  24. How to do logging in C# with log4net的更多相关文章

      1. Common.Logging log4net Common.Logging.Log4Net 配置
      1. 1.log4net 单独配置 log4net支持多种格式的日志输出,我这里只配置输出到本地的txt文件这种格式. <log4net> <root> <appender-r ...

      1. 使用Common.Logging+log4net规范日志管理
      1. Common.Logging+(log4net/NLog/) common logging是一个通用日志接口,log4net是一个强大的具体实现,也可以用其它不同的实现,如EntLib的日志.NLog ...

      1. 使用Common.Logginglog4net的组件版本兼容问题
      1. 引用:  http://www.cnblogs.com/shijun/p/3713830.html 近期使用了Common.Logging的ILog接口做日志接口,同时利用其log4net适配器与lo ...

      1. 使用Common.Logging+log4net规范日志管理【转载】
      1. 使用Common.Logging+log4net规范日志管理   Common.Logging+(log4net/NLog/) common logging是一个通用日志接口,log4net是一个强大 ...

      1. Log4net 写文件日志与数据库日志
      1. 一.数据库日志表结构 CREATE TABLE [dbo].[WebLog_Msg]( [LogID] [int] IDENTITY(1,1) NOT NULL, [Date] [datetime]  ...

      1. 关于最新版本的log4net使用中遇到的问题
      1. Quartz.NET是一个开源的作业调度框架,是OpenSymphony Quartz API的.NET移植,它用C#写成,可用于winform和asp.net应用中.它提供了巨大的灵活性而不牺牲 ...

      1. .netcore 写日志(使用NLog,log4net
      1. 参考地址: NLog:http://www.cnblogs.com/linezero/p/Logging.html Log4Net:http://www.cnblogs.com/linezero/p/ ...

      1. using log4net on my project within a self-hosted WCF application z
      1. Add reference to log4net.dll to our console service host project (our application entry point) Add t ...

      1. Quartz.net 2.x 学习笔记02-Quartz.net 2.xMVC站点中结合Log4net的使用
      1. Quartz.net 2.xMVC站点中结合Log4net的使用 首先新建一个MVC的空站点: 第二步,添加Quartz.net的引用 在搜索处输入quartz.net搜索安装即可(目前是2.3) ...

    1.  
    2. 随机推荐

        1. express 4 session的处理(仅为博主笔记)
        1. 1.app.js var express = require('express') var app = express();var routers = require('./router/index' ...

        1. 二十六:Struts2 spring整合
        1. 二十六:Struts2 spring整合 将项目名称为day29_02_struts2Spring下的scr目录下的Struts.xml文件拷贝到新项目的scr目录下 在新项目的WebRoot-- ...

        1. 使用jna调用dlljdk位数和dll位数的关系
        1. 最近在学习jna,发现dll文件能能否成功调用取决于jdk位数. 32jdk只能使用32位的dll,64jdk只能使用64位的dll,否则位数不对应的话报的错是 "Exception i ...

        1. weed-fs参数列表
        1. weed-fs没有详细的帮助文档,为了方便阅读,特意把有用的参数帮助罗列出来.未列出的两个命令为version(版本查询) 及shell(这个命令在0.45版本只有回显功能)nerc@Ubuntu:~ ...

        1. Fastcgi介绍和php中fastcgi的应用
        1. 先看下FastCgi的一些解释: CGI全称是“通用网关接口”(Common Gateway Interface), 它可以让一个客户端,从网页浏览器向执行在Web服务器上的程序请求数据. CGI描述 ...

        1. Mongodb数据导出工具mongoexport和导入工具mongoimport介绍
        1. 一.导出工具mongoexport Mongodb中的mongoexport工具可以把一个collection导出成JSON格式或CSV格式的文件.可以通过参数指定导出的数据项,也可以根据指定的条件导 ...

        1. 动态生成dropdownlist
        1. <td colspan=" id="td_ddl" runat="server"> </td> 后台代码: #region 动 ...

        1. 基于CCS3.3平台搭建DSP/BIOS系统
        1. 本人由于换工作的原因,由ccs3.1平台下转化为ccs3.3平台.先说说本人感觉的区别,ccs3.1下的CSL库集成到DSP/BIOS内,而3.3CSL库在DSP/BIOS下就没有体现. 1.二话不 ...

        1. props
        1. // 这里是导入的包 import React, { Component } from 'react'; // 导入需要用到的组件 import { AppRegistry, Text, View } ...

        1. div层叠顺序额
        1. 在模态窗体中打开新div,结果该div不显示 div不是没有显示,而是显示了,但是被这个模态状体挡住了 解决方法:修改z-index这个参数 该参数越大则显示在越上层,即可见