Logging to files

OPEN EXTEND

A log is a sequential file opened EXTEND, so every run appends after the last. OPEN EXTEND on a file that does not exist yet returns status 35, so keep the FILE STATUS and create the file with OPEN OUTPUT on the first run:

SELECT LOG-FILE ASSIGN TO "payroll.log" ORGANIZATION IS LINE SEQUENTIAL FILE STATUS IS WS-LOG-STATUS. OPEN EXTEND LOG-FILE. IF WS-LOG-STATUS = "35" OPEN OUTPUT LOG-FILE END-IF.

Log line format

Start every record with a timestamp from CURRENT-DATE, then a severity word, then the message. Build the line in working storage, move it into the FD record, and write it; fixed fields make the log greppable years later:

STRING WS-STAMP(1:14) " INFO " WS-MESSAGE DELIMITED BY SIZE INTO WS-LINE. MOVE WS-LINE TO LOG-RECORD. WRITE LOG-RECORD.

Log hygiene

Close the log at the end of every run, even after errors, so no records are lost. Cap the file size from the scheduler, and never log full account numbers or salaries in production systems.

The code on this page was run with GnuCOBOL 3.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev