Technical Article

Archiving SQL Server Error Logs

,

This script creates a stored procedure that archives the sql server error log.  It uses the startup parameters stored in the registry to locate the errorlog.1 file and then copies the errorlog.1 file to errorlog.log.

/*
**  
**  I created this script because SAs will reboot my servers
**  many times when trying to fix a problem.  If the number
**  of reboots exceeds the number of sql error logs you 
**  store then your errorlogs get overwritten.  In my 
**  experience it's after exceeding that point that someone 
**  inevitably asks a question that requires you to have 
**  the now overwritten errorlog.
**  
**  It also seems like you might be able to import the 
**  logs and do some trending on specific errors.
** 
**  After creating usp_ArchiveSQLLog, create a job that 
**  executes the stored procedure when the SQL Server Agent 
**  starts.
**  
*/

CREATE  PROCEDURE usp_ArchiveSQLLog 
AS

declare @LogString nvarchar(255)
declare @Cmd nvarchar(500)
declare @datestring nvarchar(16)
/*Create a datestring to concatinate with the errorlog filename.*/select @datestring = ltrim(rtrim(replace(replace(replace(convert(nvarchar(16), getdate(), 120), '-', ''), ':', ''), ' ', '')))
CREATE TABLE #Reg ( Value nvarchar( 255 ) , Data nvarchar( 255 ) )
/* Create a temp table to store the SQL Server startup registry parameters. */INSERT #Reg
EXEC master..xp_regenumvalues N'HKEY_LOCAL_MACHINE',
N'SOFTWARE\Microsoft\MSSQLServer\MSSQLServer\Parameters'
/* Select the string for the errorlog location. */SELECT @LogString = replace(data, '-e', '') FROM #Reg
WHERE Data LIKE '-e%'
/* Create the DOS command to copy the errorlog.1 file to errorlog<datestring>.log */set @Cmd = 'copy "'+@LogString+'.2" "'+@LogString+@datestring+'.log"'
exec master.dbo.xp_cmdshell @Cmd
drop table #Reg
GO

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating