R sink() message and output to same file - sanity check
Asked Answered
S

1

7

I'm using R's sink() function to capture errors, warnings, messages and console output into a single text file.

I'm wondering if simultaneously sinking both message and output types to a single open file is bad to do?

I capture all of the above into a single file, but I must open a file handle to allow both sink types to be captured. The following code illustrates using the file handle approach:

message_filename = 'script_messages.txt'
try(message_file <- file(message_filename, open="at")) # open file for appending in text mode
sink(message_file, type="message")
sink(message_file, type="output")

cat("\n\n")
message(format(Sys.time(), "%a %b %d %Y %X TZ(%z)"), appendLF = TRUE)
# next line produces messages since file doesn't exist
try(source("import_file.R"), silent = TRUE)

# Save and close writing errors, warnings, messages, and console output to a file
sink(type="output")
sink(type="message")
close(message_file)

If I don't open a file handle, then the sink 'output' type messages are the only ones captured in the text file.

The documentation on sink {base} has some key info in the first half of the Details section, but I'm not fluent enough to be sure I've implemented it properly.

Silkweed answered 30/11, 2019 at 22:16 Comment(0)
B
2

I believe it's to do with the global option for warn. The default is warn=0 which means "warnings are stored until the top–level function returns". In other words, when you source("script.R"), R stores up the warnings and prints them once your script has finished, i.e. after you've run sink(type="output"); sink(type="message"); close(message_file).

To change this you can call options(warn=1) before you source your script, this will print warnings as they occur and will therefore be caught by your sink. This only needs to be run once per session.

Bruell answered 30/6, 2020 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.