Oracle alert log где находится
If you have read Where to Find Oracle Alert Log Location, you may have some clues to find the right listener.log . But there're some differences between them.
Oracle DBA
Лучше потратить какое-то количество времени, чтобы записать успешный опыт, чем потом повторно воспроизводить его по памяти.
Все материалы обновляются по мере нахождения лучших практик и апгрейда знаний. Если будут желающие добавлять свои знания или исправлять ошибки и неточности, пишите в телеграм чате. Если будет учавствовать больше людей, качество материалов будет улучшаться и обновляться быстрее. Ссылки на ваши профили в соц. сетях будут добавлены в статьях, в которых вы учавствуете.
1. Background Dump Destination
If you are a DBA, you can query the value of BACKGROUND_DUMP_DEST , an initialization parameter, where you can find Oracle alert log.
SQL> show parameter background_dump_dest;
SQL> select value from v$parameter where name = 'background_dump_dest';
In case that you cannot query the database, you can still find the location of alert log at OS-level.
3 Ways to Find Oracle Alert Log Location
Here I introduce three ways to find the right Oracle alert log location.
For 9i and 10g
The default path of the listener log for 9i and 10g is somewhat different:
[oracle@ora9i ~]$ ll $ORACLE_HOME/network/log/listener.log
-rw-r--r-- 1 oracle oinstall 117307 Apr 18 14:26 /u01/app/oracle/product/9.2.0/network/log/listener.log
Eventually, it's in $ORACLE_HOME .
Also, we can use lsnrctl to list the listener log location.
[oracle@ora9i ~]$ lsnrctl status
.
Listener Log File /u01/app/oracle/product/9.2.0/network/log/listener.log
.
It's the same file.
Как я могу узнать, что моя база данных использует PFILE или SPFILE?
Выполните следующий запрос, чтобы увидеть какой файл параметров был использован:
8.1 Monitoring Errors and Alerts
You can monitor database errors and alerts to prevent, detect, and solve problems.
The easiest and best way to monitor the database for errors and alerts is with the Database Home page in Oracle Enterprise Manager Cloud Control (Cloud Control). See the Cloud Control online help for more information. This section provides alternate methods for monitoring, using data dictionary views, PL/SQL packages, and other command-line facilities.
A trace file is a file that contains diagnostic data used to investigate problems. An alert log is a file that provides a chronological log of database messages and errors.
A server-generated alert is a notification from the Oracle Database server of an impending problem.
8.1.1 Monitoring Errors with Trace Files and the Alert Log
A trace file is a file that contains diagnostic data used to investigate problems. An alert log is a file that provides a chronological log of database messages and errors.
The trace file and alert log contain information about errors.
To control the size of an alert log, you must manually delete the file when you no longer need it. Otherwise the database continues to append to the file.
You can control the maximum size of all trace files (excluding the alert log) using the initialization parameter MAX_DUMP_FILE_SIZE .
Background processes always write to a trace file when appropriate.
If shared server is enabled, each session using a dispatcher is routed to a shared server process, and trace information is written to the server trace file only if the session has enabled tracing (or if an error is encountered). Therefore, to track tracing for a specific session that connects using a dispatcher, you might have to explore several shared server trace files.
8.1.1.1 About Monitoring Errors with Trace Files and the Alert Log
The trace file and alert log contain information about errors.
Each server and background process can write to an associated trace file . When an internal error is detected by a process, it dumps information about the error to its trace file. Some of the information written to a trace file is intended for the database administrator, and other information is for Oracle Support Services. Trace file information is also used to tune applications and instances.
Critical errors also create incidents and incident dumps in the Automatic Diagnostic Repository. See Diagnosing and Resolving Problems for more information.
The alert log is a chronological log of messages and errors, and includes the following items:
All internal errors ( ORA-00600 ), block corruption errors ( ORA-01578 ), and deadlock errors ( ORA-00060 ) that occur
Administrative operations, such as some CREATE , ALTER , and DROP statements and STARTUP , SHUTDOWN , and ARCHIVELOG statements
Messages and errors relating to the functions of shared server and dispatcher processes
Errors occurring during the automatic refresh of a materialized view
The values of all initialization parameters that had nondefault values at the time the database and instance start
Oracle Database uses the alert log to record these operations as an alternative to displaying the information on an operator's console (although some systems also display information on the console). If an operation is successful, a "completed" message is written in the alert log, along with a timestamp.
The alert log is maintained as both an XML-formatted file and a text-formatted file. You can view either format of the alert log with any text editor or you can use the ADRCI utility to view the XML-formatted version of the file with the XML tags stripped.
Check the alert log and trace files of an instance periodically to learn whether the background processes have encountered errors. For example, when the log writer process (LGWR) cannot write to a member of a log group, an error message indicating the nature of the problem is written to the LGWR trace file and the alert log. Such an error message means that a media or I/O problem has occurred and should be corrected immediately.
Oracle Database also writes values of initialization parameters to the alert log, in addition to other important statistics.
The alert log and all trace files for background and server processes are written to the Automatic Diagnostic Repository, the location of which is specified by the DIAGNOSTIC_DEST initialization parameter. The names of trace files are operating system specific, but each file usually includes the name of the process writing the file (such as LGWR and RECO).
"Diagnosing and Resolving Problems" for information about the Automatic Diagnostic Repository (ADR).
"Alert Log" for additional information about the alert log.
Oracle Database Utilities for information on the ADRCI utility.
Your operating system specific Oracle documentation for information about the names of trace files
8.1.1.2 Controlling the Size of an Alert Log
To control the size of an alert log, you must manually delete the file when you no longer need it. Otherwise the database continues to append to the file.
You can safely delete the alert log while the instance is running, although you should consider making an archived copy of it first. This archived copy could prove valuable if you should have a future problem that requires investigating the history of an instance.
To control the size of an alert log:
Delete the alert log file.
8.1.1.3 Controlling the Size of Trace Files
You can control the maximum size of all trace files (excluding the alert log) using the initialization parameter MAX_DUMP_FILE_SIZE .
You can set this parameter in the following ways:
A numerical value specifies the maximum size in operating system blocks. The specified value is multiplied by the block size to obtain the limit.
A number followed by a K, M, or G suffix specifies the file size in kilobytes, megabytes, or gigabytes.
UNLIMITED , which is the default, specifies no limit.
Oracle Database can automatically segment trace files based on the limit you specify with the MAX_DUMP_FILE_SIZE initialization parameter. When a limit is reached, the database renames the current trace file using a sequential number, and creates an empty file with the original name.
Oracle Database Reference for more information about the MAX_DUMP_FILE_SIZE initialization parameter
8.1.1.3.1 Trace File Segmentation and MAX_DUMP_FILE_SIZE
Oracle Database can automatically segment trace files based on the limit you specify with the MAX_DUMP_FILE_SIZE initialization parameter. When a limit is reached, the database renames the current trace file using a sequential number, and creates an empty file with the original name.
The following table describes how trace files are segmented based on the MAX_DUMP_FILE_SIZE setting.
Trace files are not segmented.
Larger than 15M
Trace files are segmented on a boundary that is 1/5 of the MAX_DUMP_FILE_SIZE setting. Trace files with sizes that are less than this boundary in size are not segmented. For example, if the MAX_DUMP_FILE_SIZE setting is 100M , then the boundary is 20 MB (1/5 of 100 MB).
Trace files are not segmented.
There can be up to five segments, but the total combined size of the segments cannot exceed the MAX_DUMP_FILE_SIZE limit. When the combined size of all segments of the trace file exceeds the specified limit, the oldest segment after the first segment is deleted, and a new, empty segment is created. Therefore, the trace file always contains the most recent trace information. The first segment is not deleted because it might contain relevant information about the initial state of the process.
Segmentation improves space management for trace files. Specifically, segmentation enables you to manage trace files in the following ways:
You can purge old trace files when they are no longer needed.
You can diagnose problems with smaller trace files and isolate trace files that must be packaged for the incident packaging service (IPS).
Any segment that covers a time range that includes an incident is not deleted. It is kept in addition to the five default segments.
8.1.1.4 Controlling When Oracle Database Writes to Trace Files
Background processes always write to a trace file when appropriate.
In the case of the ARC n background process, it is possible, through the LOG_ARCHIVE_TRACE initialization parameter, to control the amount and type of trace information that is produced. To do so:
Other background processes do not have this flexibility.
Trace files are written on behalf of server processes whenever critical errors occur. Additionally, setting the initialization parameter SQL_TRACE = TRUE causes the SQL trace facility to generate performance statistics for the processing of all SQL statements for an instance and write them to the Automatic Diagnostic Repository.
Optionally, you can request that trace files be generated for server processes. Regardless of the current value of the SQL_TRACE initialization parameter, each session can enable or disable trace logging on behalf of the associated server process by using the SQL statement ALTER SESSION SET SQL_TRACE . This example enables the SQL trace facility for a specific session:
Use the DBMS_SESSION or the DBMS_MONITOR packages to control SQL tracing for a session.
The SQL trace facility for server processes can cause significant system overhead resulting in severe performance impact, so you should enable this feature only when collecting statistics.
"Diagnosing and Resolving Problems" for more information about how the database handles critical errors, otherwise known as incidents .
Oracle alert log location may vary from version to version, and sometimes it's not easily found. However, it usually locates at 3 locations.
Purge Alert Log
Whenever you want to clear alert log in a hurry or the space problem becomes serious, you can empty all content of alert log in this way:
[oracle@test ~]$ cat /dev/null > /path/to/alert_ORCL.log
This command can solve your space problem in a second if you have no time to think over a better solution. Just don't forget to change the location of alert log.
Deleting the alert log directly is also a way to do it as long as no one locks the file at that moment, the database will create a new file for the alert log afterwards. However, emptying is my first choice.
Файлы данных (Data Files)
Все данные в базе данных Oracle сохраняются в файлах данных. Все таблицы, индексы, триггеры, последовательности, программы на PL/SQL, представления - все это находится в файлах данных. И хотя эти и другие объекты базы данных логически содержатся в табличных пространствах, в действительности они сохраняются в файлах на жестком диске компьютера.
В каждой базе данных Oracle имеется по крайней мере один файл данных (но обычно их бывает больше). Если вы создаете в Oracle таблицу и заполняете ее строками, Oracle помещает эту таблицу и строки в файл данных. Каждый файл данных может быть связан только с одной базой данных.
У каждого файла данных имеется специальный формат, внутренний для программного обеспечения Oracle. Важно отдавать себе отчет в том, что файл данных состоит из заголовка и совокупности блоков. Заголовок файла данных Oracle содержит несколько структур, в том числе и идентификатор базы данных, номер и имя файла, тип файла, SCN создания и состояния файла.
Данные в файлы вносятся исключительно средствами Oracle.
Следующий запрос, покажет, где находятся файлы данных.
Необязательные файлы:
-
(необязательные в том смысле, что база может быть настроена для работы без данных файлов) (Alertlog - если нет необходимости в изучении данных по ошибкам, можно удалить. Трассировочные файлы по умолчанию не создаются. Чтобы создавались, нужно включать трассировку и потом не забыть отключить) (По умолчанию не используются. Нужно специально создавать специальными командами.)
Filename Format of Alert Log
Even though its location may vary from version to version, the alert log file name is always:
Occasionally, you cannot find the alert log file anywhere. Next, let's see how we can find it.
Файлы параметров pfile, spfie (Parameter Files)
Файлы параметров используются для конфигурирования действий Oracle предже всего при старте. Для того, чтобы запустить экземпляр базы данных, Oracle должен прочесть файл параметров и определить, какие параметры инициализации установлены для этого экземпляра. В файле параметров содержатся многочисленные параметры и их установленные значения. Oracle считывает файл параметров при запуске базы данных. Можно создать несколько файлов параметров, каждый будет соответствовать различным конфигурациям экземпляра.
- spfile - бинарный файл, который используется сервером Oracle при старте.
- pfile - текстовый файл с параметрами, будет использоваться при старте, если не будет найден spfile.
При старте, Oracle считает файл spfileora112.ora. (файл серверных параметров). Преимущество spfile заключается в том, что при работе с базой данных, любые изменения в базе касающиеся изменения параметра системы, автоматически записываются в данный файл.
Если используется pfile, для сохранения изменений, необходимо либо “руками вносить эти изменения” в текстовый файл, либо в консоли выполнять команды для создания данных файлов Ораклом.
Оперативные файлы журналов повтора (Online Redo Log Files)
Оперативные файлы журналов повтора - предназначены для записи всех изменений, выполненных над данными базы данных Oracle. Используется для хранения на диске информации для повторного выполнения операций.
Для компьютера выполнить задачи повторно - означает выполнить ее точно так, как она выполнялась в предыдущий раз. Поэтому назначение оперативного файла журнала повтора заключается в сохранении информации об изменениях в базе данных таким, образом, чтобы позже их можно было повторить.
Каждая база данных должна иметь не менее двух оперативных файлов журналов повтора. Текущий файл постепенно заполняется, после его заполнения (или переключения некоторыми командами), база данных приступает к записи в следующий файл. Эта операция называется переключением журналов.
Поскольку файлы повтора необходимы для выполнения восстановления базы данных и являются критичными, их объединяют в группы. Запись происходит одновременно в файлы одной группы.
For 11g and Later
The default location of listener log for 11g or above can be found at:
[oracle@ora11g ~]$ ll $ORACLE_BASE/diag/tnslsnr/$(hostname -s)/listener/trace/listener.log
-rw-r-----. 1 oracle oinstall 477708 Apr 18 18:25 /u01/app/oracle/diag/tnslsnr/ora11g/listener/trace/listener.log
As you can see in the path, the listener log follows the hostname, whereas the alert log location of database follows the database name (db_name). All paths follow the directory structure of diagnostic repository. That's the difference.
Another way to check the listener log location is to use lsnrctl command:
[oracle@ora11g ~]$ lsnrctl status
.
Listener Log File /u01/app/oracle/diag/tnslsnr/ora11g/listener/alert/log.xml
.
The listed file is a XML-versioned listener.log . Basically, it's not what we are looking for, but they are the same thing essentially.
3. Using Locate Command
Sometimes, using locate command will be faster than find to find the path of alert log file.
[oracle@test ~]$ locate alert_$ORACLE_SID.log
/u01/app/oracle/diag/rdbms/orcl/ORCL/trace/alert_ORCL.log
In some databases, the alert logs are big, maybe too big to make room for other files. We have to know ways to reduce the size of alert logs.
For your reference, the ways to find the location of listener log are slightly different from the ways we find Oracle alert log. You can take a look.
The retention of alert log cannot be controlled by ADRCI utility, it needs manual intervention. In this post, I'd like to share how I reduce the size of alert log by means of trimming the content of alert log file.
For 11g and Later
The default location of listener log for 11g or above can be found at:
[oracle@ora11g ~]$ ll $ORACLE_BASE/diag/tnslsnr/$(hostname -s)/listener/trace/listener.log
-rw-r-----. 1 oracle oinstall 477708 Apr 18 18:25 /u01/app/oracle/diag/tnslsnr/ora11g/listener/trace/listener.log
As you can see in the path, the listener log follows the hostname, whereas the alert log location of database follows the database name (db_name). All paths follow the directory structure of diagnostic repository. That's the difference.
Another way to check the listener log location is to use lsnrctl command:
[oracle@ora11g ~]$ lsnrctl status
.
Listener Log File /u01/app/oracle/diag/tnslsnr/ora11g/listener/alert/log.xml
.
The listed file is a XML-versioned listener.log . Basically, it's not what we are looking for, but they are the same thing essentially.
Обязательные файлы:
For Cluster Databases
For RAC environments, you have to check the listener logs at grid-level.
[grid@primary01 ~]$ echo $ORACLE_BASE
/u01/app/grid
[grid@primary01 ~]$ ll $ORACLE_BASE/diag/tnslsnr/$(hostname -s)/
total 48
drwxr-xr-x 14 grid oinstall 4096 Aug 11 2015 listener
drwxr-xr-x 14 grid oinstall 4096 Dec 12 2016 listener1
drwxr-xr-x 14 grid oinstall 4096 Dec 12 2016 listener2
drwxr-xr-x 14 grid oinstall 4096 Jan 6 2017 listener2_scan1_net2
drwxr-xr-x 14 grid oinstall 4096 Jan 6 2017 listener2_scan2_net2
drwxr-xr-x 14 grid oinstall 4096 Jan 6 2017 listener2_scan3_net2
drwxr-xr-x 14 grid oinstall 4096 Jan 6 2017 listener2_scan4_net2
drwxr-xr-x 14 grid oinstall 4096 Aug 11 2015 listener_scan1
drwxr-xr-x 14 grid oinstall 4096 Aug 11 2015 listener_scan2
drwxr-xr-x 14 grid oinstall 4096 Aug 11 2015 listener_scan3
drwxr-xr-x 14 grid oinstall 4096 Dec 20 2016 listener_scan4
drwxr-xr-x 14 grid oinstall 4096 Aug 11 2015 mgmtlsnr
The local listener log for the instance is usually at:
[grid@primary01 ~]$ ll $ORACLE_BASE/diag/tnslsnr/$(hostname -s)/listener/trace/listener.log
-rw-r----- 1 grid oinstall 882660 Jul 6 11:07 /u01/app/grid/diag/tnslsnr/primary01/listener/trace/listener.log
Or the equivalent log in XML format:
[grid@primary01 ~]$ lsnrctl status
.
Listener Log File /u01/app/grid/diag/tnslsnr/primary01/listener/alert/log.xml
For 11g and later releases (12c, 18c, 19c)
As we can notice, Oracle software divides alert logs to their own dedicated directories according to their database unique names, which is based on directory structure of diagnostic repository.
Find the Location of Oracle Listener Log by OS Commands
In case that the listener log is nowhere to be found, you can still use OS commands to find it.
Alert log и трассировочные файлы (trace file)
При работе базы данных события и ошибки регистрируются в текстовых файлах на сервере базы данных. Файл журнала предупреждений (alert log) нужен администратору базы данных для отслеживания важнейших действий с базой данных - наподобие открытия и закрытия базы данных, установления параметров загрузки базы данных и переключения оперативных журналов повтора. Также в эти файлы записываются многие ошибки базы данных для последующего расследования их причин. Любые структурные изменения базы данных также регистрируются в файле журнала предупреждений.
Когда возникает ошибка базы данных, может генерироваться файл трассировки (trace file). Они содержит подробную информацию о возникновении ошибки.
Файлы паролей (Password File)
Необязательный файл, используется для защиты информации о подключениях привилегированных пользователей. Если отсутствует, то вы можете выполнять администрирование своей базы данных, только локально. Кроме того, с его помощью контролируется количество привилегированных подключений для управления в одно и то же время.
Tags: Oracle Database, Файлы базы данных Oracle,
Управляющие файлы (Control Files)
Поскольку база данных Oracle является физическим набором связанных файлов данных, то для их синхронизации и контроля требуется особые методы. Для этих целей используются управляющие файлы.
База данных Oracle может иметь один или несколько управляющих файлов. Если имеется несколько управляющих файлов, все они должны быть абсолютно идентичными. При каждом запуске базы данных Oracle читает информацию управляющего файла, а при каждом изменении размещения или добавления новых файлов данных и журналов базы данных обновляет управляющий файл.
Using Find Command
Almost all UNIX and Linux support find command, so using it to find some files is a very common way to do it.
[oracle@ora11g ~]$ find $ORACLE_BASE -type f -name listener.log
/u01/app/oracle/diag/tnslsnr/ora11g/listener/trace/listener.log
/u01/app/oracle/product/11.2.0/dbhome_1/listener.log
The first file is the right file that we're looking for. The second file is not.
2. Using Find Command
Almost all UNIX and Linux have find command, so using it to find some files is a very common way to do it.
[oracle@test ~]$ find $ORACLE_BASE -type f -name alert_$ORACLE_SID.log
/u01/app/oracle/diag/rdbms/orcl/ORCL/trace/alert_ORCL.log
We find a file named alert_$ORACLE_SID.log starting from $ORACLE_BASE . As we can see, the file was found.
Trim Alert Log
If you want to keep most recent entries in the alert log just like trimming obsolete records off the alert log file, you may play this trick.
Here are the steps:
-
Backup specific number of records
Backup the last certain number of lines of the alert log into a second file which is temporary and transitional in the first command. In this example, we keep 50000 lines.
Copy the temporary and transitional file back to the alert log with force option.
Empty the transitional file in order to free its space if the space is still sensitive.
For convenience, I concatenate all commands in one line for executing them without any gaps. Additionally, this could also reduce the loss of log entries between executions.
[oracle@test ~]$ tail -50000 /path/to/alert_ORCL.log > /path/to/alert_ORCL.log.copy; cp -f /path/to/alert_ORCL.log.copy /path/to/alert_ORCL.log; cat /dev/null > /path/to/alert_ORCL.log.copy
Of course, you can wrap these commands in a shell script and schedule it for regularlly purging.
With respect to alert log in rdbms, you may have to handle listener.log in listener with the same manner as well, but first, you need to know the location of listener before preparing your script.
By the way, although 50000 lines that we keep in the alert log sounds large in quantity, the text file is not so big in size as you thought.
Предполагается, что вы инсталлировали базу данных, согласно документа.
Архивные файлы журналов повтора (Archive Log Files)
Как только оперативный файл журнала повтора (Redolog) оказывается заполнен, программное обеспечение сервера Oracle начинает запись в следующий файл. Эта операция повторяется, как следствие информация в оперативных файлах журнала (Redolog) многократно перезаписывается.
Если необходимо сохранить историю изменений, нужно, чтобы после переключения журналов сохранялась их копия. Для этого достаточно перевести работу базы данных в режим работы ARCHIVELOG.
Архивные файлы журналов повтора жизненно важны при восстановлении. Если часть базы данных потеряна или повреждена, то для устранения повреждений обычно требуется несколько архивных журналов или туева хуча этих журналов. Файлы журналов повтора должны применяться к базе данных последовательно. Если один из архивных файлов журналов повтора пропущен, то остальные архивные файлы журналов не могут использоваться. Храните все свои архивные файлы журналов повтора с момента выполнения последней резервной копии. Файлы журналов постепенно накапливаются и разрастаются. Иногда необходимо их удалять. Все операции с данными файлами по применению их к базе выполняются исключительно средствами базы данных. А копировать и переносить их при желании можно как угодно. Бездумно удалять их руками не рекомендуется.
For rest of cases without any clues
Which is the same way to determine DIAGNOSTIC_DEST .
For 9i and 10g
Using Locate Command
Sometimes, using locate command will be faster than find .
[oracle@ora11g ~]$ locate listener.log
/u01/app/oracle/diag/tnslsnr/ora11g/listener/trace/listener.log
/u01/app/oracle/product/11.2.0/dbhome_1/listener.log
The result of locate is the same as the result of find , but it's faster.
It is important that you monitor the operation of your database on a regular basis. Doing so not only informs you of errors that have not yet come to your attention but also gives you a better understanding of the normal operation of your database. Being familiar with normal behavior in turn helps you recognize when something is wrong.
You can monitor database errors and alerts to prevent, detect, and solve problems.
Monitoring performance includes monitoring locks and wait events and querying a set of data dictionary views.
Object quarantine enables an Oracle database to function even when there are corrupted, unrecoverable objects. The V$QUARANTINE view contains information about quarantined objects.
Читайте также: