How to stopApp() onSessionEnded without leaving log files in /var/log/shiny-server?

When stopApp() gets executed the temporary log file for a shiny app doesn't get automatically deleted by shiny-server (like they do when there are no error messages in the log) which is very inconvenient since these logs are not handled by logrotate and they start to pile up. Do you know how to stop an app on session ended without leaving log files in /var/log/shiny-server?

Here is a reprex so you can test the behavior if interested (This has to be deployed on /srv/shin-server)

library(shiny)

ui <- fluidPage()

server <- function(input, output, session) {
  session$onSessionEnded(stopApp)
}

shinyApp(ui, server)

Hi @andresrcs,

I'm not sure if this is what you are asking for because you could also realize this via onSessionEnded() but please check the help page of ?onStop.

There is an example on how to run a callback after each session or after the app was stopped:

## Only run this example in interactive R sessions
if (interactive()) {
  # Open this application in multiple browsers, then close the browsers.
  shinyApp(
    ui = basicPage("onStop demo"),

    server = function(input, output, session) {
      onStop(function() cat("Session stopped\n"))
    },

    onStart = function() {
      cat("Doing application setup\n")

      onStop(function() {
        cat("Doing application cleanup\n")
      })
    }
  )
}
# In the example above, onStop() is called inside of onStart(). This is
# the pattern that should be used when creating a shinyApp() object from
# a function, or at the console. If instead you are writing an app.R which
# will be invoked with runApp(), you can do it that way, or put the onStop()
# before the shinyApp() call, as shown below.

## Not run: 
# ==== app.R ====
cat("Doing application setup\n")
onStop(function() {
  cat("Doing application cleanup\n")
})

shinyApp(
  ui = basicPage("onStop demo"),

  server = function(input, output, session) {
    onStop(function() cat("Session stopped\n"))
  }
)
# ==== end app.R ====


# Similarly, if you have a global.R, you can call onStop() from there.
# ==== global.R ====
cat("Doing application setup\n")
onStop(function() {
  cat("Doing application cleanup\n")
})
# ==== end global.R ====

## End(Not run)

PS: of course you'll need to write some code to delete the logs e.g. using unlink() or fs::file_delete().

I was wondering why the shiny-server service does not handle the log deletion when stopApp() is called, I thought maybe it's a configuration issue, but what you are proposing seems like a viable walk-around.

I'm curious if there is a "best practice" for this scenario.

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.