smbache / loggr

Easy and flexible logging for R
Other
79 stars 6 forks source link

use with the pipe operator #18

Closed Mullefa closed 9 years ago

Mullefa commented 9 years ago

About to leave my current job and before I go I am frantically refactoring all our R code in production to use loggr (fun Sunday :D). Firstly, let me say it is a fantastic package. Congrats!

Now on to the request... do you think it would be possible to include variants of the logging functions that would work with the pipe operator? e.g.

iris %>%
  log_info("grouping by species") %>%
  group_by(Species) %>%
  log_info("summing Sepal.Length by Species") %>%
  summarise(Sum.Sepal.Length = sum(Sepal.Length)

Combined with ensurer, you have some even more knarly piping for use in production.

smbache commented 9 years ago

Thanks! Glad to hear it.

I'll give it some thought as to how one could do this. The main thing to overcome is that the first argument to log_* should be ignored (or even accessible via .). One option would be to have separate pipe versions, although that would add somewhat. Possibly this is acceptable. Another could be to add an argument to explicitly turn this mode on.

smbache commented 9 years ago

Just thought of this option

iris %>%
    log_info(. ~ "There are ${NROW(.)} rows!") %>%
    group_by(Species) %>%
    ...

The one-sided formula already allows interpolation so the two-sided formula could be used for this purpose.

Mullefa commented 9 years ago

Looks stella

smbache commented 9 years ago

In the latest push I tried implementing this feature: if the second argument (i.e the first visible in a pipe expression) is a two sided formula with the dot as LHS, then it will use this for the message, and return the value in the first argument. This allows for

library(magrittr)
library(loggr)

log_file("console")

iris_sub <-
    iris %>% 
    subset(Species == "versicolor") %>% 
    log_info(. ~ "Keeping ${NROW(.)} versicolor rows.") %>% 
    transform(Ratio = Sepal.Length/Sepal.Width)

This should be an acceptable solution, given that such a formula is sufficiently useless as an actual parameter for the log event. I guess it should be considered a bit more, but please play around with it and provide some feedback.