Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Racket: Logging to a file

Tags:

racket

I was writing a Racket program that needed to log information but I wanted to store the logs in a file. My first attempt was to use "with-logging-to-port" and use "open-output-file" to create an output-port.

#lang racket
(require racket/logging)
(define (identity/log x)
  (log-info "returning ~a" x) x)

(with-logging-to-port (open-output-file "testing.txt")
  (λ () (identity/log 4)) 'info)

However when I open the file afterwards it is blank! In addition, I can't run this more than once because "open-output-file" gives me an error that the file already exists.

like image 686
rmacnz Avatar asked Aug 26 '16 12:08

rmacnz


2 Answers

I'm pretty sure the reason is that you don't close the file properly. This should work:

(let ((out (open-output-file "testing.txt"
                             ; just to not get an error on consecutive runs
                             #:exists 'append))) 
  (with-logging-to-port out
    (λ () (identity/log 4)) 'info)
  (close-output-port out))

Instead of doing housekeeping you can use call-with-output-file

(call-with-output-file "testing.txt"
  (λ (out) 
    (with-logging-to-port out
      (λ () (identity/log 4)) 'info))
  #:exists 'append)
like image 118
Sylwester Avatar answered Oct 07 '22 06:10

Sylwester


If log information is in a list of strings, say lst, one can also use following function:

(display-lines-to-file  lst "mylog.txt" 
    #:exists 'append)

See: https://docs.racket-lang.org/reference/Filesystem.html?q=lines-file#%28def._%28%28lib._racket%2Ffile..rkt%29._display-lines-to-file%29%29

(require racket/file)
(display-lines-to-file   lst     path                
     [  #:separator separator                
        #:mode mode-flag                 
        #:exists exists-flag])      →       void?
like image 33
rnso Avatar answered Oct 07 '22 06:10

rnso