Oracle посмотреть ошибки

When you take your first look at an Oracle database, one of the first questions is often «where’s the alert log?». Grid Control can tell you, but its often not available in the environment.

I posted some bash and Perl scripts to find and tail the alert log on my blog some time back, and I’m surprised to see that post still getting lots of hits.

The technique used is to lookup background_dump_dest from v$parameter. But I only tested this on Oracle Database 10g.

Is there a better approach than this? And does anyone know if this still works in 11g?

brian d foy's user avatar

brian d foy

130k31 gold badges208 silver badges594 bronze badges

asked Oct 5, 2008 at 12:03

tardate's user avatar

Am sure it will work in 11g, that parameter has been around for a long time.

Seems like the correct way to find it to me.

If the background_dump_dest parameter isn’t set, the alert.log will be put in $ORACLE_HOME/RDBMS/trace

answered Oct 5, 2008 at 12:04

cagcowboy's user avatar

cagcowboycagcowboy

30k11 gold badges70 silver badges93 bronze badges

1

Once you’ve got the log open, I would consider using File::Tail or File::Tail::App to display it as it’s being written, rather than sleeping and reading. File::Tail::App is particularly clever, because it will detect the file being rotated and switch, and will remember where you were up to between invocations of your program.

I’d also consider locking your cache file before using it. The race condition may not bother you, but having multiple people try to start your program at once could result in nasty fights over who gets to write to the cache file.

However both of these are nit-picks. My brief glance over your code doesn’t reveal any glaring mistakes.

answered Oct 6, 2008 at 0:56

pjf's user avatar

pjfpjf

5,99326 silver badges42 bronze badges

1

When you take your first look at an Oracle database, one of the first questions is often «where’s the alert log?». Grid Control can tell you, but its often not available in the environment.

I posted some bash and Perl scripts to find and tail the alert log on my blog some time back, and I’m surprised to see that post still getting lots of hits.

The technique used is to lookup background_dump_dest from v$parameter. But I only tested this on Oracle Database 10g.

Is there a better approach than this? And does anyone know if this still works in 11g?

brian d foy's user avatar

brian d foy

130k31 gold badges208 silver badges594 bronze badges

asked Oct 5, 2008 at 12:03

tardate's user avatar

Am sure it will work in 11g, that parameter has been around for a long time.

Seems like the correct way to find it to me.

If the background_dump_dest parameter isn’t set, the alert.log will be put in $ORACLE_HOME/RDBMS/trace

answered Oct 5, 2008 at 12:04

cagcowboy's user avatar

cagcowboycagcowboy

30k11 gold badges70 silver badges93 bronze badges

1

Once you’ve got the log open, I would consider using File::Tail or File::Tail::App to display it as it’s being written, rather than sleeping and reading. File::Tail::App is particularly clever, because it will detect the file being rotated and switch, and will remember where you were up to between invocations of your program.

I’d also consider locking your cache file before using it. The race condition may not bother you, but having multiple people try to start your program at once could result in nasty fights over who gets to write to the cache file.

However both of these are nit-picks. My brief glance over your code doesn’t reveal any glaring mistakes.

answered Oct 6, 2008 at 0:56

pjf's user avatar

pjfpjf

5,99326 silver badges42 bronze badges

1

how to check alert log errors in oracle

What is alert log file in Oracle

The alert log file (also referred to as the ALERT.LOG) is a chronological log of messages and errors written out by an Oracle Database. Typical messages found in this file are database startup, shutdown, log switches, space errors, etc. This file should constantly be monitored to detect unexpected messages and corruption.

Oracle will automatically create a new alert log file whenever the old one is deleted.

Alert log location

The location can find out using the parameter background_dump_dest

sqlplus / as sysdba
show parameter background_dump_dest

Beginning with Release 11g, the alert log file is written as XML formatted and as a text file (like in previous releases). The default location of both these files is the new ADR home (Automatic Diagnostic Repository, yet another new dump dest in 11g).

The ADR is set by using the DIAGNOSTIC_DEST initialization parameter. But you can still find the alert log location using the parameter background_dump_dest.
background_dump_dest is set like

$diagnostic_dest/diag/rdbms/<db_unique_name>/<instance_name>/trace

11g Alert log new features

Beginning with Release 11g of Oracle Database, the alert log is written as both an XML-formatted file and as a text file, as in earlier releases. Both these log files are stored inside the ADR home. The ADR root directory is known as ADR BASE. The Automatic Diagnostic Repository (ADR) is a directory structure that is stored outside of the database. This parameter is set by DIAGNOSTIC_DEST initialization parameter.

SQL> show parameter diagno
NAME TYPE VALUE
--------------------------- ----------- ------------------------------
diagnostic_dest string /u001/oracle/product/XPROD11g/diag

The location of an ADR home is given by the following path, which starts at the ADR base directory:

ADR_BASE/diag/product_type/product_id/instance_id

For example,
So for RDBMS oracle Home of Database name XPROD

ADR_base/diag/rdbms/XPROD/XPROD

Within the ADR home directory are subdirectories where the database instance stores diagnostic data.
alert Log file,The XML-formatted alert log, trace Background and server process trace files and SQL trace files , text alert.log file , cdump Core files

XML formatted alert.log
The alert log is named log.xml and is stored in the alert subdirectory of ADR home.
To get the log.xml path

ADR_BASE/diag/product_type/product_id/instance_id/alert

From Sqlplus

SQL> select value from v$diag_info where name ='Diag Alert';

ADRCI utility to view a text version of the alert log (with XML tags stripped)

Text formatted alert.log
The alert.log is named alertSID.log and is stored in the trace subdirectory of ADR home.
To view the text-only alert.log file

ADR_BASE/diag/product_type/product_id/instance_id/trace

from sqlplus

SQL> select value from v$diag_info where name ='Diag Trace';
or
SQL > Show parameter background_dump_dest

Open file alert_SID.log with a text editor

With 11g ,Oracle provides a way to look the alert log file from the database also. There is a fixed table X$DBGALERTEXT, when you query it, Oracle reads the log.xml from alert directory (which contains all the data what alert.log does), parses it and returns the details back as rows:

SQL> select message_text from X$DBGALERTEXT where rownum desc X$DBGALERTEXT
Name Null? Type
------------------------------- -------- ----------------------------
1 ADDR RAW(4)
2 INDX NUMBER
3 INST_ID NUMBER
4 ORIGINATING_TIMESTAMP TIMESTAMP(3) WITH TIME ZONE
5 NORMALIZED_TIMESTAMP TIMESTAMP(3) WITH TIME ZONE
6 ORGANIZATION_ID VARCHAR2(64)
7 COMPONENT_ID VARCHAR2(64)
8 HOST_ID VARCHAR2(64)
9 HOST_ADDRESS VARCHAR2(16)
10 MESSAGE_TYPE NUMBER
11 MESSAGE_LEVEL NUMBER
12 MESSAGE_ID VARCHAR2(64)
13 MESSAGE_GROUP VARCHAR2(64)
14 CLIENT_ID VARCHAR2(64)
15 MODULE_ID VARCHAR2(64)
16 PROCESS_ID VARCHAR2(32)
17 THREAD_ID VARCHAR2(64)
18 USER_ID VARCHAR2(64)
19 INSTANCE_ID VARCHAR2(64)
20 DETAILED_LOCATION VARCHAR2(160)
21 PROBLEM_KEY VARCHAR2(64)
22 UPSTREAM_COMP_ID VARCHAR2(100)
23 DOWNSTREAM_COMP_ID VARCHAR2(100)
24 EXECUTION_CONTEXT_ID VARCHAR2(100)
25 EXECUTION_CONTEXT_SEQUENCE NUMBER
26 ERROR_INSTANCE_ID NUMBER
27 ERROR_INSTANCE_SEQUENCE NUMBER
28 VERSION NUMBER
29 MESSAGE_TEXT VARCHAR2(2048)
30 MESSAGE_ARGUMENTS VARCHAR2(128)
31 SUPPLEMENTAL_ATTRIBUTES VARCHAR2(128)
32 SUPPLEMENTAL_DETAILS VARCHAR2(128)
33 PARTITION NUMBER
34 RECORD_ID NUMBER

There’s also a fixed table X$DBGDIREXT, which returns all file and directory names under [diagnostic_dest]/diag directory:

SQL> select lpad(' ',lvl,' ')||logical_file file_name
from X$DBGDIREXT
where rownum < 2;

12c or above Alert log new features

With 12c and above, background_dump_dest is depreciated. We can find the alert log location using below also

adrci
adrci> show alert
adrci> show alert -tail 100

how to check alert log errors in oracle using Unix Command

Go to the background dump directory to run these unix commands
Date and errors in alert.log

cat alert*log |
awk 'BEGIN{buf=""}
/[0-9]:[0-9][0-9]:[0-9]/{buf=$0}
/ORA-/{print buf,$0}'

How to find the Date of startups in the alert.log

cat alert*log |
awk 'BEGIN{buf=""}
/[0-9]:[0-9][0-9]:[0-9]/{buf=$0}
/Starting ORACLE/{print buf,$0}'

How to easily find the Oracle database startup and shutdown time using sqlplus

Here are the steps required on How to easily find the Oracle database startup and shutdown time using sqlplus
step 1)  Create a database directory object

 create or replace directory data_dir as 'Specify the Backgound dump Dest location'
 /
 Directory created.
 CREATE TABLE alert_log
 ( text_line varchar2(255))
 ORGANIZATION EXTERNAL
 (
 TYPE ORACLE_LOADER
 DEFAULT DIRECTORY data_dir
 ACCESS PARAMETERS
 (
 records delimited by newline fields
 REJECT ROWS WITH ALL NULL FIELDS
 )
 LOCATION
 (
 'alert_.log'
 )
 )
 REJECT LIMIT unlimited
 /
 Table created.

step 2)  Use the below query to find out the timing

select to_char(last_time,'dd-mon-yyyy hh24:mi') shutdown,
 to_char(start_time,'dd-mon-yyyy hh24:mi') startup,
 round((start_time-last_time)2460,2) mins_down,
 round((last_time-lag(start_time) over (order by r)),2) days_up,
 case when (lead(r) over (order by r) is null )
 then round((sysdate-start_time),2)
 end days_still_up
 from (
 select r,
 to_date(last_time, 'Dy Mon DD HH24:MI:SS YYYY') last_time,
 to_date(start_time,'Dy Mon DD HH24:MI:SS YYYY') start_time
 from (
 select r,
 text_line,
 lag(text_line,1) over (order by r) start_time,
 lag(text_line,2) over (order by r) last_time
 from (
 select rownum r, text_line
 from alert_log
 where text_line like '_  _ ::_ 20_'
 or text_line like 'Starting ORACLE instance %'
 )
 )
 where text_line like 'Starting ORACLE instance %'
 )
 /

Related Articles
ORA-00942 table or view does not exist
ora-29913: error in executing odciexttableopen callout
ORA-00257: archiver error. Connect internal only, until freed.
ORA-03113: end-of-file on communication channel
ORA-27154: post/wait create failed during startup
how to find archive log sequence number in oracle
https://docs.oracle.com/cd/B28359_01/server.111/b28310/diag005.htm#ADMIN11267

Время на прочтение
4 мин

Количество просмотров 3.7K

Этот пост навеян статьями Часть 1. Логирование событий в Oracle PL/SQL и Часть 2. Идентификация событий происходящих в Oracle PL/SQL. В первую очередь, как специалисту по performance tuning и troubleshooting, хотелось бы прокомментировать некоторые нюансы.

1. Уровни детализации логгирования

В показанной системе не хватает гибкости настройки логгирования: как уровня детализации, так и места, куда их выводить. Можно было позаимствовать функциональность из широко известных систем логгирования а-ля java.util.logging (SLF4j, log4j и его вариации для других языков/систем, и тд), гибкую настройку для какого кода с какого уровня сообщений и куда их сохранять. Например, в том же log4plsql можно настроить вывод и в alert.log, и в trace file (с помощью `dbms_system.ksdwrt()`)

2. Пользовательские ошибки и сообщения

Из самой внутренней системы ошибок Оракл можно было позаимствовать использование UTL_LMS.FORMAT_MESSAGE. Кстати, сами ошибки(и events) можно посмотреть с помощью sys.standard.sqlerrm(N):

SQL> select sys.standard.sqlerrm(-1476) errmsg from dual;

ERRMSG
-------------------------------------
ORA-01476: divisor is equal to zero

Примеры: err_by_code.sql, trace_events.sql

Кроме того, я, конечно, понимаю, что не все ошибки можно предусмотреть, но все-таки считаю, что их надо добавлять в exception handler после того как они уже были отловлены. Это будет полезно как минимум при последующих изменениях логики и будет проще видеть нестандартные или непредусмотренные ранее ситуации.

3. Что же делать в случае незалоггированных ошибок

Естественно, может случиться так, что существующая система логгирования не регистрирует какие-то неординарные ошибки, или даже ее совсем нет в базе. Тут могут быть полезны триггеры `after servererror on database/schema`. Простой минимальный пример.

К сожалению, для полноценного и срочного решения неординарных проблем, ни системы логгирования, ни таких триггеров, может быть недостаточно, и тут на помощь приходит вся мощь самой встроенной системы событий Oracle.

Например, недавно Nenad Noveljic расследовал проблему c «TNS-12599: TNS:cryptographic checksum mismatch» для чего ему нужно было получить callstack:

К счастью, помимо использованного у него в статье «ERRORSTACK», есть еще большой список «ACTIONS», включающий в себя и «CALLSTACK»:

В этой команде 12599 — это номер события(event), callstack — инструктирует сделать дамп call стека, level 2 — указывает вывести еще и аргументы функций, lifetime 1 — только один раз.

Более подробно об этом у Tanel Poder с примерами:

  • http://tech.e2sn.com/oracle/troubleshooting/oradebug-doc

  • https://tanelpoder.com/2010/06/23/the-full-power-of-oracles-diagnostic-events-part-2-oradebug-doc-and-11g-improvements/

Мало того, как сам Танел и посоветовал, можно еще воспользоваться и «trace()» для форматированного вывода shortstack():

Так что этим же мы можем воспользоваться этим для вывода callstack:

alter system set events '12599 trace("stack is: %\n", shortstack())';

Или в более новом формате:

alter system set events 'kg_event[12599]{occurence: start_after 1, end_after 1} trace("stack is: %\n", shortstack())';

Как вы видите, здесь я еще добавил фильтр на количество срабатываний: после первого выполнения и только 1 раз.

Покажу на примере «ORA-01476: divisor is equal to zero»:

alter system set events 'kg_event[1476]{occurence: start_after 1, end_after 1} trace("stack is: %\n", shortstack())';

Здесь kg_event — это Kernel Generic event, 1476 — ORA-1476. После этого запускаем в своей сессии:

SQL> alter session set events 'kg_event[1476]{occurence: start_after 1, end_after 1} trace("stack is: %\n", shortstack())';

Session altered.

SQL> select 1/0 x from dual;
select 1/0 x from dual
        *
ERROR at line 1:
ORA-01476: divisor is equal to zero


SQL> select 1/0 x from dual;
select 1/0 x from dual
        *
ERROR at line 1:
ORA-01476: divisor is equal to zero


SQL> select 1/0 x from dual;
select 1/0 x from dual
        *
ERROR at line 1:
ORA-01476: divisor is equal to zero

И в трейсфайле получаем:

# cat ORA19_ora_12981.trc
Trace file /opt/oracle/diag/rdbms/ora19/ORA19/trace/ORA19_ora_12981.trc
Oracle Database 19c Enterprise Edition Release 19.0.0.0.0 - Production
Version 19.9.0.0.0
Build label:    RDBMS_19.9.0.0.0DBRU_LINUX.X64_200930
ORACLE_HOME:    /opt/oracle/product/19c/dbhome_1
System name:    Linux
Node name:      b7c493c7f9b0
Release:        3.10.0-1062.12.1.el7.x86_64
Version:        #1 SMP Tue Feb 4 23:02:59 UTC 2020
Machine:        x86_64
Instance name: ORA19
Redo thread mounted by this instance: 1
Oracle process number: 66
Unix process pid: 12981, image: oracle@b7c493c7f9b0


*** 2021-05-08T14:12:27.000816+00:00 (PDB1(3))
*** SESSION ID:(251.9249) 2021-05-08T14:12:27.000846+00:00
*** CLIENT ID:() 2021-05-08T14:12:27.000851+00:00
*** SERVICE NAME:(pdb1) 2021-05-08T14:12:27.000855+00:00
*** MODULE NAME:(sqlplus.exe) 2021-05-08T14:12:27.000859+00:00
*** ACTION NAME:() 2021-05-08T14:12:27.000862+00:00
*** CLIENT DRIVER:(SQL*PLUS) 2021-05-08T14:12:27.000865+00:00
*** CONTAINER ID:(3) 2021-05-08T14:12:27.000868+00:00

stack is: dbgePostErrorKGE<-dbkePostKGE_kgsf<-kgeade<-kgeselv<-kgesecl0<-evadiv<-kpofcr<-qerfiFetch<-opifch2<-kpoal8<-opiodr<-ttcpip<-opitsk<-opiino<-opiodr<-opidrv<-sou2o<-opimai_real<-ssthrdmain<-main<-__libc_start_main

Или, например, недавно я посоветовал использовать alter system set events 'trace[sql_mon.*] [SQL: ...] disk=high,memory=high,get_time=highres'; для выяснения причин, почему конкретный запрос не мониторится/сохраняется real-time SQL монитором (RTSM — Real Time SQL Monitor).

Получилось несколько сумбурно, в связи с недостатком времени, но на этом, пожалуй, закончу. Будут рад вопросам — задавайте, и я постараюсь их раскрыть отдельно.

Перейти к содержимому

Alert log это журнал ошибок и важных сообщений базы данных(запуск, остановка, изменение параметров). Его файлы лежат по пути, указанному в параметре BACKGROUND_DUMP_DEST.

show parameter BACKGROUND_DUMP_DEST;
NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------
background_dump_dest                 string      C:\oraclexe\app\oracle\diag\rdbms\xe\xe\trace

Лог хранится в текстовом виде. В 11g и выше можно получить к нему доступ напрямую из базы запросом к представлению x$dbgalertext или v$diag_alert_ext:

select * from x$dbgalertext;
select * from v$diag_alert_ext;

При необходимости, можно самому сделать запись в лог с помощью dbms_system.ksdwrt. Эта процедура принимает на вход два параметра:

  • dest — куда выполняется запись. 1 — trace файл, 2 — alert log, 3 — и trace, и alert.
  • tst — текст сообщения

Для сохранения на диск записанного в буфер используется dbms_system.ksdfls. Но как правильно, интерес представляет то, что записала в него СУБД. Алерт лог содержит важные данные о событиях в базе, в том числе ошибках и служит одним из основных источников данных при расследовании системных проблем.

Понравилась статья? Поделить с друзьями:
  • Oracle перехват ошибок
  • Oracle ошибка pls 00103 encountered the symbol
  • Oracle ошибка ora 06550
  • Oracle ошибка ora 06502
  • Oracle ошибка ora 01031