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:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
</configSections>
<log4net>
<root>
<level value="DEBUG"/>
<appender-ref ref="LogFileAppender" />
</root>
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<file value=" log.txt"/>
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="10MB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%d [%t] %-5p %c %m%n" />
</layout>
</appender>
</log4net>
</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.

using log4net;

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

namespace TestLog4net
{
class Program
{
private static readonly ILog log = LogManager.GetLogger (System.Reflection.MethodBase.GetCurrentMethod
().DeclaringType) ;
//private static readonly ILog log = LogManager.GetLogger(typeof (Program)) ;
static void Main(string[] args)
{
//// Set up a simple configuration that logs on the console.
// BasicConfigurator.Configure(); // Type type = typeof(Program);
// string assemblyPath = Assembly.GetAssembly(type).EscapedCodeBase;
// string path = assemblyPath + ".config";
// FileInfo configFile = new FileInfo(new Uri(path).LocalPath);
// XmlConfigurator.ConfigureAndWatch(configFile);
log.Debug("Application Starting") ;
}
}
}
												

How to do logging in C# with log4net的更多相关文章

  1. Common.Logging log4net Common.Logging.Log4Net 配置

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

  2. 使用Common.Logging+log4net规范日志管理

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

  3. 使用Common.Logging与log4net的组件版本兼容问题

    引用:  http://www.cnblogs.com/shijun/p/3713830.html 近期使用了Common.Logging的ILog接口做日志接口,同时利用其log4net适配器与lo ...

  4. 使用Common.Logging+log4net规范日志管理【转载】

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

  5. Log4net 写文件日志与数据库日志

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

  6. 关于最新版本的log4net使用中遇到的问题

    Quartz.NET是一个开源的作业调度框架,是OpenSymphony 的 Quartz API的.NET移植,它用C#写成,可用于winform和asp.net应用中.它提供了巨大的灵活性而不牺牲 ...

  7. .netcore 写日志(使用NLog,log4net)

    参考地址: NLog:http://www.cnblogs.com/linezero/p/Logging.html Log4Net:http://www.cnblogs.com/linezero/p/ ...

  8. using log4net on my project within a self-hosted WCF application z

    Add reference to log4net.dll to our console service host project (our application entry point) Add t ...

  9. Quartz.net 2.x 学习笔记02-Quartz.net 2.x在MVC站点中结合Log4net的使用

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

随机推荐

  1. C#EXCEL 操作类--C#DataToExcel帮助类

    using System; using System.Diagnostics; //using Excel; namespace DotNet.Utilities {     /// <summ ...

  2. VR全景智慧城市-720全景项目行业应用

    VR虚拟现实.VR全景概念已成为科技发展热议的焦点.在这样的市场大环境下,全景智慧城市做为一家对大众创新万众创业和用户体验为理念的VR全景城市化信息搜素平台平地而生成为的VR行业领跑者,致力VR全景V ...

  3. 纸上谈兵:排序算法简介及C实现

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 排序算法(Sorting Algorithm)是计算机算法的一个组成部分. 排序的 ...

  4. MySQL主从同步的延迟原理

    1. MySQL数据库主从同步延迟原理. 答:谈到MySQL数据库主从同步延迟原理,得从mysql的数据库主从复制原理说起,mysql的主从复制都是单线程的操作,主库对所有DDL和DML产生binlo ...

  5. “VS2013无法连接远程数据库”解决方案

    “VS2013无法连接远程数据库” 解决方案:以管理员身份登录CMD,输入netsh winsock reset并回车(注意,必须是已管理员身份运行,这个重置LSP连接) 或 netsh winsoc ...

  6. TListView Header重绘和高度设置

    TListView 的 Header 部分默认 BtnFace 颜色,高度也不能改变.我们可以通过编写一些代码来实现这些功能: 获得TListView 的Header 的句柄: TListView的H ...

  7. RSA加密前端JS加密,后端asp.net解密,报异常

    RSA加密前端JS加密,后端asp.net解密,报异常 参考引用:http://www.ohdave.com/rsa/的JS加密库 前端JS加密代码: function GetChangeStr() ...

  8. HDOJ(1728)逃离迷宫

    HDOJ 1728 http://acm.hdu.edu.cn/showproblem.php?pid=1728 BFS求最少转过的弯 #include <stdio.h> #includ ...

  9. C 数据类型 长度

    ----数据类型长度 C99标准并不规定具体数据类型的长度大小.计算机具有不同位数的处理器,16,32和更高位的64位处理器,在这些不同的平台上,同一种数据类型具有不同的长度. char,short, ...

  10. 使用__slots__

    [使用__slots__] 参考: 1.http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a0 ...