CREATE DATABASE IF NOT EXISTS `TestNLog`; USE `TestNLog`; -- Dumping structure for table TestNLog.TblLogrecords CREATE TABLE IF NOT EXISTS `TblLogrecords` ( `Id` int(11) NOT NULL AUTO_INCREMENT, `LogDate` datetime(6) NOT NULL, `LogLevel` varchar(50) NOT NULL, `LogType` varchar(50) DEFAULT NULL, `Logger` varchar(256) NOT NULL, `Message` longtext, `MachineName` varchar(50) DEFAULT NULL, `MachineIp` varchar(50) DEFAULT NULL, `NetRequestMethod` varchar(10) DEFAULT NULL, `NetRequestUrl` varchar(500) DEFAULT NULL, `NetUserIsauthenticated` varchar(10) DEFAULT NULL, `NetUserAuthtype` varchar(50) DEFAULT NULL, `NetUserIdentity` varchar(50) DEFAULT NULL, `Exception` longtext, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=96 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
网站配置连接
appsettings.json中增加ConectionStrings节点:
"ConectionStrings": { "MySqlConnection": "server=192.168.137.10;database=TestNLog;user=root;password=mysql@local" }
统一日志记录方法
网站下新建CommonUtils文件夹,添加NLogUtil.cs文件(包含LogType定义):
using NLog; using NLog.Config; using System; using System.ComponentModel; using System.Linq; using System.Xml.Linq; namespace NLogUsage.CommonUtils { public enum LogType { [Description("网站")] Web, [Description("数据库")] DataBase, [Description("Api接口")] ApiRequest, [Description("中间件")] Middleware } public static class NLogUtil { public static Logger dbLogger = LogManager.GetLogger("logdb"); public static Logger fileLogger = LogManager.GetLogger("logfile"); /// <summary> /// 写日志到数据库 /// </summary> /// <param>日志等级</param> /// <param>日志类型</param> /// <param>信息</param> /// <param>异常</param> public static void WriteDBLog(LogLevel logLevel, LogType logType, string message, Exception exception = null) { LogEventInfo theEvent = new LogEventInfo(logLevel, dbLogger.Name, message); theEvent.Properties["LogType"] = logType.ToString(); theEvent.Exception = exception; dbLogger.Log(theEvent); } /// <summary> /// 写日志到文件 /// </summary> /// <param>日志等级</param> /// <param>日志类型</param> /// <param>信息</param> /// <param>异常</param> public static void WriteFileLog(LogLevel logLevel, LogType logType, string message, Exception exception = null) { LogEventInfo theEvent = new LogEventInfo(logLevel, fileLogger.Name, message); theEvent.Properties["LogType"] = logType.ToString(); theEvent.Exception = exception; fileLogger.Log(theEvent); } /// <summary> /// 确保NLog配置文件sql连接字符串正确 /// </summary> /// <param></param> /// <param></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); } } } } }
配置NLog依赖注入
网站Program.cs文件中,在CreateHostBuilder方法中添加以下内容: