I've been asked to generate an entry in the event viewer, as opposed to an e-mail notification, whenever there is an autogrowth event. The problem I'm having is getting data from the default trace parameters into the message part of the event viewer.
To generate the event viewer entry, I'm using:
EXEC xp_logevent 60001, @msg, error
If I try to set @msg
to say EventName
I get an error message:
Invalid colmun name 'EventName'
Right now an entry is created in the event viewer, but it doesn't state where the autogrowth happened, how much, etc. Without that data, someone who gets the alerts via azure log analytics will have to log in to the server to check it out every time. Here is my current query:
DECLARE @tracepath nvarchar(500)
SELECT @tracepath = path FROM sys.traces WHERE is_default = 1
--The trace automatically finds _n files, trim off the _nnn portion of the file name.
select @tracepath = substring(@tracepath, 0, charindex('\log_', @tracepath,0)+4) + '.trc'
print @tracepath
SELECT
DBName = g.DatabaseName
, DBFileName = mf.physical_name
, FileType = CASE mf.type WHEN 0 THEN 'Row' WHEN 1 THEN 'Log' WHEN 2 THEN 'FILESTREAM' WHEN 4 THEN 'Full-text' END
, EventName = te.name
, EventGrowthMB = convert(decimal(19,2),g.IntegerData*8/1024.) -- Number of 8-kilobyte (KB) pages by which the file increased.
, EventTime = g.StartTime
, EventDurationSec = convert(decimal(19,2),g.Duration/1000./1000.) -- Length of time (in milliseconds) necessary to extend the file.
, CurrentAutoGrowthSet= CASE
WHEN mf.is_percent_growth = 1
THEN CONVERT(char(2), mf.growth) + '%'
ELSE CONVERT(varchar(30), convert(decimal(19,2), mf.growth*8./1024.)) + 'MB'
END
, CurrentFileSizeMB = convert(decimal(19,2),mf.size* 8./1024.)
, @tracepath
FROM fn_trace_gettable(@tracepath, default) g
cross apply sys.trace_events te
inner join sys.master_files mf
on mf.database_id = g.DatabaseID
and g.FileName = mf.name
WHERE g.eventclass = te.trace_event_id AND DATEDIFF(mi, g.StartTime, getdate()) < 360
and te.name in ('Data File Auto Grow','Log File Auto Grow')
order by StartTime desc
IF @@ROWCOUNT > 0
BEGIN
PRINT ERROR_Message()
DECLARE @msg VARCHAR(100)
SELECT @msg = ERROR_MESSAGE()
EXEC xp_logevent 60001, autogrowthEvent, error
END