Reading the SQL Server log files using TSQL
One of the issues I have is that the SQL Server Error Log is quite large and it is not always easy to view the contents with the Log File Viewer. In a previous tip "Simple way to find errors in SQL Server error log" you discussed a method of searching the error log using VBScript. Are there any other easy ways to search and find errors in the error log files?SolutionSQL Server 2005 offers an undocumented system stored procedure sp_readerrorlog. This SP allows you to read the contents of the SQL Server error log files directly from a query window and also allows you to search for certain keywords when reading the error file. This is not new to SQL Server 2005, but this tip discusses how this works for SQL Server 2005.
This is a sample of the stored procedure for SQL Server 2005. You will see that when this gets called it calls an extended stored procedure xp_readerrorlog.
CREATE PROC [sys].[sp_readerrorlog]( |
- Value of error log file you want to read: 0 = current, 1 = Archive #1, 2 = Archive #2, etc...
- Log file type: 1 or NULL = error log, 2 = SQL Agent log
- Search string 1: String one you want to search for
- Search string 2: String two you want to search for to further refine the results
Here are a few examples:
Example 1
EXEC sp_readerrorlog 6 |
Example 2
EXEC sp_readerrorlog 6, 1, '2005' |
Example 3
EXEC sp_readerrorlog 6, 1, '2005', 'exec' |
xp_readerrrorlog
Even though sp_readerrolog accepts only 4 parameters, the extended stored procedure accepts at least 7 parameters.
If this extended stored procedure is called directly the parameters are as follows:
- Value of error log file you want to read: 0 = current, 1 = Archive #1, 2 = Archive #2, etc...
- Log file type: 1 or NULL = error log, 2 = SQL Agent log
- Search string 1: String one you want to search for
- Search string 2: String two you want to search for to further refine the results
- Search from start time
- Search to end time
- Sort order for results: N'asc' = ascending, N'desc' = descending
EXEC master.dbo.xp_readerrorlog 6, 1, '2005', 'exec', NULL, NULL, N'desc' EXEC master.dbo.xp_readerrorlog 6, 1, '2005', 'exec', NULL, NULL, N'asc' |
Examples:
Exec sp_readerrorlog
The above command all the contents from current SQL Server errorlog.
Exec sp_readerrorlog 1,1,‘memory’
The above command reads the first SQL Server Archived Error log and searches for returns the result wherever “memory” appears