Logging current function name

前端 未结 2 1153
面向向阳花
面向向阳花 2020-12-30 03:34

I have a few custom logfunctions that are extensions of cat. A basic example is something like this:

catt<-function(..., file = \"\", sep = \         


        
2条回答
  •  旧巷少年郎
    2020-12-30 04:08

    I thought I'd add the progress made so far, based completely on Andrie's work. Pretty sure other people will enjoy this, so it is now a part of a package I'm developing (not on CRAN but on R-Forge for now) called addendum (including documentation) after the nightly build.

    Function to find the 'current lowest named function' on the callstack with some bells and whistles:

    curfnfinder<-function(skipframes=0, skipnames="(FUN)|(.+apply)|(replicate)",
        retIfNone="Not in function", retStack=FALSE, extraPrefPerLevel="\t")
    {
        prefix<-sapply(3 + skipframes+1:sys.nframe(), function(i){
                currv<-sys.call(sys.parent(n=i))[[1]]
                return(currv)
            })
        prefix[grep(skipnames, prefix)] <- NULL
        prefix<-gsub("function \\(.*", "do.call", prefix)
        if(length(prefix)==0)
        {
            return(retIfNone)
        }
        else if(retStack)
        {
            return(paste(rev(prefix), collapse = "|"))
        }
        else
        {
            retval<-as.character(unlist(prefix[1]))
            if(length(prefix) > 1)
            {
                retval<-paste(paste(rep(extraPrefPerLevel, length(prefix) - 1), collapse=""), retval, sep="")
            }
            return(retval)
        }
    }
    

    This can be used in a logging function like this:

    catw<-function(..., file = "", sep = " ", fill = FALSE, labels = NULL,
        append = FALSE, prefix=0)
    {
        if(is.numeric(prefix))
        {
            prefix<-curfnfinder(skipframes=prefix+1) #note: the +1 is there to avoid returning catw itself
            prefix<-paste(prefix, ":", sep="")
        }
        cat(prefix, ..., format(Sys.time(), "(%Y-%m-%d %H:%M:%S)"), "\n",
            file = file, sep = sep, fill = fill, labels = labels, append = append)
    }
    

    As mentioned in the comments to Andrie's answer so far, there are still some issues regarding do.call. I'm going to stop spending time on it for now, but have posted the related question on the r-devel mailinglist. If/when I get a response there, and it is usable, I will update the functions.

提交回复
热议问题