Paul
Paul

Reputation: 777

Notify me when log table contains error

I am using log4net and would like to set up a process to notify me when a record is written to the Log table. I would want it to run every hour or so. I would probably use this query:

SELECT * FROM Log 
WHERE Level = 'ERROR' 
AND Datediff(hh,[Date],getdate()) < 1 

Upvotes: 0

Views: 64

Answers (1)

Aaron Bertrand
Aaron Bertrand

Reputation: 280645

You could use a SQL Server Agent job (I assume you're not using SQL Server Express). You will need to set up Database Mail. Then you can simply schedule a job that runs every hour that says:

IF EXISTS 
(
  SELECT 1 FROM dbo.[Log] 
    WHERE Level = 'ERROR' 
    AND [Date] >= DATEADD(HOUR, -1, GETDATE())
)
BEGIN
    EXEC msdb.dbo.sp_send_dbmail ...
END

Note that this science isn't exact... if the job starts a few seconds after 8:00 it might miss an error that occurred at 7:00:01, and if you add a few seconds' buffer, you might double-report an error that happened at 6:59:59.997. What you can consider doing to alleviate this is to store the last error you recorded somewhere, then you can add an additional WHERE clause:

AND [Date] > (SELECT MAX(LastError) FROM dbo.LastErrorLog)

Upvotes: 3

Related Questions