一、我们自定义一个helper类。
using System; using System.Text; using System.Web; using NLog; namespace WCFCommon { public class LogHelper { // Fields private static readonly bool Isinit = false; private static bool _logComplementEnable = false; private static bool _logDubugEnable = false; private static bool _logErrorEnable = false; private static bool _logExceptionEnable = false; private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private static bool _logInfoEnable = false; // Methods static LogHelper() { if (!Isinit) { Isinit = true; SetConfig(); } } private static string BuildMessage(string info) { return BuildMessage(info, null); } private static string BuildMessage(string info, Exception ex) { StringBuilder sb = new StringBuilder(); HttpRequest request = null; if ((HttpContext.Current != null) && (HttpContext.Current.Request != null)) { request = HttpContext.Current.Request; } sb.AppendFormat("Time:{0}-{1}\r\n", DateTime.Now, info); if (request != null) { sb.AppendFormat("Url:{0}\r\n", request.Url); if (null != request.UrlReferrer) { sb.AppendFormat("UrlReferrer:{0}\r\n", request.UrlReferrer); } string realip = (request.ServerVariables == null) ? string.Empty : request.ServerVariables["HTTP_X_REAL_IP"]; string proxy = (request.Headers == null) ? string.Empty : request.Headers.Get("HTTP_NDUSER_FORWARDED_FOR_HAPROXY"); sb.AppendFormat("UserHostAddress:{0};{1};{2}\r\n", request.UserHostAddress, realip, proxy); sb.AppendFormat("WebServer:{0}\r\n", request.ServerVariables["LOCAL_ADDR"]); } if (ex != null) { sb.AppendFormat("Exception:{0}\r\n", ex); } sb.AppendLine(); return sb.ToString(); } public static void SetConfig() { _logInfoEnable = Logger.IsInfoEnabled; _logErrorEnable = Logger.IsErrorEnabled; _logExceptionEnable = Logger.IsErrorEnabled; _logComplementEnable = Logger.IsTraceEnabled; _logDubugEnable = Logger.IsDebugEnabled; } public static void WriteComplement(string info) { if (_logComplementEnable) { Logger.Trace(BuildMessage(info)); } } public static void WriteComplement(string info, Exception ex) { if (_logComplementEnable) { Logger.Trace(BuildMessage(info, ex)); } } public static void WriteCustom(string message, string dirOrPrefix) { WriteCustom(message, dirOrPrefix, null, true); } public static void WriteCustom(string message, string dirOrPrefix, bool addIpUrl) { WriteCustom(message, dirOrPrefix, null, addIpUrl); } public static void WriteCustom(string message, string dirOrPrefix, string suffix) { WriteCustom(message, dirOrPrefix, suffix, true); } public static void WriteCustom(string message, string dirOrPrefix, string suffix, bool addIpUrl) { if (addIpUrl) { message = BuildMessage(message); } Logger logger1 = LogManager.GetLogger("LogCustom"); LogEventInfo logEvent = new LogEventInfo(LogLevel.Warn, logger1.Name, message); logEvent.Context["DirOrPrefix"] = dirOrPrefix; if (suffix != null) { logEvent.Context["Suffix"] = suffix; } logger1.Log(logEvent); } public static void WriteDebug(string info) { if (_logDubugEnable) { Logger.Debug(BuildMessage(info)); } } public static void WriteError(string info) { if (_logErrorEnable) { Logger.Error(BuildMessage(info)); } } public static void WriteException(string info, Exception ex) { if (_logExceptionEnable) { Logger.Error(BuildMessage(info, ex)); } } public static void WriteFatal(string info) { if (_logErrorEnable) { Logger.Fatal(BuildMessage(info)); } } public static void WriteInfo(string info) { if (_logInfoEnable) { Logger.Info(BuildMessage(info)); } } } }
二、
NLog中Logger类的方法解释:
1. Trace - 最常见的记录信息,一般用于普通输出
2. Debug - 同样是记录信息,不过出现的频率要比Trace少一些,一般用来调试程序
3. Info - 信息类型的消息
4. Warn - 警告信息,一般用于比较重要的场合
5. Error - 错误信息
6. Fatal - 致命异常信息。一般来讲,发生致命异常之后程序将无法继续执行。
对于这些方法,我们一一配置过去。
<?xml version="1.0" encoding="utf-8" ?> <!-- This file needs to be put in the application directory. Make sure to set 'Copy to Output Directory' option in Visual Studio. --> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <variable name="logDirectory" value="E:\wcfLog\"/><!--value表示日志的路径--> <targets> <!--target设置目标存放的路径--> <target name="Info" xsi:type="File" fileName="${logDirectory}/Info/${date:format=yyyyMMddHH}.txt" layout="${message}" archiveAboveSize="5000000" Encoding="utf-8"/> <target name="Complement" xsi:type="File" fileName="${logDirectory}/Complement/${date:format=yyyyMMddHH}.txt" layout="${message}" archiveAboveSize="5000000" Encoding="utf-8"/> <target name="Debug" xsi:type="File" fileName="${logDirectory}/Debug/${date:format=yyyyMMddHH}.txt" layout="${message}" archiveAboveSize="5000000" Encoding="utf-8"/> <target name="Exception" xsi:type="File" fileName="${logDirectory}/Exception/${date:format=yyyyMMddHH}.txt" layout="${message}" archiveAboveSize="5000000" Encoding="utf-8"/> <target name="Fatal" xsi:type="File" fileName="${logDirectory}/Fatal/${date:format=yyyyMMddHH}.txt" layout="${message}" archiveAboveSize="5000000" Encoding="utf-8"/> <target name="LogCustom" xsi:type="File" layout="${message}" fileName="${logDirectory}\${event-context:DirOrPrefix}${date:format=yyyyMMddHH}${event-context:Suffix}.txt" archiveAboveSize="5000000" Encoding="utf-8"/> </targets> <rules> <!--路由规则,表示每个级别的日志所对应的target目标路径,writeTo 对应target中的name--> <logger name="*" level="Info" writeTo="Info"/> <logger name="*" level="Trace" writeTo="Complement"/> <logger name="*" level="Debug" writeTo="Debug"/> <logger name="*" level="Error" writeTo="Exception"/> <logger name="*" level="Fatal" writeTo="Fatal"/> <logger name="LogCustom" level="Warn" writeTo="LogCustom" /> </rules> </nlog>
配置文件搜索规则:
如果是运行一个独立的*.exe客户端可执行程序时,NLog将在以下目录搜索配置信息
1. 标准的程序配置文件(通常为 程序名.exe.config)
2. 程序目录下的程序名.exe.nlog文件
3. 程序目录下的NLog.config文件
4. NLog.dll所在目录下的NLog.dll.nlog文件
5. 如果定义了NLOG_GLOBAL_CONFIG_FILE环境变量,则该变量所指向的文件
如果是一个ASP.NET程序,被搜索的目录包括:
1. 标准的web程序配置文件web.config
2. 和web.config在同一目录下的web.nlog文件
3. 程序目录下的NLog.config文件
4. NLog.dll所在目录下的NLog.dll.nlog文件
5. 如果定义了NLOG_GLOBAL_CONFIG_FILE环境变量,则该变量所指向的文件。
我们把刚才的配置文件存储在规则下的目录。
三、来吧,我们来调用
class Program { static void Main(string[] args) { LogHelper.WriteError("错误"); LogHelper.WriteDebug("调试"); LogHelper.WriteFatal("致命异常"); LogHelper.WriteInfo("记录信息"); LogHelper.WriteCustom("自定义","test\\");//test表示目录文件夹 LogHelper.WriteComplement("最常见的记录信息"); } }
结果看到了: