Thursday, December 17, 2020

Logging Table in Oracle

In Oracle 12c  you create table:

CREATE TABLE msg_log (
    id            NUMBER
        GENERATED BY DEFAULT ON NULL AS IDENTITY,
    ts            TIMESTAMP WITH LOCAL TIME ZONE,
    schema_name   VARCHAR2(15),
    message       VARCHAR2(250)
);

 Create procedure:

CREATE OR REPLACE PROCEDURE log_message (
    message IN VARCHAR2
) AS
    PRAGMA autonomous_transaction;
    schema_name VARCHAR2(15);
BEGIN
    SELECT
        sys_context('userenv', 'current_schema')
    INTO schema_name
    FROM
        dual;

    INSERT /*+ APPEND */ INTO msg_log (
        ts,
        schema_name,
        message
    ) VALUES (
        SYSDATE,
        schema_name,
        message
    );

    COMMIT;
END log_message;
Test
EXEC log_message('foo');

SELECT
    id,
    TO_CHAR(ts, 'YYYY-MM-DD HH24:MM:SS') AS log_date,
    message
FROM
    msg_log; -- where ts > '17-DEC-20 05.05.52.000000000 PM';

No comments: