You can achieve logging on the server using a combination of logging
and shinyjs
.
install.packages("logging")
install.packages("shinyjs")
In your ui.R, bind shinyjs
using shinyjs::useShinyjs
:
library(shinyjs)
shinyUI(
fluidPage(
useShinyjs(),
# etc...
In your server.R, add logjs
to the list of log handlers:
library(magrittr)
library(shinyjs)
library(logging)
basicConfig()
options(shiny.error = function() {
logging::logerror(sys.calls() %>% as.character %>% paste(collapse = ", ")) })
shinyServer(function(input, output, session) {
printLogJs <- function(x, ...) {
logjs(x)
T
}
addHandler(printLogJs)
# etc...
Then to print something, use loginfo
.
Other Tips
When running your app locally, such as from RStudio, use options(shiny.error = browser)
or options(shiny.error = recover)
to identify the source of errors.
Put as much business logic into packages and external scripts as possible. Unit-test these whenever you suspect they are causing issues. The testthat
package can help here.
If you expect a variable to meet certain constraints, add an assertion. For example, if x
should be a zoo
, put assert_that(is.zoo(x))
near the top of your reactive.
Beware of the default drop
behaviour. Get into the habit of specifying drop = F
whenever you want your result to be a data.frame
.
Try to minimize the number of variables (options, environment, caching, UI state, etc.) that a unit of code depends on. Weakly typed languages are hard enough to debug already!
Use proper S4 and S3 classes instead of raw R structures where possible.
dput
will allow you to examine the internal structure of objects, and is very useful when trying to reproduce errors outside of an app.
Try to do your debugging in an interactive console, not using print
inside an app. This will allow you to iterate more quickly. When debugging outside of an app is not possible, try putting a browser()
call just before the problem code.
Never use sapply
in non-interactive code. With an empty output, it will be unable to infer the type that you want and return an empty list
. If your result should be a vector
, use vapply
. If your result should be a list
, use lapply
.
You should also look at Debugging Shiny Applications from the RStudio team.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…