Oracle: logon trigger

Create the table to save logon information:


CREATE TABLE logonaudittable (
event VARCHAR2(10),
sid NUMBER,
serial# NUMBER,
timestamp DATE,
username VARCHAR2(30),
osuserid VARCHAR2(30),
machinename VARCHAR2(64)
);

Trigger for logons:

CREATE OR REPLACE TRIGGER logon_trg
AFTER LOGON ON database
DECLARE machinename VARCHAR2(64);
osuserid VARCHAR2(30);
v_sid NUMBER(10);
v_serial NUMBER(10);
CURSOR c1 IS
SELECT sid, serial#, osuser, machine FROM v$session v
WHERE v.sid = (SELECT sid FROM gv$mystat WHERE rownum = 1 ) ;
BEGIN
OPEN c1;
FETCH c1 INTO v_sid, v_serial, osuserid, machinename;
INSERT INTO logonaudittable VALUES ( 'LOGON',
v_sid, v_serial,
sysdate, user, osuserid, machinename );
CLOSE c1;
END;

Trigger for logoffs:

CREATE OR REPLACE TRIGGER logoff_trg
BEFORE LOGOFF ON database
DECLARE machinename VARCHAR2(64);
osuserid VARCHAR2(30);
v_sid NUMBER(10);
v_serial NUMBER(10);
CURSOR c1 IS
SELECT sid, serial#, osuser, machine FROM v$session v
WHERE v.sid = (SELECT sid FROM gv$mystat WHERE rownum = 1 ) ;
BEGIN
OPEN c1;
FETCH c1 INTO v_sid, v_serial, osuserid, machinename;
INSERT INTO logonaudittable VALUES ( 'LOGOFF', v_sid, v_serial, sysdate, user, osuserid, machinename );
CLOSE c1;
END;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.