Repository navigation
Expand file tree
/
Copy pathsp_LogHunter.sql
More file actions
994 lines (907 loc) · 35.6 KB
/
Copy pathsp_LogHunter.sql
File metadata and controls
994 lines (907 loc) · 35.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
SET ANSI_NULLS ON;
SET ANSI_PADDING ON;
SET ANSI_WARNINGS ON;
SET ARITHABORT ON;
SET CONCAT_NULL_YIELDS_NULL ON;
SET QUOTED_IDENTIFIER ON;
SET NUMERIC_ROUNDABORT OFF;
SET IMPLICIT_TRANSACTIONS OFF;
SET STATISTICS TIME, IO OFF;
GO
/*
██╗ ██████╗ ██████╗
██║ ██╔═══██╗██╔════╝
██║ ██║ ██║██║ ███╗
██║ ██║ ██║██║ ██║
███████╗╚██████╔╝╚██████╔╝
╚══════╝ ╚═════╝ ╚═════╝
██╗ ██╗██╗ ██╗███╗ ██╗████████╗███████╗██████╗
██║ ██║██║ ██║████╗ ██║╚══██╔══╝██╔════╝██╔══██╗
███████║██║ ██║██╔██╗ ██║ ██║ █████╗ ██████╔╝
██╔══██║██║ ██║██║╚██╗██║ ██║ ██╔══╝ ██╔══██╗
██║ ██║╚██████╔╝██║ ╚████║ ██║ ███████╗██║ ██║
╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝
Copyright 2026 Darling Data, LLC
https://www.erikdarling.com/
For usage and licensing details, run:
EXECUTE sp_LogHunter
@help = 1;
For working through errors:
EXECUTE sp_LogHunter
@debug = 1;
For support, head over to GitHub:
https://code.erikdarling.com
EXECUTE sp_LogHunter;
*/
IF OBJECT_ID(N'dbo.sp_LogHunter', N'P') IS NULL
BEGIN
EXECUTE (N'CREATE PROCEDURE dbo.sp_LogHunter AS RETURN 138;');
END;
GO
ALTER PROCEDURE
dbo.sp_LogHunter
(
@days_back integer = -7, /*How many days back you want to look in the error logs*/
@start_date datetime = NULL, /*If you want to search a specific time frame*/
@end_date datetime = NULL, /*If you want to search a specific time frame*/
@custom_message nvarchar(4000) = NULL, /*If there's something you specifically want to search for*/
@custom_message_only bit = 0, /*If you only want to search for this specific thing*/
@first_log_only bit = 0, /*If you only want to search the first log file*/
@language_id integer = 1033, /*If you want to use a language other than English*/
@help bit = 0, /*Get help*/
@debug bit = 0, /*Prints messages and selects from temp tables*/
@version varchar(30) = NULL OUTPUT,
@version_date datetime = NULL OUTPUT
)
WITH RECOMPILE
AS
SET STATISTICS XML OFF;
SET NOCOUNT ON;
SET XACT_ABORT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
SET DATEFORMAT MDY;
BEGIN
SELECT
@version = '3.11',
@version_date = '20261101';
IF @help = 1
BEGIN
SELECT
introduction =
'hi, i''m sp_LogHunter!' UNION ALL
SELECT 'you can use me to look through your error logs for bad stuff' UNION ALL
SELECT 'all scripts and documentation are available here: https://code.erikdarling.com' UNION ALL
SELECT 'from your loving sql server consultant, erik darling: https://erikdarling.com';
SELECT
parameter_name =
ap.name,
data_type = t.name,
description =
CASE ap.name
WHEN N'@days_back' THEN 'how many days back you want to search the logs'
WHEN N'@start_date' THEN 'if you want to search a specific time frame'
WHEN N'@end_date' THEN 'if you want to search a specific time frame'
WHEN N'@custom_message' THEN 'if you want to search for a custom string'
WHEN N'@custom_message_only' THEN 'only search for the custom string'
WHEN N'@first_log_only' THEN 'only search through the first error log'
WHEN N'@language_id' THEN 'does not translate the search strings; they are English literals. Use @custom_message on non-English servers'
WHEN N'@help' THEN 'how you got here'
WHEN N'@debug' THEN 'dumps raw temp table contents'
WHEN N'@version' THEN 'OUTPUT; for support'
WHEN N'@version_date' THEN 'OUTPUT; for support'
END,
valid_inputs =
CASE ap.name
WHEN N'@days_back' THEN 'an integer; will be converted to a negative number automatically'
WHEN N'@start_date' THEN 'a datetime value'
WHEN N'@end_date' THEN 'a datetime value'
WHEN N'@custom_message' THEN 'something specific you want to search for. no wildcards or substitutions.'
WHEN N'@custom_message_only' THEN 'NULL, 0, 1'
WHEN N'@first_log_only' THEN 'NULL, 0, 1'
WHEN N'@language_id' THEN '1033; anything else only triggers a warning, because the search strings stay English'
WHEN N'@help' THEN 'NULL, 0, 1'
WHEN N'@debug' THEN 'NULL, 0, 1'
WHEN N'@version' THEN 'OUTPUT; for support'
WHEN N'@version_date' THEN 'OUTPUT; for support'
END,
defaults =
CASE ap.name
WHEN N'@days_back' THEN '-7'
WHEN N'@start_date' THEN 'NULL'
WHEN N'@end_date' THEN 'NULL'
WHEN N'@custom_message' THEN 'NULL'
WHEN N'@custom_message_only' THEN '0'
WHEN N'@first_log_only' THEN '0'
WHEN N'@language_id' THEN '1033'
WHEN N'@help' THEN '0'
WHEN N'@debug' THEN '0'
WHEN N'@version' THEN 'none; OUTPUT'
WHEN N'@version_date' THEN 'none; OUTPUT'
END
FROM sys.all_parameters AS ap
JOIN sys.all_objects AS o
ON ap.object_id = o.object_id
JOIN sys.types AS t
ON ap.system_type_id = t.system_type_id
AND ap.user_type_id = t.user_type_id
WHERE o.name = N'sp_LogHunter'
ORDER BY
ap.parameter_id
OPTION(RECOMPILE);
SELECT
mit_license_yo = 'i am MIT licensed, so like, do whatever'
UNION ALL
SELECT
mit_license_yo = 'see printed messages for full license';
RAISERROR('
MIT License
Copyright 2026 Darling Data, LLC
https://www.erikdarling.com/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
', 0, 1) WITH NOWAIT;
RETURN;
END;
/*
Don't test for sysadmin here. An account can hold EXECUTE on
xp_readerrorlog without being one, and IS_SRVROLEMEMBER answers
no while the procedure runs fine. Ask about the permission we
actually need instead.
*/
IF
(
SELECT
can_read =
ISNULL
(
HAS_PERMS_BY_NAME
(
N'master.dbo.xp_readerrorlog',
N'OBJECT',
N'EXECUTE'
),
0
)
) = 0
AND OBJECT_ID(N'rdsadmin.dbo.rds_read_error_log', N'P') IS NULL
BEGIN
RAISERROR(N'Current user does not have EXECUTE permission on xp_readerrorlog, so we can''t read the error log', 11, 1) WITH NOWAIT;
RETURN;
END;
/*Check if we're unfortunate*/
IF
(
SELECT
CONVERT
(
integer,
SERVERPROPERTY('EngineEdition')
)
) = 5
BEGIN
RAISERROR(N'This will not run on Azure SQL DB because it''s horrible.', 11, 1) WITH NOWAIT;
RETURN;
END;
/*Validate the language id*/
IF NOT EXISTS
(
SELECT
1/0
FROM sys.messages AS m
WHERE m.language_id = @language_id
)
BEGIN
RAISERROR(N'%i is not a valid language_id in sys.messages.', 11, 1, @language_id) WITH NOWAIT;
RETURN;
END;
/*
Say so, rather than pretending. @language_id is validated and then
never used: every search string below is an English literal matched
against the error log's raw text, so pointing this at a non-English
server finds nothing and says nothing about why. Warn instead of
quietly handing back an empty result set that reads like good news.
*/
IF @language_id <> 1033
BEGIN
RAISERROR(N'The search strings are English literals, so @language_id = %i will not translate them. Expect few or no results on a non-English server; use @custom_message to search in your own language.', 10, 1, @language_id) WITH NOWAIT;
END;
/*Fix days back a little bit*/
IF @days_back = 0
BEGIN
SELECT
@days_back = -1;
END;
IF @days_back > 0
BEGIN
SELECT
@days_back *= -1;
END;
/*
A NULL @days_back with no date range is fatal, and silently so: it
makes DATEADD return NULL, which makes every generated command NULL,
and sys.sp_executesql runs a NULL batch as a no-op. The procedure
reads nothing, finds nothing, and reports a clean bill of health on a
server that may be on fire. Put it back on the documented default.
*/
IF @days_back IS NULL
AND @start_date IS NULL
AND @end_date IS NULL
BEGIN
SELECT
@days_back = -7;
END;
/*
Clamp before DATEADD sees it. An absurd @days_back (a caller reaching
for "everything") overflows the datetime range and kills the run with
an arithmetic error instead of just searching every log we have.
*/
IF @days_back < -36500
BEGIN
SELECT
@days_back = -36500;
END;
/*Fix custom message only if NULL*/
IF @custom_message_only IS NULL
BEGIN
SELECT
@custom_message_only = 0;
END;
/*
@custom_message_only = 1 means "skip the canned search strings and
look only for the user-supplied @custom_message". Without a message
to search for, every insert branch below would skip (the custom
insert is gated on @custom_message LIKE N'_%', which is NULL/false
for NULL or empty input), leaving #search empty and the whole
outer loop a no-op. Reject the combination up front.
*/
IF @custom_message_only = 1
AND (@custom_message IS NULL OR LEN(@custom_message) = 0)
BEGIN
RAISERROR(N'@custom_message_only = 1 requires a non-empty @custom_message. Provide a search string or set @custom_message_only = 0.', 11, 1) WITH NOWAIT;
RETURN;
END;
/*Fix @end_date*/
IF @start_date IS NOT NULL
AND @end_date IS NULL
BEGIN
SELECT
@end_date = SYSDATETIME();
END;
/*Fix @start_date*/
IF @start_date IS NULL
AND @end_date IS NOT NULL
BEGIN
SELECT
@start_date = DATEADD(DAY, -7, @end_date);
END;
/*
Reject a reversed date range up front. Without this, xp_readerrorlog
silently returns zero rows for a start date after the end date - the
exact "looks like a clean bill of health but never actually searched"
failure mode this proc's own comments guard against everywhere else.
*/
IF @start_date IS NOT NULL
AND @end_date IS NOT NULL
AND @start_date > @end_date
BEGIN
RAISERROR(N'@start_date must be earlier than @end_date.', 11, 1) WITH NOWAIT;
RETURN;
END;
/*
Retire @days_back once we are in date-range mode, and do it HERE —
after the two fixups above, not before them.
One supplied date is enough to be in date-range mode, because a
caller who supplies only one gets the other filled in just above.
If @days_back survived at its -7 default past this point, the log
file pruner below would delete every archive older than a week — so
searching for an incident from three months ago would quietly throw
away the only file that contained it and return nothing.
*/
IF @days_back IS NOT NULL
AND
(
@start_date IS NOT NULL
OR @end_date IS NOT NULL
)
BEGIN
SELECT
@days_back = NULL;
END;
/*Debuggo*/
IF @debug = 1
BEGIN
SELECT
days_back = @days_back,
start_date = @start_date,
end_date = @end_date;
END;
/*variables for the variable gods*/
DECLARE
@c nvarchar(4000) /*holds the command to execute*/,
@l_log integer = 0 /*low log file id*/,
@h_log integer = 0 /*high log file id*/,
@t_searches bigint = 0 /*total number of searches to run*/,
@l_count integer = 1 /*loop count*/,
@is_rds bit =
CASE
WHEN OBJECT_ID(N'rdsadmin.dbo.rds_read_error_log', N'P') IS NOT NULL
THEN 1
ELSE 0
END;
/*temp tables for holding temporary things*/
CREATE TABLE
#error_log
(
log_date datetime,
process_info nvarchar(100),
text nvarchar(4000)
);
CREATE TABLE
#enum
(
archive integer
PRIMARY KEY CLUSTERED,
/*
datetime, not date. sp_enumerrorlogs reports each archive's last
write with a time component; truncating it to midnight made an
archive that ended this afternoon compare as if it had ended at
00:00, so the window bound below could rule out a file that
actually reaches into the window.
*/
log_date datetime,
log_size bigint
);
CREATE TABLE
#search
(
id integer
IDENTITY
PRIMARY KEY CLUSTERED,
/*
Every argument below is emitted as an N-prefixed single-quoted
literal: N'like this'. Both halves of that matter.
NOT double quotes: under QUOTED_IDENTIFIER ON a double-quoted argument
parses as an IDENTIFIER, and SQL Server caps identifiers at 128
characters - so a @custom_message longer than that failed with
"Msg 103 ... The identifier that starts with ... is too long", was
swallowed by the CATCH below into #errors, and handed the caller an
empty result set that reads exactly like a clean bill of health.
NOT a bare single-quoted literal either: xp_readerrorlog is an
extended stored procedure and will not implicitly convert, so a
varchar argument fails with "Msg 22004 ... Invalid Parameter Type" -
at severity 12, quiet enough to look like simply finding nothing.
Double quotes happened to satisfy this because quoted identifiers are
inherently Unicode; N'...' satisfies it deliberately, and without the
length limit.
The wrapping reads awkwardly because a literal quote must be doubled:
N'N''' opens the argument (emitting N') and N'''' closes it
(emitting ').
*/
search_string nvarchar(4000) DEFAULT N'N''''',
days_back nvarchar(30) NULL,
start_date nvarchar(30) NULL,
end_date nvarchar(30) NULL,
/*
nvarchar(12), not 10: the stored value is N'20260720' - eleven
characters counting the N prefix and quotes. Anything narrower
truncates it into an unterminated literal that breaks every
generated command.
*/
[current_date] nvarchar(12)
DEFAULT N'N''' + CONVERT(nvarchar(10), DATEADD(DAY, 1, SYSDATETIME()), 112) + N'''',
search_order nvarchar(10)
DEFAULT N'N''DESC''',
command AS
CONVERT
(
nvarchar(4000),
N'EXECUTE master.dbo.xp_readerrorlog [@@@], 1, '
+ search_string
+ N', '
/*
NULL, not " ". xp_readerrorlog ANDs its second search
string with the first, so passing a literal space quietly
required every matched line to contain one - a filter
nobody asked for, applied to every search including
@custom_message.
*/
+ N'NULL'
+ N', '
+ ISNULL(start_date, days_back)
+ N', '
+ ISNULL(end_date, [current_date])
+ N', '
+ search_order
+ N';'
) PERSISTED
);
CREATE TABLE
#errors
(
id integer
PRIMARY KEY CLUSTERED
IDENTITY,
command nvarchar(4000) NOT NULL,
error_message nvarchar(4000) NULL
);
/*get all the error logs*/
BEGIN TRY
INSERT
#enum
(
archive,
log_date,
log_size
)
EXECUTE sys.sp_enumerrorlogs;
END TRY
BEGIN CATCH
/*
27219: sp_enumerrorlogs needs securityadmin, which EXECUTE on
xp_readerrorlog does not imply, and no GRANT substitutes for
(it checks the role itself). Read the current log rather than
failing outright, since xp_readerrorlog can do that much.
*/
IF ERROR_NUMBER() = 27219
BEGIN
INSERT
#enum
(
archive,
log_date,
log_size
)
VALUES
(
0,
SYSDATETIME(),
0
);
RAISERROR(N'Not a member of securityadmin, so archived error logs cannot be enumerated. Reading the current log only.', 0, 1) WITH NOWAIT;
END
ELSE
BEGIN
;THROW;
END;
END CATCH;
IF @debug = 1 BEGIN SELECT table_name = '#enum before delete', e.* FROM #enum AS e; END;
/*filter out log files we won't use, if @days_back is set*/
IF @days_back IS NOT NULL
BEGIN
DELETE
e WITH(TABLOCKX)
FROM #enum AS e
/*
The one-minute grace is not slop. sp_enumerrorlogs reports each
archive's last write truncated to the MINUTE, and the file's real
final entry lands somewhere in the following 59 seconds - so the
reported stamp always understates when the file actually ends.
Comparing it exactly prunes archives that really do reach into
the window. Since enum <= true_end < enum + 60s, one minute is
exactly enough.
*/
WHERE DATEADD(MINUTE, 1, e.log_date) < DATEADD(DAY, @days_back, SYSDATETIME())
AND e.archive > 0
OPTION(RECOMPILE);
END;
/*
Filter out log files we won't use, if @start_date and @end_date are set.
Only the START of the window can rule a log file out, and that is the
whole subtlety here. sp_enumerrorlogs reports each archive's LAST
write, not its first, so a file stamped "March 10" holds entries
reaching back to whenever the previous archive ended. Excluding
anything stamped AFTER @end_date would throw away precisely the file
that straddles the end of the window, i.e. the one most likely to
contain the incident being investigated.
A file whose last write predates the window truly cannot contain it,
so that is the only safe exclusion. Keeping the newer files costs a
little extra reading and nothing else: xp_readerrorlog filters by
date again on the way out, so no out-of-window rows survive.
*/
IF @start_date IS NOT NULL
AND @end_date IS NOT NULL
BEGIN
DELETE
e WITH(TABLOCKX)
FROM #enum AS e
/*
A file's last write is where it ENDS; where it STARTS is the last
write of the archive before it (the one rotated out to make room).
Archives count upward into the past, so that is the next-higher
number. The oldest file has no predecessor and reaches back
indefinitely, which a NULL here handles by never matching.
*/
OUTER APPLY
(
SELECT TOP (1)
starts_at = e2.log_date
FROM #enum AS e2
WHERE e2.archive > e.archive
ORDER BY
e2.archive
) AS prior
WHERE e.archive > 0
AND
(
/*
Ended before we started looking. The +1 minute is the same
truncation grace as above: sp_enumerrorlogs rounds each
archive's last write DOWN to the minute.
*/
DATEADD(MINUTE, 1, e.log_date) < @start_date
/*Or did not begin until after we stopped*/
OR prior.starts_at > @end_date
)
OPTION(RECOMPILE);
END;
/*
Maybe you only want the first one anyway. Archive 0 IS the current
log, so "archive > 0" is the predicate that keeps exactly one file.
*/
IF @first_log_only = 1
BEGIN
DELETE
e WITH(TABLOCKX)
FROM #enum AS e
WHERE e.archive > 0
OPTION(RECOMPILE);
END;
IF @debug = 1 BEGIN SELECT table_name = '#enum after delete', e.* FROM #enum AS e; END;
/*insert some canary values for things that we should always hit. look a little further back for these.*/
INSERT
#search
(
search_string,
days_back,
start_date,
end_date
)
SELECT
x.search_string,
c.days_back,
c.start_date,
c.end_date
FROM
(
VALUES
(N'N''Microsoft SQL Server'''),
(N'N''detected'''),
(N'N''SQL Server has encountered'''),
(N'N''Warning: Enterprise Server/CAL license used for this instance''')
) AS x (search_string)
CROSS JOIN
(
SELECT
/*
Canary floor is normally "at least 90 days back" so these
server-identity strings are found regardless of how recent
the caller is interested in. When the caller supplied
@start_date/@end_date, @days_back is NULL at this point, and
a NULL days_back literal would reach xp_readerrorlog as a
NULL date argument and error. Fall back to @start_date in
date-range mode so the canary has a concrete floor.
*/
days_back =
N'N''' +
CASE
WHEN @days_back IS NOT NULL
THEN CONVERT(nvarchar(10), DATEADD(DAY, CASE WHEN @days_back > -90 THEN -90 ELSE @days_back END, SYSDATETIME()), 112)
ELSE CONVERT(nvarchar(10), @start_date, 112)
END +
N'''',
start_date =
N'N''' + CONVERT(nvarchar(30), @start_date, 121) + N'''',
end_date =
N'N''' + CONVERT(nvarchar(30), @end_date, 121) + N''''
) AS c
WHERE @custom_message_only = 0
OPTION(RECOMPILE);
/*these are the search strings we currently care about*/
INSERT
#search
(
search_string,
days_back,
start_date,
end_date
)
SELECT
search_string =
N'N''' +
REPLACE(v.search_string, N'''', N'''''') +
N'''',
c.days_back,
c.start_date,
c.end_date
FROM
(
VALUES
('error'), ('corrupt'), ('insufficient'), ('DBCC CHECKDB'), ('Attempt to fetch logical page'), ('Total Log Writer threads'),
('Wait for redo catchup for the database'), ('Restart the server to resolve this problem'), ('running low'), ('unexpected'),
('fail'), ('contact'), ('incorrect'), ('allocate'), ('allocation'), ('Timeout occurred'), ('memory manager'), ('operating system'),
('cannot obtain a LOCK resource'), ('Server halted'), ('spawn'), ('BobMgr'), ('Sort is retrying the read'), ('service'),
('resumed'), ('repair the database'), ('buffer'), ('I/O Completion Port'), ('assert'), ('integrity'), ('latch'), ('SQL Server is exiting'),
('SQL Server is unable to run'), ('suspect'), ('restore the database'), ('checkpoint'), ('version store is full'), ('Setting database option'),
('Perform a restore if necessary'), ('Autogrow of file'), ('Bringing down database'), ('hot add'), ('Server shut down'),
('stack'), ('inconsistency.'), ('invalid'), ('time out occurred'), ('The transaction log for database'), ('The virtual log file sequence'),
('Cannot accept virtual log file sequence'), ('The transaction in database'), ('Shutting down'), ('thread pool'), ('debug'), ('resolving'),
('Cannot load the Query Store metadata'), ('Cannot acquire'), ('SQL Server evaluation period has expired'), ('terminat'), ('currently busy'),
('SQL Server has been configured for lightweight pooling'), ('IOCP'), ('Not enough memory for the configured number of locks'),
('The tempdb database data files are not configured with the same initial size and autogrowth settings'), ('The SQL Server image'), ('affinity'),
('SQL Server is starting'), ('Ignoring trace flag '), ('20 physical cores'), ('No free space'), ('Warning ******************'),
('SQL Server should be restarted'), ('Server name is'), ('Could not connect'), ('yielding'), ('worker thread'), ('A new connection was rejected'),
('A significant part of sql server process memory has been paged out'), ('Dispatcher'), ('I/O requests taking longer than'), ('killed'),
('SQL Server could not start'), ('SQL Server cannot start'), ('System Manufacturer:'), ('columnstore'), ('timed out'), ('inconsistent'),
('flushcache'), ('Recovery for availability database')
) AS v (search_string)
CROSS JOIN
(
SELECT
days_back =
N'N''' + CONVERT(nvarchar(10), DATEADD(DAY, @days_back, SYSDATETIME()), 112) + N'''',
start_date =
N'N''' + CONVERT(nvarchar(30), @start_date, 121) + N'''',
end_date =
N'N''' + CONVERT(nvarchar(30), @end_date, 121) + N''''
) AS c
WHERE @custom_message_only = 0
OPTION(RECOMPILE);
/*deal with a custom search string here*/
INSERT
#search
(
search_string,
days_back,
start_date,
end_date
)
SELECT
x.search_string,
x.days_back,
x.start_date,
x.end_date
FROM
(
VALUES
(
/* xp_readerrorlog search strings are wrapped in single quotes
(see the #search.command computed column), so any literal '
inside the user-supplied @custom_message must be doubled to
avoid closing the argument early and producing a syntax
error when sys.sp_executesql parses the generated batch. A
literal " needs no handling at all now that it is not a
delimiter, and the search string is not subject to the
128-character identifier limit that silently dropped long
messages into #errors. The nvarchar(4000) command column is
the remaining ceiling: a @custom_message within a few
characters of 4000 (one less per apostrophe) still
truncates the generated command and lands in #errors. */
N'N''' + REPLACE(@custom_message, N'''', N'''''') + N'''',
N'N''' + CONVERT(nvarchar(10), DATEADD(DAY, @days_back, SYSDATETIME()), 112) + N'''',
N'N''' + CONVERT(nvarchar(30), @start_date, 121) + N'''',
N'N''' + CONVERT(nvarchar(30), @end_date, 121) + N''''
)
) AS x (search_string, days_back, start_date, end_date)
WHERE @custom_message LIKE N'_%'
OPTION(RECOMPILE);
IF @debug = 1
BEGIN
SELECT table_name = '#search', s.* FROM #search AS s;
END;
/*Set the min and max logs we're getting for the loop*/
SELECT
@l_log = MIN(e.archive),
@h_log = MAX(e.archive),
@t_searches = (SELECT COUNT_BIG(*) FROM #search AS s)
FROM #enum AS e
OPTION(RECOMPILE);
IF @debug = 1
BEGIN
RAISERROR('@l_log: %i', 0, 1, @l_log) WITH NOWAIT;
RAISERROR('@h_log: %i', 0, 1, @h_log) WITH NOWAIT;
RAISERROR('@t_searches: %I64d', 0, 1, @t_searches) WITH NOWAIT;
END;
IF @debug = 1 BEGIN RAISERROR('Declaring cursor', 0, 1) WITH NOWAIT; END;
/*start the loops*/
WHILE @l_log <= @h_log
BEGIN
DECLARE
@cs CURSOR;
SET
@cs =
CURSOR
LOCAL
SCROLL
DYNAMIC
READ_ONLY
FOR
SELECT
command
FROM #search;
IF @debug = 1 BEGIN RAISERROR('Opening cursor', 0, 1) WITH NOWAIT; END;
OPEN @cs;
FETCH FIRST
FROM @cs
INTO @c;
IF @debug = 1 BEGIN RAISERROR('Entering WHILE loop', 0, 1) WITH NOWAIT; END;
WHILE @@FETCH_STATUS = 0
BEGIN
IF @debug = 1 BEGIN RAISERROR('Entering cursor', 0, 1) WITH NOWAIT; END;
/*If using RDS, need to call a different procedure*/
IF @is_rds = 1
BEGIN
SELECT
@c =
REPLACE
(
@c,
N'master.dbo.xp_readerrorlog',
N'rdsadmin.dbo.rds_read_error_log'
);
END;
/*Replace the canary value with the log number we're working in*/
SELECT
@c =
REPLACE
(
@c,
N'[@@@]',
@l_log
);
IF @debug = 1
BEGIN
RAISERROR('log %i of %i', 0, 1, @l_log, @h_log) WITH NOWAIT;
RAISERROR('search %i of %I64d', 0, 1, @l_count, @t_searches) WITH NOWAIT;
RAISERROR('@c: %s', 0, 1, @c) WITH NOWAIT;
END;
IF @debug = 1 BEGIN RAISERROR('Inserting to error log', 0, 1) WITH NOWAIT; END;
BEGIN
BEGIN TRY
/*Insert any log entries we find that match the search*/
INSERT
#error_log
(
log_date,
process_info,
text
)
EXECUTE sys.sp_executesql
@c;
END TRY
BEGIN CATCH
/*Insert any searches that throw an error here, and why they failed*/
INSERT
#errors
(
command,
error_message
)
VALUES
(
@c,
ERROR_MESSAGE()
);
END CATCH;
END;
IF @debug = 1 BEGIN RAISERROR('Fetching next', 0, 1) WITH NOWAIT; END;
/*Get the next search command*/
FETCH NEXT
FROM @cs
INTO @c;
/*Increment our loop counter*/
SELECT
@l_count += 1;
END;
IF @debug = 1 BEGIN RAISERROR('Getting next log', 0, 1) WITH NOWAIT; END;
/*Increment the log numbers*/
SELECT
@l_log = MIN(e.archive),
@l_count = 1
FROM #enum AS e
WHERE e.archive > @l_log
OPTION(RECOMPILE);
IF @debug = 1
BEGIN
RAISERROR('log %i of %i', 0, 1, @l_log, @h_log) WITH NOWAIT;
END;
/*Stop the loop if this is NULL*/
IF @l_log IS NULL
BEGIN
IF @debug = 1 BEGIN RAISERROR('Breaking', 0, 1) WITH NOWAIT; END;
BREAK;
END;
IF @debug = 1 BEGIN RAISERROR('Ended WHILE loop', 0, 1) WITH NOWAIT; END;
END;
IF @debug = 1 BEGIN RAISERROR('Ended cursor', 0, 1) WITH NOWAIT; END;
/*get rid of some messages we don't care about*/
IF @debug = 1 BEGIN RAISERROR('Delete dumb messages', 0, 1) WITH NOWAIT; END;
DELETE
el WITH(TABLOCKX)
FROM #error_log AS el
WHERE el.text LIKE N'DBCC TRACEON 3604%'
OR el.text LIKE N'DBCC TRACEOFF 3604%'
OR el.text LIKE N'This instance of SQL Server has been using a process ID of%'
OR el.text LIKE N'Could not connect because the maximum number of ''1'' dedicated administrator connections already exists%'
OR el.text LIKE N'Login failed%'
OR el.text LIKE N'Backup(%'
OR el.text LIKE N'[[]INFO]%'
OR el.text LIKE N'[[]DISK_SPACE_TO_RESERVE_PROPERTY]%'
OR el.text LIKE N'[[]CFabricCommonUtils::GetFabricPropertyInternalWithRef]%'
OR el.text LIKE N'CHECKDB for database % finished without errors%'
OR el.text LIKE N'Parallel redo is shutdown for database%'
OR el.text LIKE N'%This is an informational message only. No user action is required.%'
OR el.text LIKE N'%SPN%'
OR el.text LIKE N'Service Broker manager has started.%'
OR el.text LIKE N'Parallel redo is started for database%'
OR el.text LIKE N'Starting up database%'
OR el.text LIKE N'Buffer pool extension is already disabled%'
OR el.text LIKE N'Buffer Pool: Allocating % bytes for % hashPages.'
OR el.text LIKE N'The client was unable to reuse a session with%'
OR el.text LIKE N'SSPI%'
OR el.text LIKE N'%Severity: 1[0-8]%'
OR el.text LIKE N'Login succeeded for user%'
OR el.text LIKE N'%query notification%'
OR el.text IN
(
N'The Database Mirroring endpoint is in disabled or stopped state.',
N'The Service Broker endpoint is in disabled or stopped state.'
)
OPTION(RECOMPILE);
/*get rid of duplicate messages we don't care about*/
IF @debug = 1 BEGIN RAISERROR('Delete dupe messages', 0, 1) WITH NOWAIT; END;
WITH
d AS
(
SELECT
el.*,
n =
ROW_NUMBER() OVER
(
PARTITION BY
el.log_date,
el.process_info,
el.text
ORDER BY
el.log_date
)
FROM #error_log AS el
)
DELETE
d
FROM d AS d WITH (TABLOCK)
WHERE d.n > 1;
/*Return the search results*/
SELECT
table_name =
'#error_log',
el.*
FROM #error_log AS el
ORDER BY
el.log_date DESC
OPTION(RECOMPILE);
/*If we hit any errors, show which searches failed here*/
IF EXISTS
(
SELECT
1/0
FROM #errors AS e
)
BEGIN
SELECT
table_name =
'#errors',
e.*
FROM #errors AS e
ORDER BY
e.id
OPTION(RECOMPILE);
END;
END;
GO