This article shows how to log to MySQL in a .NET Core application using NLog.
Code: https://github.com/damienbod/AspNetCoreNlog
2020-01-12 Updated to .NET Core 3.1, NLog.Web.AspNetCore 4.9.0
2018-04-04 Updated to NLog.Web.AspNetCore 4.5.1, ASP.NET Core 2.0
NLog posts in this series:
- ASP.NET Core logging with NLog and Microsoft SQL Server
- ASP.NET Core logging with NLog and Elasticsearch
- Settings the NLog database connection string in the ASP.NET Core appsettings.json
- ASP.NET Core, logging to MySQL using NLog
- .NET Core logging with NLog and PostgreSQL
Set up the MySQL database
MySQL Workbench can be used to add the schema ‘nlog’ which will be used for logging to the MySQL database. The user ‘damienbod’ is also required, which must match the defined user in the connection string. If you configure the MySQL database differently, then you need to change the connection string in the nlog.config file.
You also need to create a log table. The following script can be used. If you decide to use NLog.Web in a ASP.NET Core application and add some extra properties, fields to the logs, then this script needs to be extended and also the database target in the nlog.config.
CREATE TABLE `log` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT, `Application` varchar(50) DEFAULT NULL, `Logged` datetime DEFAULT NULL, `Level` varchar(50) DEFAULT NULL, `Message` varchar(512) DEFAULT NULL, `Logger` varchar(250) DEFAULT NULL, `Callsite` varchar(512) DEFAULT NULL, `Exception` varchar(512) DEFAULT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
Add NLog and the MySQL provider to the project.
The MySql.Data pre release NuGet package can be used to log to MySQL. Add this to your project.
<Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <TargetFramework>netcoreapp2.0</TargetFramework> <AssemblyName>ConsoleNLog</AssemblyName> <OutputType>Exe</OutputType> <PackageId>ConsoleNLog</PackageId> <PackageTargetFallback>$(PackageTargetFallback);dotnet5.6;portable-net45+win8</PackageTargetFallback> <GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute> <GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute> <GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.6" /> <PackageReference Include="NLog.Web.AspNetCore" Version="4.5.1" /> <PackageReference Include="MySql.Data" Version="8.0.10-rc" /> </ItemGroup> <ItemGroup> <None Update="nlog.config"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> </Project>
The NLog.Web.AspNetCore package also needs to be added or just NLog if you do not require any web extensions.
nlog.config
The database target needs to be configured to log to MySQL. The database provider is set to use the MySQL.Data package which was downloaded using NuGet. If your using a different MySQL provider, this needs to be changed. The connection string is also set here, which matches what was configured previously in the MySQL database using Workbench. If you read the connection string from the app settings, a NLog variable can be used here.
<target name="database" xsi:type="Database" dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data" connectionString="server=localhost;Database=nlog;user id=damienbod;password=1234" > <commandText> insert into nlog.log ( Application, Logged, Level, Message, Logger, CallSite, Exception ) values ( @Application, @Logged, @Level, @Message, @Logger, @Callsite, @Exception ); </commandText> <parameter name="@application" layout="AspNetCoreNlog" /> <parameter name="@logged" layout="${date}" /> <parameter name="@level" layout="${level}" /> <parameter name="@message" layout="${message}" /> <parameter name="@logger" layout="${logger}" /> <parameter name="@callSite" layout="${callsite:filename=true}" /> <parameter name="@exception" layout="${exception:tostring}" /> </target>
NLog can then be used in the application.
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NLog; using NLog.Targets; namespace ConsoleNLog { public class Program { public static void Main(string[] args) { GlobalDiagnosticsContext.Set("configDir", "C:\\git\\damienbod\\AspNetCoreNlog\\Logs"); var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); logger.Warn("console logging is great"); Console.WriteLine("log sent"); Console.ReadKey(); } } }
Full nlog.config file:
https://github.com/damienbod/AspNetCoreNlog/blob/master/src/ConsoleNLogMySQL/nlog.config
Links
https://github.com/nlog/NLog/wiki/Database-target
https://github.com/NLog/NLog.Extensions.Logging
https://docs.asp.net/en/latest/fundamentals/logging.html
https://msdn.microsoft.com/en-us/magazine/mt694089.aspx
https://docs.asp.net/en/latest/fundamentals/configuration.html