(1)创建结果日志表
create table LOG$INFO
(
USERNAME VARCHAR2(30), --登陆用户名
TERMINAL VARCHAR2(50), --登录终端名
IPADRESS VARCHAR2(20), --登录IP地址
OSUSER VARCHAR2(30), --登录主机用户名
MACHINE VARCHAR2(64), --登录主机名
PROGRAM VARCHAR2(64), --登录方式:plsql
SID NUMBER,
SERIAL# NUMBER,
AUSID NUMBER,
LOGINTIME DATE default sysdate, --登入时间
LOGout_TIME date --登出时间
);
(2)创建登录触发器
CREATE OR REPLACE TRIGGER TR_LOGIN_RECORD
AFTER logon ON DATABASE
DECLARE
mtSession v$session%ROWTYPE;
CURSOR cSession(iiQuerySid IN NUMBER) IS
SELECT * FROM v$session
WHERE nvl(osuser,'x') <> 'SYSTEM' and type <> 'BACKGROUND' and audsid = iiQuerySid;
BEGIN
OPEN cSession(userenv('SESSIONID'));
FETCH cSession INTO mtSession;
IF cSession%FOUND THEN
INSERT INTO log$info(username,logintime,terminal,ipadress,osuser,machine,
program,sid,serial#,ausid)
VALUES(USER,SYSDATE,mtSession.Terminal,
SYS_CONTEXT ('USERENV','IP_ADDRESS'),mtSession.Osuser,
mtSession.Machine,mtSession.Program,mtSession.Sid,mtSession.Serial#,userenv('SESSIONID'));
END IF;
CLOSE cSession;
EXCEPTION
WHEN OTHERS THEN
raise;
end;
/
(3)创建登出触发器
create or replace trigger TR_LOGOFF_RECORD
before LOGOFF ON DATABASE
DECLARE
mtSession v$session%ROWTYPE;
CURSOR cSession(iiQuerySid IN NUMBER) IS
SELECT * FROM v$session where
nvl(osuser,'x') <> 'SYSTEM' and type <> 'BACKGROUND' and audsid = iiQuerySid;
BEGIN
OPEN cSession(userenv('SESSIONID'));
FETCH cSession INTO mtSession;
IF cSession%FOUND THEN
UPDATE LOG$INFO SET LOGOUT_TIME=SYSDATE WHERE sid=mtSession.Sid AND serial#=mtSession.Serial#;
END IF;
CLOSE cSession;
EXCEPTION
WHEN OTHERS THEN
raise;
END;
/
(4)查询登录信息
select *from LOG$INFO;