How to write logs to database using Serilog

9. May 2020

Questions searched on google

Serilog writing to Database


Creating Serilog Table from EF Core


XML Type EF Core


Data Annotation XML type


Adding Serilog in .NET Core 3

 

We will use the approach of Entity Framework Core Generated table for Serilog Logging in Database.

First create a Log Entity class in your Models folder with code below code

 

public class Log
    {
        public int Id { get; set; }
        public string Message { get; set; }
        public string MessageTemplate { get; set; }
        public string Level { get; set; }
        public DateTime TimeStamp { get; set; }
        public string Exception { get; set; }
        [Column(TypeName ="Xml")]
        public string Properties { get; set; }
        public string LogEvent { get; set; }
    }

Now goto your context class file and the following code

public virtual DbSet<Log> Logs { get; set; } 

and add the below line in OnModelCreating method

modelBuilder.Entity<Log>().ToTable("Log");

Now we have defined the details of table which we want entity framework to genereate in database. Open the powershell and run the migrations command as below

dotnet ef migrations add Log --context AppContext

Check the migrations file name <timestamp>_Log.cs with the required changes we need and then update the database

dotnet ef database update --context AppContext

Now check the SQL Server Object Explorer with the updated database . A table exists named Log

So we now have the required table for Serilog to begin logging . Now we will configure the serilog for this . Open nuget package manager console and add the below package in order to enable the Serilog sink for MSSqlServer
Serilog.Sinks.MSSqlServer

Add below package in order to activate the serilog configuration reader feature which will read how to connect to MSSqlServer
Serilog.Settings.Configuration

Install-Package Serilog.Sinks.MSSqlServer
Install-Package Serilog.Settings.Configuration

Now we have the basic packages installed , we will add the appsettings for the serilog to connect to the MSSqlServer
Add the below code to your appsettings.json

{
  "Serilog": {
    "Using": [ "Serilog.Sinks.MSSqlServer" ],
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "MSSqlServer",
        "Args": {
          "connectionString": "Server=(localdb)\\mssqllocaldb;Database=DatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true", // connection String  
          "tableName": "Log" // table name  
        }
      }
    ]
  }
}

We have kept the table name as "Log" same as we have defined in the AppContext class for entity framework core to create in database server.

Now add the following code in your Program.cs

public class Program
    {
        
        public static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .Build();
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)//Serilog.Settings.Configuration
                .WriteTo.Console()
                .CreateLogger();

            try
            {
                Log.Information("Getting the Application Clanstech Application Running... ");
                CreateHostBuilder(args).Build().Run();

            }
            catch(Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly");
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseSerilog()//using Serilog.AspNetCore
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
                
            }).UseDefaultServiceProvider(options => options.ValidateScopes = false);
            
    }

Before using .UseSerilog() method do remember to install the package

Install-Package Serilog.AspNetCore

Now run your application and you will see all the logs populated in your Log Table in database server .

References :

https://www.carlrippon.com/asp-net-core-logging-with-serilog-and-sql-server/

https://www.c-sharpcorner.com/article/file-logging-and-ms-sql-logging-using-serilog-with-asp-net-core-2-0/

https://nblumhardt.com/2019/10/serilog-in-aspnetcore-3/

 

ASP.NET MVC Core, C#, Logging, MSSQL, Serilog , , , , ,

Implicit to Explicit implementations of interface in class for Entity Framework Core Common Columns in table like CreatedOn UpdatedOn DeletedOn IsPublished

1. May 2020

Question

I want to make some properties common to entity classes which can be implemented in class. These properties can be selective in nature means some class has one of them or more of them or none. So in order to do that we need multiple inheritance , which can only be implemented by the use of interfaces.

What I searched on internet :

Why entity framework core is not creating columns for the explicit implementations of interface properties

I have created two interfaces with the their properties

 

public interface IRecordInformation
    {
         public DateTime CreatedOn { get; set; }
         public DateTime ModifiedOn { get; set; }

    }
public interface IPublishInformation
    {
        public bool IsPublished { get; set; }
        
    }

Now suppose that I have created the Entity Class as Service and inherited both the interfaces . I have implemented the properties of interfaces which needs to be done . So I got a system where in I can just inherit the interfaces which I need in any class and the common properties will be forced by compiler with an error if I don’t implement them .

 
public class Service : IRecordInformation, IPublishInformation
    {
        public int ServiceId { get; set; }
        public string Name { get; set; }
        public string FileName { get; set; }
        
        public DateTime CreatedOn { get; set; }
        public  DateTime ModifiedOn { get; set; }
        public bool IsPublished { get; set; }
    }

We have achieved avoiding the mistake of forgetting to include CreatedOn ModifiedOn Properties in any class . Now the question is if I want to remove the modifiedOn property from all the class will removing it from interface will work ? answer is no because as soon as I remove the property from interface the compiler thinks that the modifiedOn property is of Service class’s own property which makes our requirement error prone . Hence , what we can do is use explicit implementation of interface properties in class

This can be done like the below example.

public class Service : IRecordInformation, IPublishInformation
    {
        public int ServiceId { get; set; }
        public string Name { get; set; }
        public string FileName { get; set; }
        
        public DateTime IRecordInformation.CreatedOn { get; set; }
        public  DateTime IRecordInformation.ModifiedOn { get; set; }
        public bool IPublishInformation.IsPublished { get; set; }
    }

Now we have achieved that whenever there is any change in interface the compiler will force us to change the class implementation as well . But the problem arises now is the Entity Framework Core does not processes the explicit implementations of interface into table columns . So we have to make implicit to explicit implementations like below .

public bool IsPublished
        {
            get
            {
                return ((IPublishInformation)this).IsPublished;
            }
            set
            {
                ((IPublishInformation)this).IsPublished = value;
            }

        }

bool IPublishInformation.IsPublished { get; set; }
public DateTime CreatedOn 
   { 
       get 
            {
                ((IRecordInformation)this).CreatedOn;
            }
       set
            {
                 ((IRecordInformation)this).CreatedOn = value; 
            }
   }
public DateTime ModifiedOn
   {
         get
              {
                  return ((IRecordInformation)this).ModifiedOn;
              }
         set
              {
                  ((IRecordInformation)this).ModifiedOn = value;
               }

    }
public DateTime IRecordInformation.CreatedOn { get; set; }
public DateTime IRecordInformation.ModifiedOn { get; set; }

Now entity Framework core sees the CreatedOn ModifiedOn properties and creates the corresponding columns in the table .

Question on stackoverflow also 

https://stackoverflow.com/questions/61422152/when-using-explicit-interface-implementation-in-entity-classes-ef-core-does-no/61537924#61537924

ASP.NET MVC Core, C# , , , , , , , ,

How to Get the Base URL in ASP.NET MVC Core View , ASP.NET MVC Core get website link in View

21. April 2020

Get the Absolute URI from ASP.NET MVC Content or Action.

How to Get the Base URL in ASP.NET MVC Core View ?

ASP.NET MVC Core get website link in View .

 

Answer to above questions when i was trying to find what i actually wanted is below .

@Url.Action(<action>,<controller>,null,Context.Request.Scheme)

You can replace the <action> and <controller> with your values in double quotes if you want to get the exact link of a action method .

It will generate a link like - http://www.clanstech.com/Home/Services

Or you can also ignore <action>, <controller> altogether to get just the base url , website link , domain link on which you are hosting your website application .

Like this @Url.Action(null,null,null,Context.Request.Scheme)

It will generate a link like - http://www.clanstech.com/

ASP.NET MVC, ASP.NET MVC Core, C# , , , , ,

Code for resizing your images before saving them in C#

19. August 2014

Code for resizing your images before saving them in C#

Here is the link to that page http://www.codeproject.com/Tips/552141/Csharp-Image-resize-convert-and-save

C# , ,

Login.DestinationPageUrl does not work for me

4. July 2013

Login.DestinationPageUrl does not work for me

 Whenever i try to login , this control redirects to the page requested on the first place after logging in even though i have mentioned which page to open after user is logged in . Following is the solution to this :

protected void Login1_LoggedIn(object sender, EventArgs e) 

{ 

  Response.Redirect(ResolveClientUrl(Login1.DestinationPageUrl));

}

ASP.NET, C# ,

How can I sort List<T> based on properties of T ?

28. February 2013

A very good answer to this problem is provided on this blog post .

http://stackoverflow.com/questions/605189/how-can-i-sort-listt-based-on-properties-of-t

 

_list.Sort((a,b)=> String.Compare(a.Name,b.Name));

 

_list.Sort((a,b)=> a.SomethingInteger.CompareTo(b.SomethingInteger));

C# ,

StackOverflowException thrown in C#

8. February 2013

I was getting a stackOverFlowException in my program , i found out that i have called my function in its own definition body , actually i had a similar name function in other class and i forgot to call that function with its own instance and hence this exception was thrown . 

C#

How to implement IValueConverter Interface and using it in xaml

7. February 2013

Nice msdn article for this topic :- http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter(v=vs.100).aspx

C#