How many files are in your SQL Error log directory?

How many files are in your SQL Error log directory?
Download PDF

I was investigating a slow sever recently and discovered almost a million files in the sql server error log directory. This contained job history and backup logs for many years. The error log directory is not a location that I normally check, so I created a script to quickly and easily check how many files are in a SQL Server error log directory

SET NOCOUNT ON;

-- first get the path to the error log directory
DECLARE @errorLogPath as NVARCHAR(4000);
SELECT @errorLogPath = 
       cast(SERVERPROPERTY('ErrorLogFileName') AS NVARCHAR(4000));

SET @errorLogPath = REPLACE(@errorLogPath, '\ERRORLOG', '');


-- now get a list of files -- this may take a while
CREATE TABLE #DirectoryTree (
      subdirectory nvarchar(512),
      depth int,
      isfile bit);

INSERT INTO #DirectoryTree (subdirectory,depth,isfile)
EXEC master.sys.xp_dirtree @errorLogPath,1,1;


-- get a count of files in the error log directory
DECLARE @fileCount AS INTEGER = 0;
SELECT @fileCount = COUNT(*) FROM #DirectoryTree
WHERE isfile = 1;


PRINT 'Error log directory ' + @errorLogPath + ' contains ' +
       cast(@fileCount as varchar(100)) + ' files.';

DROP TABLE #DirectoryTree;

It is good to know if you have a ton of files in that directory. This script was tested on SQL Server 2005, 2008, 2008R2, 2012, 2014, 2016, 2017 and 2019.

 

More from Stedman Solutions:

SteveStedman5
Steve and the team at Stedman Solutions are here for all your SQL Server needs.
Contact us today for your free 30 minute consultation..
We are ready to help!

Leave a Reply

Your email address will not be published. Required fields are marked *

*