Лог ошибок sql server

Пересказ статьи Rajendra Gupta. How to manage SQL Server logs effectively

В статье дается обзор журналов SQL Server для управления и устранения неполадок на сервере.

Введение

Журналы являются лучшим средством администратора баз данных при решении любых проблем. Эти проблемы могут быть связаны с конфигурацией сервера, запуском, восстановлением, производительностью, флагами трассировки, тупиковыми ситуациями, вводом-выводом или задержками. Предположим, например, что ваш экземпляр SQL Server перезапускается по непонятным причинам, и после перезапуска службы SQL работают, однако ваше приложение не имеет доступа к базе данных. Таким образом, для исследования проблемы вам нужно заглянуть в последний журнал SQL Server, чтобы проконтролировать процесс восстановления базы данных и узнать оценку времени его завершения.

Администратор базы данных может также сконфигурировать SQL Server для выполнения дополнительных записей в журналы ошибок. Например, мы можем включить флаг трассировки для захвата информации о тупиковых ситуациях. DBA должен регулярно просматривать эти журналы в поисках потенциальных проблем. Вы можете обнаружить в журналах такую информацию, как сбой резервного копирования, ошибки входа, ошибки ввода-вывода. Эти журналы ошибок являются отличным средством для обнаружения существующих и потенциальных проблем в экземплярах SQL Server.

Журналы SQL Server известны как SQL Server Error logs. Журналы ошибок содержат информационные сообщения, предупреждения и сообщения о критичных ошибках. Вы можете просматривать некоторые из этих журналов также в просмотрщике событий Windows. Однако рекомендуется использовать журналы SQL Server для получения подробной информации.

Журналы SQL Server и их местонахождение

Если вы подключены к экземпляру SQL Server в SSMS, перейдите к Management -> SQL Server Logs. Как показано ниже, имеется текущий журнал и шесть архивных журналов (Archive#1 — Archive #6).

Метод 1: Использование расширенной процедуры xp_readerrorlog

Текущие журналы являются самыми последними файлами журнала ошибок, и вы можете использовать их для просмотра недавней деятельности с момента запуска SQL Server или ручного перезапуска файла журнала. Журнал ошибок SQL Server является текстовым файлом, хранящимся в каталоге журналов экземпляра SQL Server. Вы можете использовать расширенную процедуру xp_readerrorlog для нахождения текущего местоположения журнала ошибок.

USE master
GO
xp_readerrorlog 0, 1, N'Logging SQL Server messages', NULL, NULL,NULL
GO

Этот запрос имеет следующие параметры:

  1. Файл журнала ошибок: значение 0 для текущего, 1 для Archive#1, 2 для Archive #2.
  2. Тип файла журнала: значение 0 для журнала ошибок SQL Server, 1 для агента SQL Server.
  3. Строка поиска 1
  4. Строка поиска 2
  5. Время от
  6. Время до
  7. Сортировка результатов — по возрастанию (N’ASC) или по убыванию (N’Desc)

Для моего демонстрационного экземпляра файл журнала ошибок находится в папке C:Program FilesMicrosoft SQL ServerMSSQL14.MSSQLSERVERMSSQLLogERRORLOG.

Метод 2: Использование функции SERVERPROPERTY()

Мы можем использовать в запросе функцию SERVERPROPERTY, и также определить местонахождение SQL Server ERRORLOG.

SELECT SERVERPROPERTY('ErrorLogFileName')  AS 'Error log location'

Метод 3: использование менеджера конфигурации SQL Server

Откройте SQL Server Configuration Manager и посмотрите параметры запуска. Местоположение файлов журнала указывается с помощью переключателя -e.

Вы можете развернуть каталог журналов и просмотреть текущий или архивные файлы журнала. Эти журналы ошибок можно открыть в текстовом редакторе, таком как Notepad или Visual Studio Code.

Конфигурирование числа файлов журнала SQL Server и их размеров

По умолчанию SQL Server поддерживает текущий и 6 архивных файлов журнала. Чтобы уточнить значение, выполните щелчок правой кнопкой на папке SQL Server Logs в SSMS и выберите Configure.

SQL Server записывает всю информацию в текущий файл журнала, независимо от размера файла журнала. В загруженной системе или в экземпляре с большим количеством ошибок вам может быть сложно просмотреть файл журнала в SSMS. SQL Server создает новый файл журнала и архивирует текущий файл в следующих случях.

  1. При перезапуске службы SQL.
  2. При перезагрузке журнала ошибок вручную.

Однако если вы часто перезапускаете серверы по неизвестным причинам, то можете потерять все исторические данные в архивных журналах, поскольку их поддерживается только шесть. Поскольку ошибки содержат ценную информацию, которая может помочь в решении проблем, вы можете не захотеть потерять эти важные данные. Тогда, возможно, вы захотите сохранять файлы журнала производственной системы в течение недели или даже месяца.

SQL Server позволяет сконфигурировать от 6 до 99 файлов журнала ошибок. Вы не можете указать значение меньше шести, поскольку в любом случае будет поддерживаться шесть архивных журналов ошибок.

Для изменения значения по умолчанию числа файлов журнала ошибок поставьте галочку в поле с названием “Limit the number of error log files before they are recycled”. Например, следующий скриншот показывает максимальное число файлов журнала ошибок, равное 30.

Это эквивалентно выполнению скрипта T-SQL, который использует расширенную хранимую процедуру и обновляет значение регистра.

USE [master]
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'SoftwareMicrosoftMSSQLServerMSSQLServer', N'NumErrorLogs', REG_DWORD, 30
GO

Замечание. Следует перезапустить службу SQL, чтобы изменения вступили в силу.

Как утверждалось ранее, по умолчанию размер журнала ошибок не ограничен. Например, если вы не запускаете SQL Server в течение длительного периода и вручную не перегружаете файлы журнала, этот файл вырастет до громадных размеров. Поэтому в конфигурации журнала ошибок показано значение 0, соответствующее неограниченному размеру журнала.

Вы можете задать размер в Кб для ограничения размера журнала ошибок в соответствии с вашими требованиями. Например, здесь мы ограничиваем размер файла журнала в 1Гб.

Эквивалентный скрипт T-SQL обновляет ErrorLogSizeInKb в регистре SQL Server.

USE [master]
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'SoftwareMicrosoftMSSQLServerMSSQLServer', N'ErrorLogSizeInKb', REG_DWORD, 1048576
GO

Перезагрузка журналов ошибок вручную

SQL Server позволяет вручную перегружать журналы ошибок для эффективного управления ими. Например, предположим, что вы увеличили число файлов журнала ошибок до 30. Тогда мы можем создать задание для агента SQL Server, который перегружает журналы ошибок в полночь. Тем самым мы имеем файл журнала ошибок на каждый день, если SQL Server не будет перезапущен в этом промежутке. Для перезагрузки вручную выполните системную хранимую процедуру sp_cycle_errorlog. Эту процедуру может выполнить пользователь с фиксированной серверной ролью sysadmin.

EXEC sp_cycle_errorlog
GO

Файл журнала SQL Server Agent

Агент SQL Server также имеет отдельный журнал ошибок, подобный журналам SQL Server. Вы можете обнаружить его в папке SQL Server Agent – > Error logs.

Щелкните правой кнопкой на папке Error log и выберите команду Configure. Это даст местоположение журнала ошибок агента и уровень журнала агента.

Файл журнала агента имеет расширение *.OUT и хранится в папке log при конфигурации по умолчанию. Например, в моей системе файл журнала находится здесь: C:Program FilesMicrosoft SQL ServerMSSQL14.MSSQLSERVERMSSQLLogSQLAGENT.OUT.

По умолчанию в файл журнала записываются ошибки и предупреждения; однако мы можем включить информационные сообщения:

  • Предупреждения: Эти сообщения предоставляют информацию о потенциальных проблемах. Например, “Job X was deleted while it was running” (задание Х было удалено во время выполнения).
  • Сообщение об ошибках: оно дает информацию, которая требует немедленного вмешательства администратора баз данных, например, невозможность почтового сеанса.

Чтобы добавить информационное сообщение, поставьте галочку в поле Information.

SQL Server использует до 9 файлов журнала агента SQL Server. Имя текущего файла SQLAGENT.OUT. Файл с расширением .1 указывает на первый архивный журнал ошибок агента. Аналогично расширение .9 указывает на 9-й (самый старый) архив журнала ошибок.

Файлы журнала агента SQL Server перегружаются всякий раз, когда перезапускается SQL Server Agent. Для того, чтобы сделать это вручную, выполните щелчок правой кнопкой на папке Error Logs folder и выберите Recycle.

Или используйте хранимую процедуру sp_cycle_agent_errorlog для перезагрузки файлов журнала агента SQL Server вручную.

USE msdb ;  
GO
EXEC dbo.sp_cycle_agent_errorlog ;
GO

Хранимая процедура архивирует текущий журнал ошибок агента, используя следующий процесс:

  • Создается новый текущий журнал ошибок агента.
  • Текущий журнал ошибок SQLAgent.out преобразуется в SQLAgent.1.
  • SQLAgent.1 преобразуется в SQLAgent.2

Заключение

Файл журнала ошибок SQL Server содержит информацию, предупреждения и критические сообщения экземпляра. Это полезно для решения проблем, аудита входа (успешно, отказ). Администратор базы данных может сконфигурировать требуемое число архивных журналов ошибок и каталогов для хранения этих файлов.
Вы должны регулярно просматривать записи в журнале в качестве подготовки ежедневных или еженедельных отчетов о состоянии сервера.

SQL Server maintains its own log, also called “SQL Server Error Log”. This log contains messages describing informational and error events, similar to messages that you can find in Windows logs. In fact, many of the messages found in the SQL Server Error Log can also be found in the Windows Application Log. The SQL Server Error Log is a great place to find information about what’s happening on your database server.

SQL Server uses 7 log files to store these messages. One file serves as the current log file, and every new message is written to that file. The other 6 files are archived files, and they contain previous messages. Each time SQL Server is restarted, it recycles the files. What does it mean? First, it means that a new log file is created and becomes the new current log file. Second, the oldest log file (“Archive #6”) is deleted.

And third, all the other log files are pushed back one step. The previous current log file becomes “Archive #1”, the previous “Archive #1” log file becomes “Archive #2”, and so on.

The log files are stored in the log folder of the instance. This folder is located by default in “Program FilesMicrosoft SQL ServerMSSQL{nn}.MyInstanceMSSQLLog”. You can configure the location of the log folder during installation, and you can also change it using the “-e” startup parameter of the SQL Server service.

So far I described the default behavior of SQL Server. There are three problems with the default behavior of SQL Server. The first problem is that you have no control over the size of the log files. One file can be very large while another file can be very small. It would be easier to manage these files and work with them if they had a more controlled and predictable size. The second problem is that you have no control over the recycling process. One file can contain two months of messages, while another file can contain only a few hours of messages. It’s difficult to find a specific message from a specific point in time. The third problem with the default behavior of SQL Server is that there are only 7 log files, and if recycling happens too often, then you might not have enough history.

In order to solve the first two problems mentioned above, all we need to do is to control the recycling process.

The sys.sp_cycle_errorlog system stored procedure will do the job. Each time you call this stored procedure, SQL Server performs the recycling process as mentioned above. So what you can do is create a job that runs on a fixed schedule (let’s say – daily), which calls this stored procedure. This way, each log file will contain messages for a single day. The result is a more predictable size for the log files, and it’s also easier to locate messages from a specific day.

In order to solve the third problem (not enough history), all we need to do is to increase the number of log files. You can determine how many archive log files to keep (in addition to the current log file). The default is 6, but you can change it to any number between 6 and 99. One way to do it is by right-clicking the “SQL Server Logs” folder in SSMS and choosing “Configure”. You will be presented with the following dialog:

Check the checkbox and specify the number of archive log files you would like to have. For example, I usually use 30 log files, one for each day, so at any point in time, I have a log history of 30 days.

Notice that you can also limit the size of each error log file. If you are going to recycle the error log on a daily basis, then limiting the size might not be necessary. Nevertheless, it is a good practice to limit the size as well, just to make sure that no single file becomes too large.

Instead of using the GUI, you can also use the following statements:

EXECUTE sys.xp_instance_regwrite

N’HKEY_LOCAL_MACHINE’ ,

N’SoftwareMicrosoftMSSQLServerMSSQLServer’ ,

N’NumErrorLogs’ ,

REG_DWORD ,

30;

GO

EXECUTE sys.xp_instance_regwrite

N’HKEY_LOCAL_MACHINE’ ,

N’SoftwareMicrosoftMSSQLServerMSSQLServer’ ,

N’ErrorLogSizeInKb’ ,

REG_DWORD ,

1048576;

GO

Everything I wrote here is related to the SQL Server Error Log. Similarly, SQL Server Agent also maintains its own log in the same way. The only differences are:

  1. There are 10 files by default, instead of 7.

  2. You can’t change the number of log files.

  3. The log files are recycled each time SQL Server Agent is restarted.

  4. You use the dbo.sp_cycle_agent_errorlog system stored procedure, located in msdb, to force a recycle.

You can configure the properties of the SQL Server Agent Error Log by expanding “SQL Server Agent” in SSMS, then right-clicking “Error Logs”, and then choose “Configure”. You will be presented with the following dialog:

Here, you can specify the location of the SQL Server Agent error log files. By default, they are located in the same folder as the SQL Server error log files. You can also specify the format of the error logs (Unicode or not). And finally, you can choose the types of messages to be sent to the error log based on message severity. You can choose any combination of errors, warnings and informational messages. As you can see, there is no option to determine the number of log files. There are always 10 files.

So in order to summarize this post, I created a script that implements the recommended practice as described here.

The script does the following:

  1. Sets the number of SQL Server log files to 30.

  2. Limits the size of each log file to 1GB.

  3. Creates a job that runs every midnight and recycles the log files. The job contains two steps – the first step recycles the SQL Server log files, and the second recycles the SQL Server Agent log files.

Next time you need to investigate a database failure that occurred 12 days ago between 04:00 and 06:00 in the morning, at least you know where to search for the error messages…

Another best practice related to the SQL Server error log is to enable trace flag 3226. Without this trace flag, every time a backup on the instance is completed successfully, an entry is written in the SQL Server Error Log. If you have frequent log backups of multiple databases, these entries can add up quickly and consume a lot of space in the logs. In this case, it would be a good idea to use trace flag 3226 as a startup parameter. This trace flag suppresses those successful backup entries.

Работа с логом ошибок SQL ServerАвтор: Alexey Knyazev

Сегодня я расскажу про недокументированные расширенные хранимые процедуры (Extended Stored Procedures) для работы с журналом ошибок SQL Server и SQL Server Agent.
На самом деле при просмотре журнала SQL Server Logs через SSMS (SQL Server Management Studio) идёт обращение именно к этим двум основным процедурам (xp_readerrorlog и xp_enumerrorlogs), хоть и не на прямую, а через системные интерфейсные процедуры.
Особое внимание я уделю описанию входных параметрам этих недокументированных процедур.

И так, что же происходит, когда мы просматриваем журнал ошибок через SSMS?

Во первых мы определяем путь к нашей папке с журналами

select ServerProperty(‘ErrorLogFileName’)

Затем выводим информацию о текущем журнале и о шести предыдущих

exec master.dbo.sp_enumerrorlogs

в качестве входного параметра можно указать

  • 1 — Список журналов SQL Server (значение по умолчанию)
  • 2 — Список журналов SQL Server Agent

Если обратиться к тексту этой процедуры, то можно увидеть, что это не более, чем «обёртка» для вызова другой процедуры

create proc sys.sp_enumerrorlogs(

    @p1     int = 1)

as

begin

    IF (not is_srvrolemember(N‘securityadmin’) = 1)

    begin

       raiserror(15003,1,1, N‘securityadmin’)

       return (1)

    end

    exec sys.xp_enumerrorlogs @p1

end

По коду процедуры видно, прежде чем обратиться к расширенной хранимой процедуре xp_enumerrorlogs, идёт проверка, что пользователь входит в серверную роль securityadmin.

Теперь если мы нажмём View SQL Server Log

то мы сможем просмотреть все события выбранного журнала:

В этот момент идёт обращение к ещё одной процедуре-обёртке master..sp_readerrorlog.
Ниже текст этой процедуры:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

create proc sys.sp_readerrorlog(

    @p1     int = 0,

    @p2     int = NULL,

    @p3     nvarchar(4000) = NULL,

    @p4     nvarchar(4000) = NULL)

as

begin

    if (not is_srvrolemember(N‘securityadmin’) = 1)

    begin

       raiserror(15003,1,1, N‘securityadmin’)

       return (1)

    end

    if (@p2 is NULL)

        exec sys.xp_readerrorlog @p1

    else

        exec sys.xp_readerrorlog @p1,@p2,@p3,@p4

end

Как вы видите у неё четыре входных параметра:

  • @p1 — номер журнала (0-6); 0 — текущий
  • @p2 — чей журнал; 1 — SQL Server, 2 — SQL Server Agent
  • @p3 — фильтр для поиска
  • @p4 — второе условие для поиска

Пример:

exec master.dbo.sp_readerrorlog 0, 1, N‘error’

exec master.dbo.sp_readerrorlog 0, 1, N‘error’, N‘34050’

 

Но это ещё не всё. Если обратиться к самой расширенной процедуре xp_readerrorlog, то у неё есть ещё несколько параметров:

  • @p5 — условие с какой даты выводить результат
  • @p6 — условие до какой даты выводить результат из журнала
  • @p7 — тип сортировки (asc/desc)
  • @p8 — экземпляр SQL Server (@InstanceName), параметр появился в SQL Server 2012

Пример:

exec master.dbo.xp_readerrorlog 0, 1, null, null, ‘20130418’, ‘20130419’

exec master.dbo.xp_readerrorlog 0, 1, null, null, ‘20130418’, ‘20130419’, N‘desc’

Если необходимо работать с журналом пользователю с минимальными привилегиями, то достаточно дать явные права на эти расширенные процедуры, но обращаться к ним придётся через запросы, т.к. SSMS использует интерфейсные процедуры, которые проверяют входимость пользователя в группу securityadmin.

use master

go

grant execute on xp_readerrorlog to [Ваш юзер]

go

 

Запись опубликована в рубрике В помощь администратору с метками error log. Добавьте в закладки постоянную ссылку.

SQL server maintains its own informational and Error events in Error log. The SQL Server error log is a great place to find the information what is happening in your database. SQL Server error log maintain information about failures/ Success and Errors that
occurred in the database since SQL Server was last restarted or since the last time you have recycled the error logs. SQL Server error log contains user define events and certain system events.

By default there are 6 Archived error logs and 1 Current error log available in SQL Server instance.

1
By default error Log available in the location C:Program FilesMicrosoft SQL ServerMSSQL10.MSSQLSERVERMSSQLLog

 In the above path the filename called ERRORLOG is the currently using error log and 6 archived error logs are like ErrorLog.1, ErrorLog.2 to ErrorLog.6.

How to configure number of Error log to be maintained by SQL Server.

SQL Server management studio -> Management -> SQL Server Logs

2

3

Here can increase SQL Server error log up to 99 files.

How to start new SQL Server error log file.

Every time SQL server restart will start with new SQL server error log with name ERRORLOG and old file are renamed to ErrorLog.1, ErrorLog.1 and soon.

Here method to create new error log without server restart.

Exec sp_cycle_errorlog

Go

Before Sp_cycle_errorlog

4

After Sp_cycle_errorlog

5

Get Size of 6 default log files

EXEC master..sp_enumerrorlogs

Go

Log file data in Table

xp_readerrorlog

Have a nice day!!

How to Open, Read & Check MS SQL Error Log File – Ultimate Tutorial

sql server logs

This blog gives you a big picture of the SQL Server Error Log file, where it is located in the system & the bets way to open & view it. So, let’s have a deeper look at it.

The SQL Server Error Log sounds like SQL Transaction Log, which keeps a record of database transactions and ensures database integrity. Right? Unfortunately, Error Log file is not like that.

Topics To Be Covered

  • What is Inside SQL Server Error Log ?
  • Where is SQL Server Error Log Located ?
  • How to Change Error Log File Location in SQL Server?
  • How to Read SQL Error Log?

SQL Error Log files are very much different from SQL Server LDF. It majorly comprises User-defined events and is used to troubleshoot system problems. In this technical guide, we are going to provide complete information about Microsoft SQL Server Error Log File.

Let’s get started!

SQL Server Logs & What’s Inside Them?

SQL Server logs are the files storing complete data for the transactions of the SQL Server, whereas error log files are different. It comprises information regarding the Audit Collection, Database Mail, Windows Events, SQL Server Agent, SQL Server, Job History, and Data Collection. Moreover, it shows a summary report that use to analyze which activities took place in SSMS. So, it can easily be troubleshoot by the user.

Where is MS SQL Server Error Log Stored?

You can easily find the SQL Error Log location for your dedicated SQL Server version. All you need to use the following path to access it.

Drive: Program Files Microsoft SQL Server MSSQLV.SQLEXPRESS MSSQL Log ERRORLOG

It is a general path that provides you SQL Server 2017 / 2016 / 2014 / 2012 / 2008 / 2008 R2 / 2005 error log file location. For example, it is the SQL Server 2016 Error Log file location in Windows 10.

C: Program Files Microsoft SQL Server MSSQL13.SQLEXPRESS MSSQL Log

error log location

How to Change Error Log File Location in MS SQL Server 2017/ 2016/ 2014/ 2012

Sometime SQL users need to update the path of an SQL Error log file. The overall procedure is classified into two stages.

Stage 1: Start the SQL Server Configuration Manager

One can open the Configuration Manager with different techniques. All of them are mentioned below.

Method #1 – To open Configuration Manager, you can type the SQL Server Configuration Manager in the search box of Start and open it as shown in the screenshot.

change error log location in SQL Server

Method #2 – Else, you can use the following path to open SQL Server Configuration Manager.

SQL Server Version SQL Server Configuration Manager Exe Location
SQL Server 2017 C: Windows System32 SQLServerManager14.msc
SQL Server 2016 C: Windows System32 SQLServerManager13.msc
SQL Server 2014 C: Windows System32 SQLServerManager12.msc
SQL Server 2012 C: Windows System32 SQLServerManager11.msc
SQL Server 2008 C: Windows System32 SQLServerManager10.msc

Here, we opened the SQL Server Configuration Configuration Manager with the above–mentioned location in SQL Server 2017.

configuration

Method #3 – You can also open the Run dialog box and type ‘compmgmt.msc’ in the box.

command

From the following screen, expand the Services and Applications section and get the SQL Server Configuration Manager.

expand services

Stage 2: Change the SQL Server Error Log Path

Step-1. Under the SQL Server Configuration Manager, go to the SQL Server Services option.

services

Step-2. Perform right-click on SQL Server(SQLEXPRESS) as shown in the screenshot and choose the Properties option.

properties

Step-3. From the SQL Server(SQLEXPRESS) Properties, click on the Startup Parameters tab. Afterward, under the Existing parameters section, choose the log file whose location you want to change.

set parameters of SQL server error log

Step-4. The starting prefix (like e,d) and the current Error Log file Name will not change. Rest of the folder can be changed. Mention the new path under the Specify a startup parameter box and update it.

Step-5. The changes to SQL error logs location are saved but they are not active. For this. You need to start the SQL Server Services.

Quick Steps to Open SQL Server Error Logs

  • Launch Log Analyzer & Add SQL Server Error Log.
  • Set offline or Online Mode & Enter Server Details.
  • Preview the Concerned Files and then Proceed.
  • Set the Filters and the Destination Location.
  • Click on Export to Get the Desired Results.

Methods to Open SQL Server Error Log Files

There are two ways through which one can view the Error Log. Now, whenever, the SQL Server could not open Error Log file, then use any of the below-mentioned techniques.

Approach #1: Use T-SQL to Read SQL Error Log

Connect with the SSMS and type ‘sp_readererrorlog’ in the panel. It is a SQL Server query to read Error Log.

T-SQL querry

Approach #2: Use Object Explorer Option

Without the help of T-SQL, you can also view the error log. Let’s check out how to read SQL Server Error Log.

Step-1. Open Microsoft SQL Server Management Studio on your system.

Step-2. Time to connect with Object Explorer. Open Connect to Server Window and select the Server name. Afterward, choose the Authentication Type and click on Connect.

connect to server

Step-3. Go to the Management section from the Object Explorer in order to read SQL Error Log.

Go to Management

Step-4. Expand the Management Section and go to the SQL Server Logs.

Go to SQL Server Logs

Step-5. Right-click on SQL Server Logs option. Go to the View option and select SQL Server Log from the menu.

Click View

Step-6. The Log File Summary will appear on the screen. From the same window, you can opt for different Log – SQL Server Agent, Database Mail.

Open SQL Server Error Log

That’s all about Microsoft SQL Server Error Log.

Automated Solution to Read & Examine Error Log

Well, the manual method works but not all the time. The success ratio here is quite low. Evidently. experts recommend users opt for an advanced automated solution. And this is exactly why experts recomd the automated solution. Moreover, if you want to examine the SQL Transaction Log file, then you can try SysTools LDF File Reader Software. Download this tool & then simply follow the below instructions to read & examine your SQL error log files.

Step-1. Launch the Software & then Click on the Open button to add LDF log files.

add LDF files

Step-2. Select the Online or Offline mode & Enter SQL Server Details in the dialog box.

enter server credentials

Step-3. Preview the Files that you are concerned with by selecting them from the left panel.

read error log files

Step-4. Enter Filters if you want to Export the records for further examination.

enter filters for export

Step-5. Click on the Export button to get the records on your preferred location.

export sql server error log file

Automated Tool Features for SQL Server Logs

The automated tool is way better than the manual one because of several factors. Let’s have a look at these features in detail that makes this utility special.

  • Execute complete analysis of SQL transaction log files without hassles.
  • Recover & repair corrupt SQL LDF files as well to restore the database files.
  • Analyze all transactions like Insert, Update, and Delete with advanced features.
  • Easily examine the error log files without any need for the SQL Server application.
  • Supports data types: Datetime2, datetimeoffset, sql_variant, hierarchyid, geometry & geography.
  • Microsoft SQL Server 2019, 2017, 2016, 2014, 2012, 2008 & SQL Server 2005 LDF are supported here.

Conclusion

Finally, after understanding all the core concepts of SQL Server logs carefully, it’s time for us to conclude this article. Now, we know the best ways as well to open, read & check SQL Server error logs in a smart manner.  The above-mentioned manual & automated solutions are good enough for users to get the desired results they want.

However, when we dig deep, it’s very easy for us to say that manual solutions are a bit complex. Therefore, as per experts’ opinion, the automated tool is the only reliable option left which makes the task hassle-free.

Frequently Asked Questions –

Q-1. How to find log path where the files are kept?

Ans: The location of Error Log – C: Program Files Microsoft SQL Server MSSQLn.SQLEXPRESS MSSQL Log, where n is equivalent to the number basis on the Server version.

Q-2. How to perform SQL Server error log monitoring?

Ans: Open ErrorLog using Log File Viewer in Management Studio and analyze all the events happened in the system.

Q-3. What is the difference between SQL Log & SQL ErrorLog File?

Ans: The SQL Log or Transaction Log file keeps record of every transaction performed on the database. Whereas, the Error Log used to keep track of events happened in SSMS related to ports, network and much more.

Q-4. What’s the best way to find error logs but not their path?

Ans: Firstly, check for the error message. Now, examine errlog.log primarily. Also, check the optional log files for errors. Identify the respective errors easily.

Q-5. How to create an error log in SQL Server?

Ans: Follow the instruction as mentioned carefully:

  • Go to Object Explorer & Expand Database.
  • Navigate to Expand Management.
  • Right Click SQL Server Logs here.
  • Now Click on Configure to create errors.

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Лог ошибок python
  • Лог ошибок phpmyadmin
  • Лог ошибок php wordpress
  • Лог ошибок outlook

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии