Logging in Co-array Fortran

Our first program will demonstrate logging capabilities in Co-array Fortran. Here’s the full source code and explanation:

program logging_example
  use iso_fortran_env, only: error_unit, output_unit
  implicit none

  ! Simple logging to standard output
  print *, "Standard output logging"

  ! Logging to error unit (equivalent to stderr)
  write(error_unit, *) "Error unit logging"

  ! Custom logging with timestamp
  call log_with_timestamp("Custom timestamp logging")

  ! Logging with severity levels
  call log_with_level("INFO", "This is an info message")
  call log_with_level("WARNING", "This is a warning message")
  call log_with_level("ERROR", "This is an error message")

contains

  subroutine log_with_timestamp(message)
    character(len=*), intent(in) :: message
    character(len=20) :: timestamp

    call date_and_time(time=timestamp)
    write(output_unit, '(A,": ",A)') timestamp, trim(message)
  end subroutine log_with_timestamp

  subroutine log_with_level(level, message)
    character(len=*), intent(in) :: level, message

    write(output_unit, '("[",A,"]: ",A)') trim(level), trim(message)
  end subroutine log_with_level

end program logging_example

This program demonstrates various logging techniques in Co-array Fortran:

  1. We use the iso_fortran_env module to access standard output and error units.

  2. Simple logging is done using the print statement, which writes to standard output.

  3. We can log to the error unit (equivalent to stderr) using write(error_unit, *).

  4. A custom logging function with timestamp is implemented in the log_with_timestamp subroutine. It uses the intrinsic date_and_time subroutine to get the current timestamp.

  5. Logging with severity levels is demonstrated in the log_with_level subroutine, which prepends a severity level to the message.

To compile and run the program:

$ gfortran -o logging_example logging_example.f90
$ ./logging_example

Sample output (the exact timestamp will depend on when you run the program):

Standard output logging
Error unit logging
20230823120000: Custom timestamp logging
[INFO]: This is an info message
[WARNING]: This is a warning message
[ERROR]: This is an error message

While Co-array Fortran doesn’t have built-in logging libraries like some modern languages, we can implement basic logging functionality using standard I/O operations and custom subroutines. For more advanced logging needs, you might consider using external libraries or developing a more comprehensive logging module.