Nlog日志记录组件使用

前面做的项目都是用的log4或者用个文件类写入文件中记录日志,这个nlog用着很方便,同时也有net core的版本,一步一步操作吧

1,nuget 中找到nlog并下载安装,注意框架版本,也可以去官网下载 :https://nlog-project.org/

2,安装ok后直接上代码

public sealed class Log
    {
        private static Logger _logger = LogManager.GetCurrentClassLogger();
         
        public static void Trace(string strMsg)
        {
            _logger.Trace(strMsg);
        }
        
        //有很多重载,可以看提示
        public static void Trace(Exception e,string strMsg)
        {
            _logger.Trace(e,strMsg); 
        }
        
        public static void Debug(string strMsg)
        {
            _logger.Debug(strMsg);
        }

        public static void Info(string strMsg)
        {
            _logger.Info(strMsg);
        }

        public static void Warn(string strMsg)
        {
            _logger.Warn(strMsg);
        }

        public static void Warn(Exception e)
        {
            _logger.Warn(e);
        }

        public static void Warn(Exception e,string strMsg)
        {
            _logger.Warn(e,strMsg);
        }
         
        public static void Error(string strMsg)
        {
            _logger.Error(strMsg);
        }

        public static void Error(Exception e, string strMsg)
        {
            _logger.Error(strMsg);
        }

        public static void Error(Exception e)
        {
            _logger.Error(e);
        }

        public static void Fatal(string strMsg)
        {
            _logger.Fatal(strMsg);
        }

    }

2,修改 Nlog.config 的文件,不修改有默认的格式和存储方式

    2.1 可以通过文件方式记录,配置文件如下

当然格式化的值有很多,可以查看官方文档

<?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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Off">
     
     <variable name="fileFormat"
          value="
            ${newline}date: ${date}
            ${newline}level: ${level}
            ${newline}logger: ${logger}
            ${newline}machinename: ${machinename}
            ${newline}message: ${message}
            ${newline}------------------------------------------------------------" /> 


    <targets>  <!-- async="true" 使用异步确保程序退出,日志写完-->

        <target name="logfile" 
		xsi:type="File" 
		maxArchiveFiles="1" 
		layout="${fileFormat}"
		archiveAboveSize="102400000"  
		fileName="${basedir}/Logs/${date:format=yyyy-MM}/${shortdate}.log" />

    </targets>

    <rules> 
        <logger name="*" minlevel="Info" writeTo="logfile" />
	   <logger name="*" minlevel="Trace" writeTo="file"/>  <!--写入到文件--> 
    </rules>
</nlog>

 

    2.2 执行sql记录到数据库中,配置如下

<?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"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Trace" internalLogFile="Nlog.log">

<variable name="variable1"
	value="
	${newline} date:	${date}
	${newline}level:	${level}
	${newline}logger:	${logger}
	${newline}machinename:	${machinename}
	${newline}message:	${message}
	${newline}appdomain:	${appdomain}
	${newline}assembly-version:	${assembly-version}
	${newline}basedir:	${basedir}
	${newline}callsite:	${callsite}
	${newline}callsite-linenumber:	${callsite-linenumber}
	${newline}counter:	${counter}
	${newline}nlogdir:	${nlogdir}
	${newline}processid:	${processid}
	${newline}processname:	${processname}
	${newline}specialfolder:	${specialfolder}
	${newline}stacktrace: ${stacktrace}${newline}" />

<targets>
<!-- <target name="log_file"
	xsi:type="File"
	fileName="${basedir}/LogInformation/${level}_${shortdate}.txt"
	layout="${variable1}" />-->

	<target
		name="log_database"
		xsi:type="Database"
		connectionString="Data Source=.;Initial Catalog=localtext;Persist Security Info=True;User ID=sa;Password=">
		<commandText>
		insert into NLogInfo([Date],[origin],[Level],[Message],[Detail]) values (getdate(), @origin, @logLevel, @message,@detail);
		</commandText>
		<!--日志来源-->
		<parameter name="@origin" layout="${callsite}" />
		<!--日志等级-->
		<parameter name="@logLevel" layout="${level}" />
		<!--日志消息-->
		<parameter name="@message" layout="${message}" />
		<!--引用variable1信息-->
		<parameter name="@detail" layout="${variable1}" />
	</target>
</targets>

<rules>
	<!--<logger name="*" writeTo="log_file" />-->
	<logger name="*" writeTo="log_database" />
</rules>
</nlog>

  NLogInfo的表结构创建脚本也给出来:

CREATE TABLE [dbo].[NLogInfo2](
	[LogId] [int] IDENTITY(1,1) NOT NULL,
	[Date] [datetime] NOT NULL,
	[Origin] [nvarchar](100) NULL,
	[Level] [nvarchar](50) NULL,
	[Message] [nvarchar](max) NULL,
	[Detail] [nvarchar](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

3,运行测试

class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("开始 ...");

            try
            {
                throw new Exception("测试错误");
            }
            catch (Exception e)
            {
                for (int i = 0; i < 10; i++)
                {
                    Log.Error(e.Message);

                    Console.WriteLine($"执行了{i + 1}条记录 ...");
                }
            }
            Console.ReadKey();
        }

    }

 3.1 执行到数据库中的结果

3.2.执行到文件中的结果

ok,写到这里,欢迎指教!

 

 

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值