重庆熊猫 Loading

ASP.NET Core 6 接入NLog 并写入日志到MySQL数据库

环境

VS 2022
ASP.NET 7
NLog 5
MySQL 8

安装包

dotnet add package NLog.Web.AspNetCore
dotnet add package NLog.Database
dotnet add package MySql.Data

数据库准备(MySQL)

在数据库中创建sql

CREATE DATABASE `ApplicationLog`;

use `ApplicationLog`;

CREATE TABLE `LogRecords` (
  `LogId` bigint NOT NULL AUTO_INCREMENT,
  `MachineName` varchar(255) NOT NULL,
  `Application` varchar(255) NOT NULL,
  `CreateDateTime` datetime NOT NULL,
  `Thread` varchar(255) NOT NULL,
  `LogLevel` varchar(255) NOT NULL,
  `Logger` varchar(255) NOT NULL,
  `Message` TEXT NOT NULL,
  `Exception` TEXT NOT NULL,
  PRIMARY KEY (`LogId`)
) ENGINE=InnoDB AUTO_INCREMENT=36 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

创建配置文件

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"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
      autoReload="true"
      throwExceptions="true"
      internalLogLevel="Off"
	  internalLogFile="/NLog.config"
	  >
	<!-- throwExceptions在生成环境下记得关闭,即设置为false -->
	<extensions>
		<add assembly="NLog.Web.AspNetCore"/>
	</extensions>


	<targets>
		<!-- 文件日志 -->
		<!-- archive相关参数:文件拆分,每100M拆分一个新文件 -->
		<!--<target xsi:type="File"
            name="file_log"
            fileName="NLog\${shortdate}\${event-properties:filename}${shortdate}.log"
            layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}"
            archiveFileName="NLog\${shortdate}\${event-properties:filename}${shortdate}.{####}.log"
            archiveNumbering="Rolling"
            archiveAboveSize="10485760"
            concurrentwrites="true"
            maxArchiveFiles="100"
              />-->

		<!-- 数据库日志(MySQL) -->
		<!-- 需要安装包:dotnet add package NLog.Database -->
		<!-- 需要安装包:dotnet add package MySql.Data -->
		<target name="mysql_log" xsi:type="Database"
            dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data"
            connectionString="server=192.168.100.100;database=ApplicationLog;user=ccccc;pwd=ccccc;SslMode=none"
            commandText="INSERT INTO LogRecords(MachineName, Application,CreateDateTime, Thread, `LogLevel`, `Logger`, `Message`, `Exception`)VALUES(@MachineName,@Application,@CreateDateTime, @Thread,@LogLevel, @Logger, @Message, @Exception);"
			async="true"
				>

			<parameter name="@MachineName" layout="${machinename}" />
			<parameter name="@Application" layout="Whale.Backend.WebAPI" />
			<parameter name="@CreateDateTime" layout="${date}" />
			<parameter name="@Thread" layout="${threadid}" />
			<parameter name="@LogLevel" layout="${level}" />
			<parameter name="@Logger" layout="${logger}" />
			<parameter name="@Message" layout="${message}" />
			<parameter name="@Exception" layout="${exception:tostring}" />
		</target>
	</targets>


	<rules>
		<!--路由顺序会对日志打印产生影响。路由匹配逻辑为顺序匹配。-->

		<!--忽略ASP.NET Core框架的日志-->
		<!--<logger name="Microsoft.*" minlevel="Trace"  final="true" />-->

		<!-- 文件日志 -->
		<!--<logger name="*" minlevel="Trace" writeTo="file_log" />-->

		<!-- 数据库日志(MySQL) -->
		<logger name="*" minlevel="Trace" writeTo="mysql_log" />
	</rules>
</nlog>

引入NLog组件 到 ASP.NET 7

打开Program.cs文件:

using NLog.Web;

// NLog: Setup NLog for Dependency injection
builder.Logging.ClearProviders();
builder.Host.UseNLog();

在程序中使用

private readonly ILogger<XXXXXController> _logger;
public XXXXXController(ILogger<XXXXXController> logger)
{
    _logger = logger;
    this._logger.LogError("First Test");
}

参考链接

https://nlog-project.org/download/
https://github.com/NLog/NLog.Web
https://github.com/NLog/NLog/wiki/Getting-started-with-ASP.NET-Core-6
https://github.com/NLog/NLog/wiki/Database-target
https://www.cnblogs.com/wei325/p/16000271.html
https://www.cnblogs.com/haiouxiangyun/p/15921375.html
https://www.c-sharpcorner.com/article/implementation-of-nlog-with-net-6-web-api/
https://damienbod.com/2017/03/03/net-core-logging-to-mysql-using-nlog/
https://www.thecodebuzz.com/nlog-database-logging-asp-net-core-csharp/
https://blog.elmah.io/nlog-tutorial-the-essential-guide-for-logging-from-csharp/
https://www.cnblogs.com/muyeh/p/9788311.html

posted @ 2023-04-19 16:56  重庆熊猫  阅读(445)  评论(0编辑  收藏  举报