<?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>hosting &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/hosting/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Thu, 03 Dec 2020 04:14:50 +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>hosting &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Use Serilog ASP.NET Core to SQL Server Database</title>
		<link>https://topreviewhostingasp.net/use-serilog-asp-net-core-to-sql-server-database/</link>
					<comments>https://topreviewhostingasp.net/use-serilog-asp-net-core-to-sql-server-database/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Thu, 03 Dec 2020 04:03:24 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp.net core hosting]]></category>
		<category><![CDATA[asp.net core tips]]></category>
		<category><![CDATA[asp.net core tutorial]]></category>
		<category><![CDATA[hosting]]></category>
		<category><![CDATA[serilog asp net core]]></category>
		<category><![CDATA[sql server]]></category>
		<category><![CDATA[web host asp net core]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=2813</guid>

					<description><![CDATA[Logging is an essential feature for any application, as it is necessary for detecting, investigating, and debugging issues. Serilog is a third-party, open source library that allows .NET developers to log structured data to the console, to files, and to several other kinds of data stores.  This article discusses how we can use Serilog to log structured [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>Logging is an essential feature for any application, as it is necessary for detecting, investigating, and debugging issues. <a href="https://serilog.net/">Serilog</a> is a third-party, open source library that allows .NET developers to log structured data to the console, to files, and to several other kinds of data stores. </p>



<p>This article discusses how we can use Serilog to log structured data to a SQL Server database. To work with the code examples provided in this article, you should have Visual Studio 2019 installed in your system.</p>



<h2 class="wp-block-heading">Create Your First ASP.NET Core 3.0 Project</h2>



<p>Make sure you create your ASP.NET Core project in Visual Studio. We assume that you have installed Visual Studio on your computer.</p>



<h2 class="wp-block-heading">Install the NuGet packages for Serilog</h2>



<p>To work with Serilog, you should install the Serilog packages from NuGet. You can do this either via the NuGet package manager inside the Visual Studio 2019 IDE, or by executing the following commands at the NuGet package manager console:</p>



<pre class="wp-block-code"><code>Install-Package Serilog
Install-Package Serilog.AspNetCore
Install-Package Serilog.Sinks.MSSqlServer
Install-Package Serilog.Settings.Configuration</code></pre>



<h2 class="wp-block-heading">Initialize Serilog in Program.cs in ASP.NET Core</h2>



<p>The following code snippet illustrates how you can plug Serilog into ASP.NET Core. Note how the UseSerilog() extension method has been used to set Serilog as the logging provider.</p>



<pre class="wp-block-code"><code>public static IWebHost BuildWebHost(string[] args) =&gt;
            WebHost.CreateDefaultBuilder(args)
                   .UseStartup&lt;Startup&gt;()
                   .UseSerilog()
                   .Build();</code></pre>



<h2 class="wp-block-heading">Build an example web host in ASP.NET Core</h2>



<p>Naturally, we’ll need an application to illustrate the use of Serilog. Here is the complete source code of the Program class for our example app. Note how we’ve configured and built the web host.</p>



<pre class="wp-block-code"><code>    public class Program
    {
        public static void Main(string[] args)
        {
            IConfigurationRoot configuration = new
            ConfigurationBuilder().AddJsonFile("appsettings.json",
            optional: false, reloadOnChange: true).Build();
            Log.Logger = new LoggerConfiguration().ReadFrom.Configuration
            (configuration).CreateLogger();
            BuildWebHost(args).Run();
        }
        public static IWebHost BuildWebHost(string[] args) =&gt;
            WebHost.CreateDefaultBuilder(args)
                .UseStartup&lt;Startup&gt;()
                .UseSerilog()
                .Build();
    }</code></pre>



<h2 class="wp-block-heading">Configure database connection settings in ASP.NET Core</h2>



<p>When you create a new ASP.NET Core project in Visual Studio, the appsettings.json file is created by default. Here is where you can specify the database connection string and other configuration information. Open the appsettings.json file from the project we created earlier and enter the following information:</p>



<pre class="wp-block-code"><code>{
  "Serilog": {
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Data Source=LAPTOP-ULJMOJQ5;Initial
           Catalog=Research;    
     User Id=joydip; Password=sa123#;",
          "tableName": "Log",
          "autoCreateSqlTable": true
        }
      }
    ]
  }
}</code></pre>



<h2 class="wp-block-heading">Create a database table to log data in SQL Server</h2>



<p>You might want to create the log table yourself as well. Below is the script you can use to create a log table in the SQL Server database.</p>



<pre class="wp-block-code"><code>CREATE TABLE [Log] (
   [Id] int IDENTITY(1,1) NOT NULL,
   [Message] nvarchar(max) NULL,
   [MessageTemplate] nvarchar(max) NULL,
   [Level] nvarchar(max) NULL,
   [TimeStamp] datetimeoffset(7) NOT NULL,
   [Exception] nvarchar(max) NULL,
   [Properties] nvarchar(max) NULL
   CONSTRAINT [PK_Log]
     PRIMARY KEY CLUSTERED ([Id] ASC)
)</code></pre>



<p>When you run the application, a new table named Log will be created and the ASP.NET Core startup events will be logged there. Figure 1 below shows the data that has been logged inside the Log table.</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="1024" height="447" class="wp-image-2816" src="https://topreviewhostingasp.net/wp-content/uploads/2020/12/image_1-1024x447.jpg" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2020/12/image_1-1024x447.jpg 1024w, https://topreviewhostingasp.net/wp-content/uploads/2020/12/image_1-300x131.jpg 300w, https://topreviewhostingasp.net/wp-content/uploads/2020/12/image_1-768x335.jpg 768w, https://topreviewhostingasp.net/wp-content/uploads/2020/12/image_1-50x22.jpg 50w, https://topreviewhostingasp.net/wp-content/uploads/2020/12/image_1.jpg 1200w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>



<h2 class="wp-block-heading">Log data in action methods in ASP.NET Core</h2>



<p>You can leverage dependency injection to inject a logger instance in your controller as shown in the code snippet below:</p>



<pre class="wp-block-code"><code>public class DefaultController : Controller
{
   private readonly ILogger&lt;DefaultController&gt; _logger;
   public DefaultController(ILogger&lt;DefaultController&gt; logger)
   {
      _logger = logger;
   }
}</code></pre>



<p>The following code snippet illustrates how you can take advantage of Serilog in your controller’s action methods to log data.</p>



<pre class="wp-block-code"><code>public class DefaultController : Controller
    {
        private readonly ILogger&lt;DefaultController&gt; _logger;
        public DefaultController(ILogger&lt;DefaultController&gt; logger)
        {
            _logger = logger;
        }
        public IActionResult Index()
        {
            _logger.LogInformation("Hello World");
            return View();
        }
    }</code></pre>



<p>Although independent of .NET Core, Serilog plugs into the ASP.NET Core ecosystem nicely, making structured logging easy and convenient. Serilog also takes advantage of <a href="https://github.com/serilog/serilog/wiki/Provided-Sinks">dozens of sinks</a> to send the logs to many different logging targets ranging from text files to databases to hosting providers. I will post other interesting post in next post.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/use-serilog-asp-net-core-to-sql-server-database/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
