MT.Extensions.Logging.MsSql 2.1.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package MT.Extensions.Logging.MsSql --version 2.1.0                
NuGet\Install-Package MT.Extensions.Logging.MsSql -Version 2.1.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MT.Extensions.Logging.MsSql" Version="2.1.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add MT.Extensions.Logging.MsSql --version 2.1.0                
#r "nuget: MT.Extensions.Logging.MsSql, 2.1.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install MT.Extensions.Logging.MsSql as a Cake Addin
#addin nuget:?package=MT.Extensions.Logging.MsSql&version=2.1.0

// Install MT.Extensions.Logging.MsSql as a Cake Tool
#tool nuget:?package=MT.Extensions.Logging.MsSql&version=2.1.0                

MT.Extensions.Logging.MsSql

An .net Core Logger Extension that logs to MsSql server using stored procedure. (ELMAH for Asp.Net Core)

An Extension of ILogger to log Data into MsSql DB, This is an alternative for ELMAH in asp.net mvc. currently there is no page to view errors, or error details inside, but anyone can help will be appreciated.

The Default LogLevel for this Extension is Error, (if not specified).

How to Install.

1- Before using this tool, Create a Database, and add Connection string into appsetting.json like below.

{
  "ConnectionStrings": {
    "LoggerConnection" : "Server=(localdb)\\MSSQLLocalDB;Database=Logs;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

2- Execute CreateScript.sql file in database

Update Script:

Not: If you are updating from version 2.0.1 or below, please run update script below:

/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.Logs
	DROP CONSTRAINT DF_Logs_LogId
GO
CREATE TABLE dbo.Tmp_Logs
	(
	TimeUtc datetime NOT NULL,
	LogId uniqueidentifier NOT NULL,
	Application nvarchar(100) NULL,
	Category nvarchar(60) NOT NULL,
	Type nvarchar(100) NOT NULL,
	Source nvarchar(60) NOT NULL,
	FileName nvarchar(400) NOT NULL,
	Message nvarchar(500) NOT NULL,
	[User] nvarchar(50) NOT NULL,
	StatusCode int NOT NULL,
	StackTrace nvarchar(4000) NOT NULL,
	ExceptionDetail ntext NOT NULL
	)  ON [PRIMARY]
	 TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE dbo.Tmp_Logs SET (LOCK_ESCALATION = TABLE)
GO
ALTER TABLE dbo.Tmp_Logs ADD CONSTRAINT
	DF_Logs_LogId DEFAULT (newid()) FOR LogId
GO
IF EXISTS(SELECT * FROM dbo.Logs)
	 EXEC('INSERT INTO dbo.Tmp_Logs (TimeUtc, LogId, Category, Type, Source, FileName, Message, [User], StatusCode, StackTrace, ExceptionDetail)
		SELECT TimeUtc, LogId, Category, Type, Source, FileName, Message, [User], StatusCode, StackTrace, ExceptionDetail FROM dbo.Logs WITH (HOLDLOCK TABLOCKX)')
GO
DROP TABLE dbo.Logs
GO
EXECUTE sp_rename N'dbo.Tmp_Logs', N'Logs', 'OBJECT' 
GO
ALTER TABLE dbo.Logs ADD CONSTRAINT
	PK_Log_ID PRIMARY KEY NONCLUSTERED 
	(
	LogId
	) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

GO
CREATE NONCLUSTERED INDEX IX_TimeUTC ON dbo.Logs
	(
	TimeUtc DESC
	) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
COMMIT
GO

ALTER PROCEDURE [dbo].[spInsertLog]
(
    @TimeUtc DATETIME,
    @LogId UNIQUEIDENTIFIER,
	@Application NVARCHAR(100) = null,
    @Category NVARCHAR(60),
    @Type NVARCHAR(100),
    @Source NVARCHAR(60),
	@FileName NVARCHAR(400),
    @Message NVARCHAR(500),
    @User NVARCHAR(50),
    @ExceptionDetail NTEXT,
    @StatusCode INT,
	@StackTrace NVARCHAR(4000)
)
AS

    SET NOCOUNT ON

    INSERT
    INTO
        [dbo].[Logs]
        (
            [TimeUtc],
            [LogId],
			[Application],
            [Category],            
            [Type],
            [Source],
			[FileName],
            [Message],
            [User],
            [ExceptionDetail],
            [StatusCode],
			[StackTrace]
        )
    VALUES
        (
            @TimeUtc,
            @LogId,
			@Application,
            @Category,            
            @Type,
            @Source,
			@FileName,
            @Message,
            @User,
            @ExceptionDetail,
            @StatusCode,
			@StackTrace
        )
GO

Create Script

Not if this is first time you are installing this nuget package, run below script to create tables and sp.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Logs](
	[TimeUtc] [datetime] NOT NULL,	
	[LogId] [uniqueidentifier] NOT NULL,
	[Application] [nvarchar](100) NULL,
	[Category] [nvarchar](60) NOT NULL,
	[Type] [nvarchar](100) NOT NULL,
	[Source] [nvarchar](60) NOT NULL,
	[FileName] [nvarchar] (400) NOT NULL,
	[Message] [nvarchar](500) NOT NULL,
	[User] [nvarchar](50) NOT NULL,
	[StatusCode] [int] NOT NULL,
	[StackTrace] [nvarchar] (4000) NOT NULL,
	[ExceptionDetail] [ntext] NOT NULL,
 CONSTRAINT [PK_Log_ID] PRIMARY KEY NONCLUSTERED 
(
	[LogId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

/****** Object:  StoredProcedure [dbo].[spInsertLog]  ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[spInsertLog]
(
    @TimeUtc DATETIME,
    @LogId UNIQUEIDENTIFIER,
	@Application NVARCHAR(100) = null,
    @Category NVARCHAR(60),
    @Type NVARCHAR(100),
    @Source NVARCHAR(60),
	@FileName NVARCHAR(400),
    @Message NVARCHAR(500),
    @User NVARCHAR(50),
    @ExceptionDetail NTEXT,
    @StatusCode INT,
	@StackTrace NVARCHAR(4000)
)
AS

    SET NOCOUNT ON

    INSERT
    INTO
        [dbo].[Logs]
        (
            [TimeUtc],
            [LogId],
			[Application],
            [Category],            
            [Type],
            [Source],
			[FileName],
            [Message],
            [User],
            [ExceptionDetail],
            [StatusCode],
			[StackTrace]
        )
    VALUES
        (
            @TimeUtc,
            @LogId,
			@Application,
            @Category,            
            @Type,
            @Source,
			@FileName,
            @Message,
            @User,
            @ExceptionDetail,
            @StatusCode,
			@StackTrace
        )
GO

/****** Object:  Default [DF_Logs_LogId] ******/
ALTER TABLE [dbo].[Logs] ADD  CONSTRAINT [DF_Logs_LogId]  DEFAULT (newid()) FOR [LogId]
GO

3- in Asp.net Core Web Application in startup.cs add following codes: 3-1-

public void ConfigureServices(IServiceCollection services)
{
  // Add framework services.

  // Add This Line To access HttpContext from within the MsSqlLogger to get the user name that gets error
  services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  services.AddMvc();
}

3-2-

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,
            IHttpContextAccessor httpContextAccessor)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    // Add This To Log to MsSql Db
    loggerFactory.AddMsSql(Configuration.GetConnectionString("LoggerConnection"), httpContextAccessor, "SampleApplication");

	// Also you can add as Provider as below:
	//loggerFactory.AddProvider(new MsSqlLoggerProvider((_, LogLevel) => LogLevel >= LogLevel.Trace,
    //     Configuration.GetConnectionString("LoggerConnection"), null,"SampleApplication"));            

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Using in Asp.net Core Web Application Targetting .NetFramework

To Use in Asp.Net Web Application targetting .NetFramework you should also add following nuget packages manually to your project.

  • System.Security.Claims (4.3) from <a href='https://www.nuget.org/packages/System.Security.Claims/'>NUGET</a>

  • System.Diagnostics.StackTrace (4.3) from <a href='https://www.nuget.org/packages/System.Diagnostics.StackTrace'>NUGET</a>

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.2.2 18,715 3/4/2021
2.2.1 578 11/24/2020
2.2.0 494 9/22/2020
2.1.1 677 10/17/2019
2.1.0 571 10/16/2019
2.0.1 1,662 7/13/2018
2.0.0 1,065 12/22/2017
1.0.0 1,106 10/3/2017

Added ApplicationName column and removed Sequence (useless), The Application name can be used to specify witch application is logging, and usefull when multiple application uses the same database. also some columns order changed, TimeUtc moved to first column because everyone wnat to get last data in sql management studio, uses Order by 1 desc and it would be solved unordered list of logs :)
Added an update script to update from previous database scheme to current.