Debian Codegraph @

R/otel-attr-srcref.R

raw
1
2
3 # Very similar to srcrefFromShinyCall(),
4 # however, this works when the function does not have a srcref attr set
5 otel_srcref_attributes <- function(srcref, fn_name = NULL) {
6 if (is.function(srcref)) {
7 srcref <- getSrcRefs(srcref)[[1]][[1]]
8 }
9
10 if (is.null(srcref)) {
11 return(NULL)
12 }
13
14 stopifnot(inherits(srcref, "srcref"))
15
16 # Semantic conventions for code: https://opentelemetry.io/docs/specs/semconv/registry/attributes/code/
17 #
18 # Inspiration from https://github.com/r-lib/testthat/pull/2087/files#diff-92de3306849d93d6f7e76c5aaa1b0c037e2d716f72848f8a1c70536e0c8a1564R123-R124
19 srcfile <- attr(srcref, "srcfile")
20 # Prefer the original filename (as user typed it) over the normalized path
21 filename <- getSrcfileFilename(srcfile)
22 dropNulls(list(
23 "code.function.name" = fn_name,
24 # Location attrs
25 "code.file.path" = filename,
26 "code.line.number" = srcref[1],
27 "code.column.number" = srcref[2],
28 # Remove these deprecated location names once Logfire supports the preferred names
29 # https://github.com/pydantic/logfire/issues/1559
30 "code.filepath" = filename,
31 "code.lineno" = srcref[1],
32 "code.column" = srcref[2]
33 ))
34 }
35
36 #' Get the srcref for the call at the specified stack level
37 #'
38 #' If you need to go farther back in the `sys.call()` stack, supply a larger
39 #' negative number to `which_offset`. The default of 0 gets the immediate
40 #' caller. `-1` would get the caller's caller, and so on.
41 #' @param which_offset The stack level to get the call from. Defaults to -1 (the
42 #' immediate caller).
43 #' @return An srcref object, or NULL if none is found.
44 #' @noRd
45 get_call_srcref <- function(which_offset = 0) {
46 # Go back one call to account for this function itself
47 call <- sys.call(which_offset - 1)
48
49 srcref <- attr(call, "srcref", exact = TRUE)
50 srcref
51 }
52
53
54 append_otel_srcref_attrs <- function(attrs, call_srcref, fn_name) {
55 if (is.null(call_srcref)) {
56 return(attrs)
57 }
58
59 srcref_attrs <- otel_srcref_attributes(call_srcref, fn_name)
60 if (is.null(srcref_attrs)) {
61 return(attrs)
62 }
63
64 attrs[names(srcref_attrs)] <- srcref_attrs
65
66 attrs
67 }