<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>database logging asp net core &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/database-logging-asp-net-core/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Fri, 05 Mar 2021 03:26:40 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>database logging asp net core &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Perform Database Logging Using NLog in ASP.NET Core</title>
		<link>https://topreviewhostingasp.net/how-to-perform-database-logging-using-nlog-in-asp-net-core/</link>
					<comments>https://topreviewhostingasp.net/how-to-perform-database-logging-using-nlog-in-asp-net-core/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 05 Mar 2021 03:26:35 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core hosting]]></category>
		<category><![CDATA[asp net core tips]]></category>
		<category><![CDATA[database logging asp net core]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=2934</guid>

					<description><![CDATA[NLog is a highly efficient logging framework which helps us enabling logging to almost all logging source format including Console, File, Database logging, etc. High-end logging requirements like&#160;Database&#160;or&#160;File&#160;or&#160;Rolling File&#160;logging provider are still not available through the .NET Core framework. Currently, the available ASP.NET Core version logging framework is already very rich and gives us a [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>NLog is a highly efficient logging framework which helps us enabling logging to almost all logging source format including Console, File, Database logging, etc.</p>



<p>High-end logging requirements like&nbsp;<strong>Database&nbsp;</strong>or&nbsp;<strong>File&nbsp;</strong>or<strong>&nbsp;Rolling File&nbsp;</strong>logging provider are still not available through the .NET Core framework.</p>



<p>Currently, the available ASP.NET Core version logging framework is already very rich and gives us a lot of flexibility of logging to different logging providers like Console, Event, EventSource, etc.</p>



<p>We shall be targeting&nbsp;<strong>SQL&nbsp;</strong>Databaseas logging source.</p>



<p>NLog supports below database provider as well,</p>



<ul><li>System.Data.OracleClient</li><li>Oracle.DataAccess.Client</li><li>System.Data.SQLite</li><li>Npgsql</li><li>MySql.Data.MySqlClient</li></ul>



<h2 class="wp-block-heading">Getting started</h2>



<h3 class="wp-block-heading">Create ASP.NET Core API</h3>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="766" height="296" src="https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_1.jpg" alt="" class="wp-image-2935" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_1.jpg 766w, https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_1-300x116.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_1-50x19.jpg 50w" sizes="(max-width: 766px) 100vw, 766px" /></figure>



<p>NLog is available as NuGet package. Please use the latest available version available for the ASP.NET Core version.</p>



<pre class="wp-block-code"><code>PM>Install-Package NLog.Web.AspNetCore -Version 4.9.1
</code></pre>



<p>Additionally please install below NuGet package for SQL database provider support</p>



<pre class="wp-block-code"><code>PM>Install-Package System.Data.SqlClient -Version 4.81
</code></pre>



<p>OR</p>



<p>You can also also install the packages from Nuget Package Manager,</p>



<figure class="wp-block-image size-large"><img decoding="async" width="766" height="216" src="https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_2.jpg" alt="" class="wp-image-2936" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_2.jpg 766w, https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_2-300x85.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_2-50x14.jpg 50w" sizes="(max-width: 766px) 100vw, 766px" /></figure>



<h3 class="wp-block-heading">NLog Database Configuration</h3>



<p>NLog support multiple ways of managing the configuration like you can use code or combination of code and config file etc.</p>



<h3 class="wp-block-heading">DDL – Create SQL Table schema</h3>



<p>I have used below script to create the&nbsp;<em>NlogDBLog</em>&nbsp;table.</p>



<p>Sample DDL file can be found on GitHub,</p>



<pre class="wp-block-code"><code>SET ANSI_NULLS ON
 SET QUOTED_IDENTIFIER ON
 CREATE TABLE &#91;dbo].&#91;NlogDBLog] (
     &#91;Id] &#91;int] IDENTITY(1,1) NOT NULL,
     &#91;Application] &#91;nvarchar](50) NOT NULL,
     &#91;Logged] &#91;datetime] NOT NULL,
     &#91;Level] &#91;nvarchar](50) NOT NULL,
     &#91;Message] &#91;nvarchar](max) NOT NULL,
     &#91;Logger] &#91;nvarchar](250) NULL,
     &#91;Callsite] &#91;nvarchar](max) NULL,
     &#91;Exception] &#91;nvarchar](max) NULL,
   CONSTRAINT &#91;PK_dbo.NlogDBLog] PRIMARY KEY CLUSTERED (&#91;Id] ASC)
     WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON &#91;PRIMARY]
 ) ON &#91;PRIMARY]</code></pre>



<p>Please update the above script for any customization if needed.</p>



<p>After running the above script our database schema looks as below,</p>



<figure class="wp-block-image size-large"><img decoding="async" width="365" height="238" src="https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_3.jpg" alt="" class="wp-image-2937" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_3.jpg 365w, https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_3-300x196.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_3-50x33.jpg 50w" sizes="(max-width: 365px) 100vw, 365px" /></figure>



<h3 class="wp-block-heading">Create NLog.Config</h3>



<p>Below is sample config file,</p>



<pre class="wp-block-code"><code>&lt;?xml version="1.0" encoding="utf-8" ?>
&lt;nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogLevel="Warn"
      internalLogFile="C:\temp\Logs\internal-nlog4txt">
  &lt;extensions>
    &lt;add assembly="NLog.Web.AspNetCore"/>
  &lt;/extensions>
 
  &lt;targets>
 
    &lt;target name="database" xsi:type="Database">
      &lt;connectionString>
        Server=localhost\SQL;Database=master;Trusted_Connection=True;
      &lt;/connectionString>
      &lt;commandText>
        insert into dbo.NlogDBLog (
        Application, Logged, Level, Message,
        Logger, CallSite, Exception
        ) values (
        @Application, @Logged, @Level, @Message,
        @Logger, @Callsite, @Exception
        );
      &lt;/commandText>
      &lt;parameter name="@application" layout="AspNetCoreNlog" />
      &lt;parameter name="@logged" layout="${date}" />
      &lt;parameter name="@level" layout="${level}" />
      &lt;parameter name="@message" layout="${message}" />
      &lt;parameter name="@logger" layout="${logger}" />
      &lt;parameter name="@callSite" layout="${callsite:filename=true}" />
      &lt;parameter name="@exception" layout="${exception:tostring}" />
    &lt;/target>
  &lt;/targets>
 
  &lt;rules>
    &lt;logger name="*" minlevel="Trace" writeTo="database" />
  &lt;/rules>
&lt;/nlog></code></pre>



<p>In the above Configuration we have defined below,</p>



<ul><li><strong>name </strong>– Our custom target name for the given provider identification. It should be the same as <em>writeTo </em>field in Rules tag.</li><li><strong>type </strong>– Target type Database or File</li><li><strong>connectionString </strong>-Define connection string</li><li><strong>commandText</strong> -Please mention the DML command here targetting NlogDBLog created using DDL commands</li></ul>



<h3 class="wp-block-heading">Loading Configuration</h3>



<p>Please update the Main method for adding the Database logging as shown in below-highlighted code in <em>Program.cs</em></p>



<pre class="wp-block-code"><code>var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();</code></pre>



<p>Below is the complete code base,</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="766" height="404" src="https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_4.jpg" alt="" class="wp-image-2938" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_4.jpg 766w, https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_4-300x158.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_4-50x26.jpg 50w" sizes="(max-width: 766px) 100vw, 766px" /></figure>



<p>Please update HostBuilder as below using <em><strong>UseNLog</strong></em>,</p>



<pre class="wp-block-code"><code>public static IHostBuilder CreateHostBuilder(string&#91;] args) =>
          Host.CreateDefaultBuilder(args)
              .ConfigureWebHostDefaults(webBuilder =>
              {
                  webBuilder.UseStartup&lt;Startup>();
              })
             .ConfigureLogging(logging =>
             {
                 logging.ClearProviders();
                 logging.SetMinimumLevel(LogLevel.Trace);
             })
             .UseNLog();</code></pre>



<p>Let’s do the logging using <strong>ILogger </strong>instance in any part of the code,</p>



<pre class="wp-block-code"><code>&#91;HttpGet("{id}")]
public ActionResult&lt;IEnumerable&lt;string>> Get(int id)
{
    _logger.LogInformation("Start : Getting item details for {ID}", id);
 
    List&lt;string> list = new List&lt;string>();
 
    list.Add("A");
    list.Add("B");
 
    _logger.LogInformation($"Completed : Item details for  {{{string.Join(", ", list)}}}");
 
    return list;
}</code></pre>



<p>Below is how the logs will captured in the NLog <strong>SQL </strong>table,</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="769" height="174" src="https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_5.jpg" alt="" class="wp-image-2939" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_5.jpg 769w, https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_5-300x68.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/03/image_5-50x11.jpg 50w" sizes="(max-width: 769px) 100vw, 769px" /></figure>



<h3 class="wp-block-heading">Adding Database provider</h3>



<p>If not using SQL provider then please use fully qualified name of the provider connection type.</p>



<p><strong>MySQL Client</strong></p>



<pre class="wp-block-preformatted">dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySqlConnector"</pre>



<p><strong>SQL Client</strong></p>



<pre class="wp-block-preformatted">dbProvider="Microsoft.Data.SqlClient.SqlConnection, Microsoft.Data.SqlClient"</pre>



<p><strong>SQLite client</strong></p>



<pre class="wp-block-preformatted">dbProvider="Microsoft.Data.Sqlite.SqliteConnection, Microsoft.Data.Sqlite"</pre>



<h2 class="wp-block-heading">Summary</h2>



<p><strong>NLog </strong>simplifies and helps us enabling logging in a few simple steps and address the Database logging requirements easily. Currently, high-end logging requirements like Database or Files are not yet available through the .NET Core framework and certainly, we need to depend on custom or existing external solutions and <strong>NLog </strong>suffices that requirement easily.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-perform-database-logging-using-nlog-in-asp-net-core/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
