【编译】使用log4net打造StreamInsight适配器/应用日志记录器
(注:我将代码注释修改为了中文,并对内容做了少部分修改)
在微软.NET平台下有许多种方式实现日志记录功能(如Trace,ETW等等)。为了提供更大程度的灵活性,我准备把一类日志接口放在一起,以用在各种应用程序中(我博客里的代码样例都是使用的这个方法)。我还会给出这些接口的一个实现来让它们可以利用各种日志记录框架如Tracing,ETW等,这里我用的是log4net。
- 下载log4net二进制程序包,并解压到本地磁盘中。这里将用的主要文件是log4net-1.2.10\bin\net\2.0\release\log4net.dll程序集;
- 以管理员身份运行Visual Studio命令行窗口,切换到log4net目录并将log4net.dll程序集注册进GAC(用这个命令gacutil /i log4net.dll);
- 将log4net.dll程序集加入到项目引用中;
- 基于下述代码创建StreamInsightLog类:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using log4net.Config; using System.IO; namespace IntroHost { /// <summary> /// 使用log4net实现的StreamInsight日志类 /// </summary> public class StreamInsightLog { /// <summary> /// log4net日志对象引用 /// </summary> private readonly log4net.ILog log; /// <summary> /// 日志消息所处的类别 /// </summary> private string category; /// <summary> /// 读取app.config文件并初始化log4net库 /// </summary> public static void Init() { XmlConfigurator.Configure(); } /// <summary> /// 根据某个配置文件初始化log4net库 /// </summary> /// <param name="configFile"></param> public static void Init(string configFile) { XmlConfigurator.ConfigureAndWatch( new FileInfo(configFile)); } /// <summary> /// 初始化特定类别下的StreamInsightLog对象 /// </summary> /// <param name="category"></param> public StreamInsightLog(string category) { this.log = log4net.LogManager.GetLogger(category); this.category = category; } /// <summary> /// 将异常信息记录ERROR日志 /// </summary> public void LogException(Exception ex0, string fmt, params object[] vars) { log.Error(string.Format(fmt, vars), ex0); } /// <summary> /// 记录特定日志级别的消息 /// </summary> public void LogMsg(TraceEventType type, string fmt, params object[] vars) { string message; if (vars.Any()) message = String.Format(fmt, vars); else message = fmt; switch (type) { case TraceEventType.Verbose: log.Debug(message); break; case TraceEventType.Information: log.Info(message); break; case TraceEventType.Warning: log.Warn(message); break; case TraceEventType.Error: log.Error(message); break; case TraceEventType.Critical: log.Fatal(message); break; } } public void LogInfo(string fmt, params object[] vars) { log.InfoFormat(fmt, vars); } public bool ShouldLog(TraceEventType type) { switch (type) { case TraceEventType.Verbose: return log.IsDebugEnabled; case TraceEventType.Information: return log.IsInfoEnabled; case TraceEventType.Warning: return log.IsWarnEnabled; case TraceEventType.Error: return log.IsErrorEnabled; case TraceEventType.Critical: return log.IsFatalEnabled; default: return false; } } } }
日志接口搞定,下面让我们创建下面的app.config文件来配置log4net,主要包括: - 控制台输出源(将日志记录输出到控制台)
- 文件输出源(将日志记录写到文件中,下面的注释部分)
- 两类日志类别(General和Adapter)
<?xml version="1.0" encoding="utf-8"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821"/> </configSections> <log4net> <!-- Uncomment this block to log to files <appender name="ServiceLog" type="log4net.Appender.RollingFileAppender"> <file value="logs\StreamInsightHost.log" /> <appendToFile value="true" /> <maxSizeRollBackups value="10" /> <maximumFileSize value="50MB" /> <rollingStyle value="Size" /> <staticLogFileName value="true" /> <layout type="log4net.Layout.PatternLayout"> <header value="[Header] " /> <footer value="[Footer] " /> <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" /> </layout> </appender> --> <!-- Log to the console --> <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date %-5level - %message%newline" /> </layout> </appender> <root> <!-- The master logging level; change to update all logging categories --> <level value="INFO" /> <!-- Log to the console --> <appender-ref ref="ConsoleAppender" /> <!-- Uncomment to log to file <appender-ref ref="ServiceLog" /> --> </root> <!-- Levels are DEBUG, INFO, WARNING, ERROR and FATAL --> <logger name="General"> <level value="INFO" /> </logger> <logger name="Adapter"> <level value="DEBUG" /> </logger> </log4net> </configuration>
- 在Main.cs文件中,初始化日志接口:
static void Main(string[] args) { StreamInsightLog.Init(); }
我们现在建立好了日志记录和跟踪手段,下面就可以开发适配器了!