Logging in Fortran

Here’s the translation of the Go logging example to Fortran, formatted in Markdown suitable for Hugo:

Our example demonstrates logging in Fortran. While Fortran doesn’t have a standard logging package like Go, we can create a simple logging module to achieve similar functionality.

module logging
  implicit none
  private
  public :: log_message, set_log_unit

  integer :: log_unit = 6  ! Default to standard output

contains
  subroutine set_log_unit(unit)
    integer, intent(in) :: unit
    log_unit = unit
  end subroutine set_log_unit

  subroutine log_message(message)
    character(len=*), intent(in) :: message
    character(len=20) :: timestamp
    call date_and_time(time=timestamp)
    write(log_unit, '(A,1X,A)') timestamp, trim(message)
  end subroutine log_message
end module logging

program main
  use logging
  implicit none

  integer :: custom_log_unit

  ! Simple logging to standard output
  call log_message("standard logger")

  ! Changing the log output to a file
  open(newunit=custom_log_unit, file='logfile.txt', status='replace')
  call set_log_unit(custom_log_unit)
  call log_message("logging to file")

  ! Logging with additional information
  call log_message("log with info: key=value, age=25")

  close(custom_log_unit)
end program main

In this Fortran example, we’ve created a simple logging module that provides basic functionality similar to the Go logging package. Here’s a breakdown of the code:

  1. We define a logging module with a log_message subroutine that writes timestamped messages to a specified unit (default is standard output).

  2. The set_log_unit subroutine allows changing the output unit, similar to how we can change the output in the Go example.

  3. In the main program, we demonstrate logging to standard output and to a file.

  4. While Fortran doesn’t have built-in support for structured logging like Go’s slog package, we show how to include additional information in the log message as a simple string.

To run the program, save it as logging.f90 and compile it with a Fortran compiler:

$ gfortran logging.f90 -o logging
$ ./logging

This will produce output in the console and create a logfile.txt file with additional log entries.

Note that Fortran’s logging capabilities are more basic compared to Go’s. For more advanced logging in Fortran, you might need to use external libraries or create a more sophisticated custom logging module.