How to create periodically send text to a “log file” while printing normal output to console?

前端 未结 5 1432
隐瞒了意图╮
隐瞒了意图╮ 2021-02-12 22:43

I\'m creating R code for a Monte Carlo simulation of a professional sport. Because the game dynamics are very complicated and to make the debugging process simpler, I\'d like to

相关标签:
5条回答
  • 2021-02-12 23:17

    write("this message", file=stderr())

    0 讨论(0)
  • 2021-02-12 23:21

    To open the log file in "append" mode:

    log_con <- file("test.log",open="a")
    
    0 讨论(0)
  • 2021-02-12 23:27

    See ?cat. You can open a file connection to your log file and specify that in your cat call. When you don't specify a file name or connection it will print to the console.

    As you say, don't use sink() as it will make the log file the default connection. Rather, open a named connection with file().

    > log_con <- file("test.log")
    > cat("write to log", file = log_con) # creates file and writes to it
    > cat("write to console") # prints to console
    write to console
    

    The above results in a log file with the line "write to log" and "write to console" printed on the console.

    If you need to append to your log file, set append = TRUE and use the file name instead of the file() connection.

    > cat("add to log", file = "test.log", append = TRUE)
    
    0 讨论(0)
  • 2021-02-12 23:31

    The library log4r seems to be more complete than an homemade one: https://github.com/johnmyleswhite/log4r

    0 讨论(0)
  • 2021-02-12 23:42

    Figured it out, thanks to shujaa and BigFinger. To summarize, here is how you would do it with my example code:

    log_con <- file("/filepath/log.txt", open="a")
    
    for (i in 1:100)
    {
    cat("loop begins", file = log_con, sep="\n")
    a <- rnorm(n = 100, mean = i, sd = 5)
    print(mean(a))
    cat("single loop completed", file = log_con, sep="\n")
    }
    
    close(log_con)
    
    0 讨论(0)
提交回复
热议问题