ORACLE使用UTL_FILE记录日志简介
Author:wangmin
1:以管理员用户登陆
如:conn sys/beyond@beyond as sysdba
2:配置UTL_FILE可操作目录
使用命令:
alter system set utl_file_dir=’/opt/oracle/oracle10g/log/utl_log’ scope=spfile
在oracle 10g之后,可以通过创建目录的形式
-- Create directory
create or replace directory UTL_FILE_DIR
as '/opt/oracle/oracle10g/log/utl_log';
操作如下图所示:
3:授权给指定用户,以便执行utl_file
GRANT EXECUTE ON utl_file TO beyond;
GRANT create any directory to beyond;
GRANT create any library to beyond;
4:重启数据库,用指定用户beyond创建测试脚本,并测试
测试代码:
create or replace procedure p_testlog(p_path varchar2,
p_filename varchar2,
v_text varchar2) as
v_filehandle utl_file.file_type; --定义一个文件句柄
begin
if (p_path is null or p_filename is null) then
goto to_end;
end if;
/*open specified file*/
v_filehandle := utl_file.fopen(p_path, p_filename, 'w');
utl_file.put_line(v_filehandle, v_text);
utl_file.fclose(v_filehandle);
<<to_end>>
null;
end p_testlog;
测试执行过程截图:
测试结果截图:
可以看到已经在指定文件目录下创建了日志文件running.log,并记录日志。
5:UTL_FILE包使用介绍
Name |
Description |
Use in SQL? |
DISABLE |
Disables output from the package; the DBMS_OUTPUT buffer will not be flushed to the screen |
Yes |
ENABLE |
Enables output from the package |
Yes |
GET_LINE |
Gets a single line from the buffer |
Yes |
GET_LINES |
Gets specified number of lines from the buffer and passes them into a PL/SQL table |
Yes |
NEW_LINE |
Inserts an end-of-line mark in the buffer |
Yes |
PUT |
Puts information into the buffer |
Yes |
PUT_LINE |
Puts information into the buffer and appends an end-of-line marker after that data |
Yes |
注意一下open_model:
只支持三种模式,只读r,只写w和追加a的方式。如果使用一个日志文件最好使用‘a’,使用w的话,会重新创建一个日志文件。