How to Keep ELMAH_Error Table Rows Getting Too Big by Automatically Deleting Rows

Prevent Log errors from getting Too Big in ELMAH_Error SQL Server Table
by

I recently ran into an issue with the ELMAH Error logger Table getting way TOO Big in my SQL Server database.  The table row size in the ELMAH_Error table had over 200,000 rows. This was way more than I ever needed to look at, and was causing other issues with my SQL Server database.  So I needed to change the ELMAH_LogERROR stored procedure so that it would automatically delete error log data when the TOTAL Row Count was over 10000 rows, while still keeping the most recent 10000 records for me to be able to review the error messagees. You could very easily change this to 1,000 or some other number depending on how many rows you need to look at in your ELMAH_Error table. NOTE: I'm using ELMAH version 1.2.2 in the example below.

Here's the ELMAH_LogError stored procedure code, that will automatically delete records from the ELMAH_Error table when the row size is over 10,000 rows:

ALTER PROCEDURE [dbo].[ELMAH_LogError]
(
    @ErrorId UNIQUEIDENTIFIER,
    @Application NVARCHAR(60),
    @Host NVARCHAR(30),
    @Type NVARCHAR(100),
    @Source NVARCHAR(60),
    @Message NVARCHAR(500),
    @User NVARCHAR(50),
    @AllXml NTEXT,
    @StatusCode INT,
    @TimeUtc DATETIME
)
AS

    SET NOCOUNT ON

    INSERT
    INTO
        [dbo].[ELMAH_Error]
        (
            [ErrorId],
            [Application],
            [Host],
            [Type],
            [Source],
            [Message],
            [User],
            [AllXml],
            [StatusCode],
            [TimeUtc]
        )
    VALUES
        (
            @ErrorId,
            @Application,
            @Host,
            @Type,
            @Source,
            @Message,
            @User,
            @AllXml,
            @StatusCode,
            @TimeUtc
        )



		DECLARE  @TotalRowCount INT
		SELECT @TotalRowCount = (SELECT COUNT(ErrorId) FROM [dbo].[ELMAH_Error])

		/* Automatically delete error log data when TOTAL Row Count is over 10000 */
		IF @TotalRowCount is not null AND @TotalRowCount > 10000
		BEGIN

			-- DELETE all ROWS except the most recent 10000
			-- numbered rows
			WITH goners AS (
				SELECT ROW_NUMBER() OVER(ORDER BY [TimeUtc] DESC) AS rn, [ErrorId]
				FROM [dbo].[ELMAH_Error]
			)
			DELETE FROM goners
			WHERE rn > 10000

		END

That's it, hope that helps!

 


0
0

Add your comment

by Anonymous - Already have an account? Login now!
Your Name:  

Comment:  
Enter the text you see in the image below
What do you see?
Can't read the image? View a new one.
Your comment will appear after being approved.

Related Posts


I recently ran into the following error while trying to get Elmah to work / complie with my Web Application Project in Visual Studio 2010: Could not load file or assembly 'file:///C:\Users\DOUGDELL2\Documents\Visual Studio...  more »