每个人编写的程序都会有bug,我们在开发的时候可以debug去调试,但是在部署到生产环境或者用户环境下时只能靠一些用户提供的很少的信息来定位,并且很多情况这些信息是不够去准确定位问题的,那如果我们记录了所有逻辑操作信息,就像系统日志一样,那会为我们提供很方便的操作信息帮助我们定位问题。下面是我基于log4net.dll封装的logger类库,目的是方便的实现log功能。
为什么封装log4net:
因为程序如果包含多个project,那么使用log4net时每个project都需要引用并且调用下面方法private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
如果有一个类库只需要被其他project引用,然后直接就可以调用log方法,比如:Debug,Info,Warn,Error,Fatal。
封装方法:
- 新建类库,增加log4net.dll引用。
- 新建配置文件logger.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="log4configfile" value="C:\work\Project\persian\SourceCode\trunk\PersianSearch\log4config.xml"/>
</appSettings>
</configuration>
- log4.cs 代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net.Core;
using System.Configuration;
using System.IO;
using System.Xml;
using System.Reflection;
/*
* Before use this dll to log for your code, please copy logger.dll, log4net.dll, logger.config
* and log4config.xml in the same folder, then just reference logger.dll in your project, you
* could use all log method to log to debug your app or trace or record any error info. For
* log4config.xml path you could redefine it in logger.config. Also log4config.xml is a standard
* log4 config file, you could modify freely as per the rules of log4 config file.
* You could free to use it.
* Author: TIEYUN GUO
* Date: 2013/08/03
* Version: 0.1
*/
namespace logger
{
public static class log4
{
private static string currentConfig = Directory.GetCurrentDirectory() + @"\logger.config";
private static readonly log4net.ILog log = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
static log4()
{
if (!File.Exists(currentConfig))
throw new Exception("Not found logger.config file, please make sure logger.config" +
"is available in the same path with logger.dll");
string log4ConfigFilePath = GetAttributeValue(currentConfig,"log4configfile");
//if(!log4ConfigFilePath.Contains("\\"))
// log4ConfigFilePath = Directory.GetCurrentDirectory() + "\\" + log4ConfigFilePath;
if (!File.Exists(log4ConfigFilePath))
throw new Exception("Not found log4 config file: " + log4ConfigFilePath +
". Please modify log4filepath in logger.config file or copy log4config.xml to " +
Directory.GetParent(Path.GetFullPath(log4ConfigFilePath)));
log4net.Config.XmlConfigurator.Configure(new FileInfo(log4ConfigFilePath));
}
public static void Debug(string message)
{
log.Debug(message);
}
public static void Debug(string message, Exception e)
{
log.Debug(message,e);
}
public static void DebugFormat(string format, params object[] args)
{
log.DebugFormat(format, args);
}
public static void Info(string message)
{
log.Info(message);
}
public static void Info(string message, Exception e)
{
log.Info(message, e);
}
public static void InfoFormat(string format, params object[] args)
{
log.InfoFormat(format, args);
}
public static void Warn(string message)
{
log.Warn(message);
}
public static void Warn(string message, Exception e)
{
log.Warn(message, e);
}
public static void Warn(string format, params object[] args)
{
log.WarnFormat(format, args);
}
public static void Error(string message)
{
log.Error(message);
}
public static void Error(string message, Exception e)
{
log.Error(message, e);
}
public static void ErrorFormat(string format, params object[] args)
{
log.ErrorFormat(format, args);
}
public static void Fatal(string message)
{
log.Fatal(message);
}
public static void Fatal(string message, Exception e)
{
log.Fatal(message, e);
}
public static void FatalFormat(string format, params object[] args)
{
log.FatalFormat(format, args);
}
/// <summary>
/// Get property of config file
/// </summary>
/// <param name="file">log4 config file</param>
/// <param name="key"></param>
/// <returns></returns>
private static string GetAttributeValue(string file, string key)
{
string value = string.Empty;
try
{
if (File.Exists(file))
{
XmlDocument xml = new XmlDocument();
xml.Load(file);
XmlNode xNode = xml.SelectSingleNode("//appSettings");
XmlElement element = (XmlElement)xNode.SelectSingleNode("//add[@key='" + key + "']");
value = element.GetAttribute("value").ToString();
}
}
catch(Exception e)
{
throw new Exception("Read log4config file fail!", e);
}
return value;
}
}
}
使用方法:
第一:增加logger.dll引用。第二:copy log4config.xml文件与logger.config, log4net.dll和logger.dll在一个目录下。你也可以修改log4config.xml的路径在logger.config中。第三:使用log方法,例如加入debug信息as below第四:log被存放在logger.dll所在目录的log文件夹下。
InitialConfig();
timer.Start();
log4.Info("Start to sync data.");
SyncData();
timer.Stop();
log4.Info("Sync data end.");
log4.Debug("Sync data totally costs: " + timer.ElapsedMilliseconds / 1000);Notes: 目前根据我的需要只增加了文件和console日志。你可以自己加入事件日志,数据库日志等按照log4net配置文件格式。