标签:根据 测试 效率 数据库 cal mes 自己的 nod gen
项目中日志是比较常见的一个功能模块,在开发阶段和运维阶段我们可以根据日志排查项目出现的问题,同时可以为项目运营阶段提供业务数据分析。所以日志是项目中不可或缺的功能模块,项目中一般会根据项目需要开发偏向业务的日志模块,而本博客主要介绍第三方日志框架NLog。通过引入NLog日志框架,项目中可以快速的实现基本的日志模块,大大的提高了开发效率。
添加NLog和NLog.Web.AspNetCore安装包
Install-Package NLog -Version 4.7.4
Install-Package NLog.Web.AspNetCore -Version 4.9.3
网站根目录下新建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" autoReload="true" throwExceptions="false" internalLogLevel="Off" internalLogFile="NlogRecords.log"> <!--Nlog内部日志记录为Off关闭。除非纠错,不可以设为Trace否则速度很慢,起码Debug以上--> <extensions> <add assembly="NLog.Web.AspNetCore" /> </extensions> <targets> <!--通过数据库记录日志 配置 dbProvider请选择mysql或是sqlserver,同时注意连接字符串,需要安装对应的sql数据提供程序 MYSQL: dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" connectionString="server=localhost;database=BaseMIS;user=root;password=123456" MSSQL: dbProvider="Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient" connectionString="Server=127.0.0.1;Database=BaseMIS;User ID=sa;Password=123456" --> <target name="log_database" xsi:type="Database" dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" connectionString="server=localhost;port=3306;User Id=root;password=wuzhd123456!;Database=testnlog;pooling=true;character set=utf8;Connection Timeout=160"> <commandText> INSERT INTO TblLogrecords (LogDate,LogLevel,LogType,Logger,Message,MachineName,MachineIp,NetRequestMethod ,NetRequestUrl,NetUserIsauthenticated,NetUserAuthtype,NetUserIdentity,Exception) VALUES (@LogDate,@LogLevel,@LogType,@Logger,@Message,@MachineName,@MachineIp,@NetRequestMethod ,@NetRequestUrl,@NetUserIsauthenticated,@NetUserAuthtype,@NetUserIdentity,@Exception); </commandText> <parameter name="@LogDate" layout="${date}" /> <parameter name="@LogLevel" layout="${level}" /> <parameter name="@LogType" layout="${event-properties:item=LogType}" /> <parameter name="@Logger" layout="${logger}" /> <parameter name="@Message" layout="${message}" /> <parameter name="@MachineName" layout="${machinename}" /> <parameter name="@MachineIp" layout="${aspnet-request-ip}" /> <parameter name="@NetRequestMethod" layout="${aspnet-request-method}" /> <parameter name="@NetRequestUrl" layout="${aspnet-request-url}" /> <parameter name="@NetUserIsauthenticated" layout="${aspnet-user-isauthenticated}" /> <parameter name="@NetUserAuthtype" layout="${aspnet-user-authtype}" /> <parameter name="@NetUserIdentity" layout="${aspnet-user-identity}" /> <parameter name="@Exception" layout="${exception:tostring}" /> </target> <target name="log_file" xsi:type="File" fileName="${basedir}/logs/${shortdate}.log" layout="${longdate} | ${level:uppercase=false} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" /> <!--ColoredConsole彩色控制台 xsi:type="Console"是指定输出到普通控制台--> <target name="log_console" xsi:type="ColoredConsole" useDefaultRowHighlightingRules="true" layout="${longdate}|${level}|${logger}|${message} ${exception}"> <highlight-row condition="level == LogLevel.Trace" foregroundColor="DarkGray" /> <highlight-row condition="level == LogLevel.Debug" foregroundColor="Gray" /> <highlight-row condition="level == LogLevel.Info" foregroundColor="White" /> <highlight-row condition="level == LogLevel.Warn" foregroundColor="Yellow" /> <highlight-row condition="level == LogLevel.Error" foregroundColor="Red" /> <highlight-row condition="level == LogLevel.Fatal" foregroundColor="Magenta" backgroundColor="White" /> </target> </targets> <rules> <!--跳过所有级别的Microsoft组件的日志记录--> <!--<logger name="Microsoft.*" maxlevel="Info" final="true" />--> <!-- BlackHole without writeTo --> <!--只通过数据库记录日志,这里的*,如果给了name名字,代码里用日志记录的时候,取logger需要把name当做参数--> <logger name="*" minlevel="Info" writeTo="log_database" /> <logger name="*" minlevel="Trace" writeTo="log_console" /> <logger name="*" minlevel="Warn" writeTo="log_file" /> </rules> </nlog>
c:\temp\nlog-internal.log
NLog.Web.AspNetCore
包MySql.Data.MySqlClient.MySqlConnection, MySql.Data
name="@LogType"
参数,layout="${event-properties:item=LogType}",表示@LogType参数的值从event-properties中的LogType中取aspnet-
开头的是NLog.Web.AspNetCore包中提供的方法
在CreateHostBuilder
方法内,追加使用NLog服务以及配置
.ConfigureLogging(logging => { logging.ClearProviders(); logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace); }).UseNLog(); // NLog: 依赖注入Nlog;
在Main方法中初始化配置
var host = CreateWebHostBuilder(args).Build(); Logger logger = LogManager.GetCurrentClassLogger(); try { logger.Trace("网站启动中..."); using (IServiceScope scope = host.Services.CreateScope()) { IConfiguration configuration = scope.ServiceProvider.GetRequiredService<IConfiguration>(); //获取到appsettings.json中的连接字符串 string sqlString = configuration.GetSection("Connection:MySql").Value; //确保NLog.config中连接字符串与appsettings.json中同步 NLogUtil.EnsureNlogConfig("NLog.config", sqlString); logger.Trace("初始化数据库"); //用于查看彩色控制台样式,以及日志等级过滤 logger.Trace("Test For Trace"); logger.Debug("Test For Debug"); logger.Info("Test For Info"); logger.Warn("Test For Warn"); logger.Error("Test For Error"); logger.Fatal("Test For Fatal"); } //throw new Exception("测试异常");//for test //其他项目启动时需要做的事情 //code logger.Trace("网站启动完成"); host.Run(); } catch (Exception ex) { logger.Fatal(ex, "网站启动失败"); throw; }
NLogUtil类 EnsureNlogConfig 验证是否与appsettings.json同步
/// <summary> /// 确保NLog配置文件sql连接字符串正确 /// </summary> /// <param name="nlogPath"></param> /// <param name="sqlConnectionStr"></param> public static void EnsureNlogConfig(string nlogPath, string sqlConnectionStr) { XDocument xd = XDocument.Load(nlogPath); if (xd.Root.Elements().FirstOrDefault(a => a.Name.LocalName == "targets") is XElement targetsNode && targetsNode != null && targetsNode.Elements().FirstOrDefault(a => a.Name.LocalName == "target" && a.Attribute("name").Value == "log_database") is XElement targetNode && targetNode != null) { if (!targetNode.Attribute("connectionString").Value.Equals(sqlConnectionStr))//不一致则修改 { //这里暂时没有考虑dbProvider的变动 targetNode.Attribute("connectionString").Value = sqlConnectionStr; xd.Save(nlogPath); //编辑后重新载入配置文件(不依靠NLog自己的autoReload,有延迟) LogManager.Configuration = new XmlLoggingConfiguration(nlogPath); } } }
控制台:
文件:
数据库:
.NET Core中使用NLog按等级过滤写入控制台、文件、数据库记录日志
标签:根据 测试 效率 数据库 cal mes 自己的 nod gen
原文地址:https://www.cnblogs.com/ZhengHengWU/p/13614730.html