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.
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)
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With