C# NLog的使用及解决NLog无法生成日志文件问题

C# 使用NLog记录日志

跟log4net一样NLog,Nlog也是常用的记录日志组件

需要先下载好Nlog及Nlog.Config,注意我的版本号,我当前使用的4.5版本
C# NLog的使用及解决NLog无法生成日志文件问题_第1张图片

下载完成后我们的项目根目录会生成Nlog.config配置文件

具体使用参考如下配置


<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">

  
  <variable name="myvar" value="myvalue"/>

  
  <targets>

    

    
    <target xsi:type="File" name="System" fileName="${basedir}/logs/${shortdate}System.log"
        layout="${longdate} ${uppercase:${level}} ${message}" />
        
  targets>

  <rules>
    

    
    <logger name="System" minlevel="Debug" writeTo="System" />
    
  rules>
nlog>

之后我简单封装了一下Logger.cs

public class Logger
	{

		/// 
		/// 
		/// context
		/// log operation
		public static void Log(string context, string name, LogLevel lever)
		{
			try
			{
				var currentLogger = LogManager.GetLogger(name);
				if (currentLogger != null)
					currentLogger.Log(lever, context);
			}
			catch
			{

			}
		}

		public static void Log(string context, string name, LogLevel level, Exception ex)
		{
			try
			{
				var currentLogger = LogManager.GetLogger(name);
				if (currentLogger != null)
				{
					string exception = string.Empty;
					if (ex != null)
					{
						exception = "异常信息:" + ex.Message;
						if (ex.InnerException != null)
							exception += ex.InnerException.Message;
					}
					currentLogger.Log(level, context + exception);
				}
			}
			catch { }

		}

		public static void LogInfo(string context, string name)
		{
			try
			{
				var currentLogger = LogManager.GetLogger(name);
				if (currentLogger != null)
					currentLogger.Log(LogLevel.Info, context);
			}
			catch
			{

			}
		}
		public static void SystemInfo(string context)
		{
			LogInfo(context, "System");
		}
		//其它类型日志,自由添加,注意Nlog.Config也要配置好
		public static void SystemOther(string context)
		{
			LogInfo(context, "Other");
		}
	}

使用方法

SystemInfo("这是System日志")

注意,需要设置Nlog.config的属性否则无法生成日志文件

vs 解决方案中 选中Nlog.config右击 属性
C# NLog的使用及解决NLog无法生成日志文件问题_第2张图片

你可能感兴趣的:(C#,NLog,c#)