public class Logs
{
private static Logger logger = LogManager.GetCurrentClassLogger(); //初始化日志类
/// <summary>
/// 日志状态枚举
/// </summary>
private enum LogState
{
/// <summary>
/// 用户已登录
/// </summary>
NLogin,
/// <summary>
/// 用户未登录
/// </summary>
YLogin,
}
/// <summary>
/// 静态构造函数
/// </summary>
static Logs()
{
//初始化配置日志
LogManager.Configuration = new XmlLoggingConfiguration(System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "\Demo\NLog.config");
}
/// <summary>
/// 日志写入通用方法(建议使用)
/// </summary>
/// <param name="msg">日志内容</param>
/// <param name="logType"> 日志类别
/// 类别: 1.Debug
/// 2.Info
/// 3.Error
/// 4.Fatal
/// 5.Warn
/// </param>
/// <param name="loginState">登录状态 true:有用户登录信息 false 无用户登录信息</param>
/// <remarks>
/// 注:默认类型为Info 可以配置其他日志 logType用于反射 规则一定要准确
/// 例: 1.默认日志 LogWriter("test log"); 正常的业务日志
/// 2.异常日志 LogWriter("test log","Fatal"); try catch 里请使用这个日志级别
///
/// </remarks>
public static void LogWriter(String msg, String logType = "Info", bool loginState = true)
{
try
{
String logMethod = ""; //调用者类名和方法名
if (logType == "Fatal")
{
StackTrace trace = new StackTrace();
//获取是哪个类来调用的
String invokerType = trace.GetFrame(1).GetMethod().DeclaringType.Name;
//获取是类中的那个方法调用的
String invokerMethod = trace.GetFrame(1).GetMethod().Name;
logMethod = invokerType + "." + invokerMethod + " | ";
}
String IP = HttpContext.Current.Request.UserHostAddress; //获取IP
//反射执行日志方法
Type type = typeof(Logger);
MethodInfo method = type.GetMethod(logType, new Type[] { typeof(String) });
if (loginState == true)
{
//如果是登陆状态 可以记录用户的登陆信息 比如用户名,Id等
method.Invoke(logger, new object[] { logMethod + msg + " [ " + IP + " | " + LogState.NLogin + " ]" });
}
else
{
method.Invoke(logger, new object[] { logMethod + msg + " [ " + IP + " | " + LogState.NLogin + " ]" });
}
}
catch
{
//日志代码错误,直接记录日志
Fatal(msg);
Warn(msg);
}
}
/// <summary>
/// 调试日志
/// </summary>
/// <param name="msg">日志内容</param>
private static void Debug(String msg)
{
logger.Debug(msg);
}
/// <summary>
/// 信息日志
/// </summary>
/// <param name="msg">日志内容</param>
/// <remarks>
/// 适用大部分场景
/// 1.记录日志文件
/// </remarks>
private static void Info(String msg)
{
logger.Info(msg);
}
/// <summary>
/// 错误日志
/// </summary>
/// <param name="msg">日志内容</param>
/// <remarks>
/// 适用异常,错误日志记录
/// 1.记录日志文件
/// </remarks>
private static void Error(String msg)
{
logger.Error(msg);
}
/// <summary>
/// 严重致命错误日志
/// </summary>
/// <param name="msg">日志内容</param>
/// <remarks>
/// 1.记录日志文件
/// 2.控制台输出
/// </remarks>
private static void Fatal(String msg)
{
logger.Fatal(msg);
}
/// <summary>
/// 警告日志
/// </summary>
/// <param name="msg">日志内容</param>
/// <remarks>
/// 1.记录日志文件
/// 2.发送日志邮件
/// </remarks>
private static void Warn(String msg)
{
try
{
logger.Warn(msg);
}
catch { }
}
}
web项目下面添加一个Demo文件夹创建Nlog.Config
<?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" throwExceptions="true">
<targets xsi:type="AsyncWrapper">
<!--保存至文件-->
<target name="log_file" xsi:type="File"
fileName="${basedir}/Logs/${shortdate}/${level:uppercase=false:padding=-5}.txt"
layout="${longdate} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
<!--输出至Debugger-->
<target name="debugger" xsi:type="Debugger"
layout="NLog: ${date:format=HH:mm:ss} | ${message}" />
<!--输出至控制台-->
<target name="console" xsi:type="ColoredConsole" layout="${longdate} ${message} ${exception:format=tostring}"></target>
<!--输出至邮件-->
<target xsi:type="Mail" name="infoMail"
smtpServer="smtp.163.com"
smtpPort="25"
smtpAuthentication="Basic"
smtpUserName="deno@163.com"
smtpPassword="demo"
enableSsl="true"
addNewLines="true"
from="demo@163.com"
to="demo@qq.com"
subject="Project Exception Mail"
header="*********************"
body="${longdate} | ${message} "
footer="*********************"/>
</targets>
<rules>
<logger name="*" level="Info" writeTo="log_file" />
<logger name="*" levels="Error" writeTo="log_file" />
<logger name="*" levels="Debug" writeTo="log_file" />
<!--<logger name="*" level="Debug" writeTo="debugger" />-->
<!--<logger name="*" level="Fatal" writeTo="console" />-->
<logger name="*" level="Fatal" writeTo="log_file" />
<!--<logger name="*" level="Warn" writeTo="infoMail" />-->
<logger name="*" level="Warn" writeTo="log_file" />
</rules>
</nlog>