最近有个监控项目需要采集数据库信息,原来方案是写个sql脚本,每个脚本放一个查询语句然后通过操作系统层su到oracle用户通过sqlpus执行这个.sql,然后加到crontab定时执行。但是这个问题有个弊端,就是建立的连接太多,假如每5分钟采集一次数据那意味着5分钟通过sqlplus登陆数据库再退出。后来想着怎么在数据库层每5分钟执行下查询而不是操作系统频繁的通过sqlplus登陆,具体思路写个存储过程通过存储过程把查询结果输出到指定的日志文件。再通过job定时调度。
1、建立dir授予相应权限
SQL> create or replace directory monitor as ‘/oracle/monitor‘;
SQL> grant read,write on directory monitor to system;
Grant succeeded.
SQL> grant read,write on directory monitor to sys;
Grant succeeded.
2、创建procedure
SQL> create or replace procedure pro_inst_status as
2 v_tmp varchar2(60);
3 v_out_file utl_file.file_type;
4 v_file_name varchar2(30);
5 begin
6 v_file_name := ‘inst_status.log‘;
7 v_out_file := utl_file.fopen(‘MONITOR‘,v_file_name,‘w‘);
8 if (utl_file.is_open(v_out_file)) then
9 select to_char(sysdate,‘yyyy-mm-dd hh24:mi:ss‘)||‘, ‘||instance_name||‘, ‘||status
10 into v_tmp from v$instance;
11 utl_file.put_line(v_out_file, v_tmp);
12 else
13 raise_application_error(-20001,‘Inst file Open Failure!‘);
14 end if;
15 utl_file.fclose(v_out_file);
16