About NLog
NLog is a simple and flexible .NET logging libraries, NLog the API is very similar to log4net, configuration is very simple. Output log supports many forms: text files, system logs, database, consoles, mail, etc.
1.NLog Profile
In nuget console input nlog installation command: Install-Package NLog.Config
Way Nlog configuration commonly used in two
1. Direct use of the profile or web application configuration file (app.config / web.config)
2.NLog.config this is a good form (recommended)
Profiles of the main labels are: Targets and rules :
<Targets /> - defines a target log / output, the lower is the <target>
<Rules /> - routing rules defined in the log, is lower <logger>
2. Introduction label
<nlog>标签
autoReload 修改配置文件后是否允许自动加载无须重启程序
throwExceptions 内部日志系统抛出异常(建议throwExceptions的值设为“false”,这样由于日志引发的问题不至于导致应用程序的崩溃。)
internalLogLevel 可选Trace|Debug|Info|Warn|Error|Fatal决定内部日志的级别 Off 关闭
internalLogFile 把内部的调试和异常信息都写入指定文件里
<targets>标签
<target />定义了日志的输出,可以设置文件名称和格式,输出方式。
name 自定义该target的名字,可供rule规则里使用
type 定义类型,官方提供了很多可选类型,常用的还是 File \Database \Colored Console\ Mail
layouts 用来规定布局样式,语法“${属性}”,可以把上下文信息插入到日志中,官方提供的可以用的属性见文末附录
<rules>标签
<logger/>定义日志的记录规则,记录范围
name 记录者的名字
minlevel 最低级别
maxlevel 最高级别
level 单一日志级别
levels 一系列日志级别,由逗号分隔。
<Variable> tag
变量定义
<!-- 定义变量var1-->
<variable name="var1" value="${basedir}/logs"/>
<targets>
<!-- 使用变量var1-->
<target name="File" xsi:type="File" fileName="${var1}/${shortdate}.txt"/>
</targets>
3. A simple chestnuts
Logging to color console, log text file and mysql databases. First, add the following Nlog.config file, placed in the bin console project / debug directory
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true">
<targets>
<!--控制台彩色打印-->
<target name="console" xsi:type="ColoredConsole" useDefaultRowHighlightingRules="false" layout="${longdate}|${pad:padding=5:inner=${level:uppercase=true}}|${message}" >
<highlight-row condition="level == LogLevel.Debug" foregroundColor="DarkGray" />
<highlight-row condition="level == LogLevel.Info" foregroundColor="Gray" />
<highlight-row condition="level == LogLevel.Warn" foregroundColor="Yellow" />
<highlight-row condition="level == LogLevel.Error" foregroundColor="Red" />
<highlight-row condition="level == LogLevel.Fatal" foregroundColor="Red" backgroundColor="White" />
</target>
<!--写入log文本文件-->
<target name="file" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
<target xsi:type="File" fileName="${basedir}/logs/nlog/AT___${shortdate}.log" layout="----------------日志记录开始----------------${newline}【日志时间】:${longdate} ${newline}【日志级别】:${level:uppercase=true}${newline}【异常相关信息】${newline}${message}${newline}${newline}${newline}" />
</target>
<!--写入mysql数据库-->
<target name="db" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
<target type="Database" dbProvider="MySql.Data.MySqlClient" connectionString="server=10.0.10.66;port=3306;database=logedemo;uid=root;pwd=123321;SslMode=none">
<commandText>
INSERT INTO tbLog(Timestamp,Level,Message,StackTrace) VALUES(@time_stamp, @level, @message, @stacktrace);
</commandText>
<!--database connection parameters-->
<parameter name="@time_stamp" layout="${date}" />
<parameter name="@level" layout="${level:uppercase=true}" />
<parameter name="@message" layout="${message}" />
<parameter name="@stacktrace" layout="${stacktrace}" />
</target>
</target>
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="console" />
<logger name="*" minlevel="Info" writeTo="db" />
<logger name="*" minlevel="Debug" writeTo="file" />
</rules>
</nlog>
LogHelper is a simple helper achieved through expansion of String, call the code is as follows:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("---------------------------begin");
"helper logs debug".Debug();
"helper logs info".Info();
"helper logs warn".Warn();
"helper logs error".Error();
"helper logs fatal".Fatal();
Console.WriteLine("---------------------------end");
Console.ReadKey();
}
}
public static class LogHelper
{
private static ILogger logger = GetLogger();
private static ILogger GetLogger()
{
LogManager.Configuration = new XmlLoggingConfiguration(Path.Combine(AppDomain.CurrentDomain.BaseDirectory + @"\Nlog.config"));
return LogManager.GetCurrentClassLogger();
}
/// <summary>
/// 调试
/// </summary>
/// <param name="debug"></param>
public static void Debug(this string debug)
{
logger.Debug(debug);
}
/// <summary>
/// 信息
/// </summary>
/// <param name="info"></param>
public static void Info(this string info)
{
logger.Info(info);
}
/// <summary>
/// 警告
/// </summary>
/// <param name="warn"></param>
public static void Warn(this string warn)
{
logger.Warn(warn);
}
/// <summary>
/// 错误
/// </summary>
/// <param name="error"></param>
public static void Error(this string error)
{
logger.Error(error);
}
/// <summary>
/// 严重错误
/// </summary>
/// <param name="fatale"></param>
public static void Fatal(this string fatal)
{
logger.Fatal(fatal);
}
/// <summary>
/// 跟踪
/// </summary>
/// <param name="trace"></param>
public static void Trace(this string trace)
{
logger.Trace(trace);
}
}
Record results are as follows:
Console log information using color highlight display
the effect is as follows mysql
log files results are as follows
Exception information here is just a simple word, in the actual development we can add a lot of content to the abnormality-related information, the following is a .Net exception log WebApi of the display:
The filter code is as follows
/// <summary>
/// 异常处理过滤器
/// </summary>
public class ErrorHandleAttribute : ExceptionFilterAttribute
{
/// <summary>
/// 异常处理过滤器
/// </summary>
/// <param name="actionExecutedContext"></param>
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
//获取客户端Ip
string clientIP = GetHostAddress();//主机Ip
//获取httpmethod
string strHttpMethod = actionExecutedContext.Request.Method.ToString();
//请求的url
string url = actionExecutedContext.Request.RequestUri.AbsoluteUri;
//异常信息
string exceptionMsg = actionExecutedContext.Exception.Message;
//异常定位
string exceptionPosition = actionExecutedContext.Exception.StackTrace.Split(new string[] { "\r\n" }, StringSplitOptions.None).Where(s => !string.IsNullOrWhiteSpace(s)).First().Trim();
//string stack
//记录的message
string message = $"----1.[客户端Ip]:{ clientIP} " + Environment.NewLine + $"----2.[请求方法]:{ strHttpMethod} " + Environment.NewLine + $"----3.[请求url]:{ url }" + Environment.NewLine + $"----4.[异常信息]:{exceptionMsg} " + Environment.NewLine + $"----5.[异常定位]:{exceptionPosition}";
//Log4net记录
LogHelper.WriteErrorLog("", message);
//nlog记录
NlogHelper.WriteErrorLog(message);
actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(
HttpStatusCode.InternalServerError,
new { msg = "服务器忙,请稍后再试!" });
}
/// <summary>
/// 获取客户端IP地址(无视代理)
/// </summary>
/// <returns>若失败则返回回送地址</returns>
public static string GetHostAddress()
{
string userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(userHostAddress))
{
if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
if (string.IsNullOrEmpty(userHostAddress))
{
userHostAddress = HttpContext.Current.Request.UserHostAddress;
}
}
//最后判断获取是否成功,并检查IP地址的格式(检查其格式非常重要)
if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
{
return userHostAddress;
}
return "127.0.0.1";
}
/// <summary>
/// 检查IP地址格式
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
public static bool IsIP(string ip)
{
return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
}
}
4.layout parameter list
${appdomain} | The current application domain |
${assembly-version} | application |
${basedir} | The basic directory for the application domain. |
${callsite} | (Information source class name, a method name and related information). |
${counter} | Numerical |
${date} | The current date and time. |
${environment} | Environment Variables |
${exception} | exception information |
$ {Guid} | GUID |
${identity} | Thread identification information |
${level} | level. |
${log4jxmlevent} | XML Event Description |
${logger} | Recorder name |
$ {Longdate} | Date and time format classification yyyy-MM-dd HH: mm: ss.ffff. |
${machinename} | name |
${message} | News |
${newline} | Character 换行 |
${processid} | The current process identifier |
${processinfo} | Run Information |
${processname} | The name of the current process. |
${processtime} | During which time format HH: MM: ss.mmm. |
$ {} Shortdate | A short format YYYY-MM-DD. |
${threadid} | Identifier for the current thread. |
${threadname} | The current thread. |
${ticks} | The current date and time. |
${time} | 24-hour format HH: MM: ss.mmm. |
$ {Was} | {$ Var} - new variables (4.1) |
Added: Below is a sub-level record Nlog.Config, this configuration file and the top of the LogHelper can be used together.
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true">
<targets>
<target name="Debug" xsi:type="file" fileName="F:/Logs/Debug/${shortdate}-Debug.log" layout="----------------日志记录开始----------------${newline}【日志时间】:${longdate} ${newline}【日志级别】:${level:uppercase=true}${newline}【相关信息】${newline}${message}${newline}${newline}${newline}" />
<target name="Warn" xsi:type="file" fileName="F:/Logs/Warn/${shortdate}-Warn.log" layout="----------------日志记录开始----------------${newline}【日志时间】:${longdate} ${newline}【日志级别】:${level:uppercase=true}${newline}【相关信息】${newline}${message}${newline}${newline}${newline}" />
<target name="Error" xsi:type="file" fileName="F:/Logs/Error/${shortdate}-Error.log" layout="----------------日志记录开始----------------${newline}【日志时间】:${longdate} ${newline}【日志级别】:${level:uppercase=true}${newline}【相关信息】${newline}${message}${newline}${newline}${newline}" />
<target name="Info" xsi:type="file" fileName="F:/Logs/Info/${shortdate}-Info.log" layout="----------------日志记录开始----------------${newline}【日志时间】:${longdate} ${newline}【日志级别】:${level:uppercase=true}${newline}【相关信息】${newline}${message}${newline}${newline}${newline}" />
<target name="Fatal" xsi:type="file" fileName="F:/Logs/Fatal/${shortdate}-Fatal.log" layout="----------------日志记录开始----------------${newline}【日志时间】:${longdate} ${newline}【日志级别】:${level:uppercase=true}${newline}【相关信息】${newline}${message}${newline}${newline}${newline}" />
<target name="Trace" xsi:type="file" fileName="F:/Logs/Trace/${shortdate}-Trace.log" layout="----------------日志记录开始----------------${newline}【日志时间】:${longdate} ${newline}【日志级别】:${level:uppercase=true}${newline}【相关信息】${newline}${message}${newline}${newline}${newline}" />
</targets>
<rules>
<logger name="*" levels="Info" writeTo="Info" />
<logger name="*" levels="Warn" writeTo="Warn" />
<logger name="*" levels="Trace" writeTo="Trace" />
<logger name="*" levels="Debug" writeTo="Debug" />
<logger name="*" levels="Error" writeTo="Error" />
<logger name="*" levels="Fatal" writeTo="Fatal" />
</rules>
</nlog>