-- logger3.sql

CREATE OR REPLACE PACKAGE logger AS
  TYPE line_tab_type IS TABLE OF VARCHAR2(500) INDEX BY PLS_INTEGER;
  PROCEDURE open(file VARCHAR2);
  PROCEDURE write(line VARCHAR2);
  FUNCTION read_lines RETURN line_tab_type;
  PROCEDURE close;
END;
/

CREATE OR REPLACE PACKAGE BODY logger AS
  logfile UTL_FILE.FILE_TYPE;
  filename VARCHAR2(30);
 
  PROCEDURE open(file VARCHAR2) AS
  BEGIN
   filename := file;
   logfile := UTL_FILE.FOPEN('LOGDIR', filename, 'a');
  END open;

  PROCEDURE write(line VARCHAR2) AS
    time VARCHAR2(30);
  BEGIN
    time := TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS');
    UTL_FILE.PUT_LINE(logfile, time || ': ' || line);
  END write;

  FUNCTION read_lines RETURN line_tab_type AS
    line VARCHAR2(1024);
    line_tab line_tab_type;
    i PLS_INTEGER := 1;
  BEGIN
    UTL_FILE.FCLOSE(logfile);
    logfile := UTL_FILE.FOPEN('LOGDIR', filename, 'r');

    WHILE TRUE LOOP
      UTL_FILE.GET_LINE(logfile, line);
      line_tab(i) := line;
      i := i + 1;
    END LOOP;

  EXCEPTION
    WHEN NO_DATA_FOUND THEN
      UTL_FILE.FCLOSE(logfile);
      logfile := UTL_FILE.FOPEN('LOGDIR', filename, 'a');
      RETURN line_tab;
  END read_lines;

  PROCEDURE close AS
  BEGIN
    UTL_FILE.FCLOSE(logfile);
  END close;
END;
/
