### Start Span Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Begin a span using `start_span()`. The `_dev` version can show errors related to tracer setup. ```R sessx <- start_span() ``` ```R start_span_dev() ``` -------------------------------- ### Install Development Version of otel from GitHub Source: https://github.com/r-lib/otel/blob/main/README.md Install the development version of the otel package from GitHub using the pak package manager. ```r # install.packages("pak") pak::pak("r-lib/otel") ``` -------------------------------- ### Zero-Code Instrumentation Example Source: https://context7.com/r-lib/otel/llms.txt Automatically instrument R packages without modifying source code using environment variables. This example instruments dplyr and otel packages. ```bash # Instrument all functions in dplyr and tidyr packages # OTEL_TRACES_EXPORTER=http OTEL_R_INSTRUMENT_PKGS=dplyr,tidyr Rscript script.R # Instrument only specific functions # OTEL_R_INSTRUMENT_PKGS_DPLYR_INCLUDE=filter,select,mutate # Exclude specific functions # OTEL_R_INSTRUMENT_PKGS_DPLYR_EXCLUDE=*_join ``` ```r # Example script.R library(dplyr) library(otel) # All dplyr operations are automatically traced mtcars %>% filter(mpg > 20) %>% select(mpg, cyl, wt) %>% mutate(efficiency = mpg / wt) ``` -------------------------------- ### Install otel from CRAN Source: https://github.com/r-lib/otel/blob/main/README.md Install the otel package from CRAN using the pak package manager. ```r # install.packages("pak") pak::pak("otel") ``` -------------------------------- ### Get Tracer from Provider Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Obtains a tracer instance from the tracer provider. Use this to start spans. ```R get_default_tracer_provider()$get_tracer() ``` -------------------------------- ### Check setup_r_trace Result (Initial) Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/onload.md Examine the `res` output after calling `setup_r_trace` to verify initial setup status. ```r res ``` -------------------------------- ### Get or Create an OpenTelemetry Logger Source: https://context7.com/r-lib/otel/llms.txt Gets or creates a logger from the default logger provider for more control over logging behavior. Allows setting a minimum severity level and checking if a specific level is enabled. ```r # Custom logger usage my_logger <- otel::get_logger( name = "com.mycompany.myapp", minimum_severity = "info" ) my_logger$info("Custom logger message") my_logger$warn("Warning from custom logger") # Check if enabled at specific level if (my_logger$is_enabled("debug")) { my_logger$debug("Debug message") } ``` -------------------------------- ### Set Tracer Name and Start Span Source: https://github.com/r-lib/otel/blob/main/README.md Set the tracer name using `otel_tracer_name` and start a local active span with `otel::start_local_active_span()` to instrument a function. ```r otel_tracer_name <- "" fn <- function(...) { spn <- otel::start_local_active_span("fn") ... } ``` -------------------------------- ### Get Meter from Provider Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Obtains a meter instance from the meter provider. Use this to create metric instruments. ```R get_default_meter_provider()$get_meter() ``` -------------------------------- ### Setup Default Tracer Provider Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/defaults.md Sets up the default tracer provider. This function can issue warnings or errors if specific exporters are not supported or if environment variables are misconfigured. ```r setup_default_tracer_provider() ``` -------------------------------- ### Setup Default Logger Provider Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/defaults.md Sets up the default logger provider. This function can issue errors if the specified exporter is unknown, cannot be loaded, or is not of the correct type. ```r setup_default_logger_provider() ``` -------------------------------- ### Start Local Active Span Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Initiate a local active span with `start_local_active_span()`. The `_dev` version might indicate errors during tracer initialization. ```R span4 <- start_local_active_span() ``` ```R start_local_active_span_dev() ``` -------------------------------- ### Get Logger from Provider Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Obtains a logger instance from the logger provider. Use this to log messages. ```R get_default_logger_provider()$get_logger() ``` -------------------------------- ### Setup Default Meter Provider Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/defaults.md Sets up the default meter provider. This function can issue warnings or errors if specific exporters are not supported or if environment variables are misconfigured. ```r setup_default_meter_provider() ``` -------------------------------- ### Get Default Logger Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Obtain the default logger with `get_logger()`. The `_dev` version may surface errors in setting up the logger provider. ```R lgr <- get_logger() ``` ```R get_logger_dev() ``` -------------------------------- ### Tracer Retrieval Functions Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Functions to get the default tracer. ```APIDOC ## get_default_tracer ### Description Retrieves the default OpenTelemetry tracer. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R trc <- get_tracer() ``` ### Response #### Success Response (Tracer Object) - **trc** (object) - The default tracer object. #### Response Example ``` # Message indicating an error if tracer cannot be retrieved OpenTelemetry error: nope ``` ## get_tracer_dev ### Description Development function to retrieve the default tracer, may provide more detailed error information. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R get_tracer_dev() ``` ### Response #### Success Response (Tracer Object) - **Output** (object) - The default tracer object. #### Response Example ``` # Potential error output if tracer cannot be retrieved Error in `get_default_tracer_provider()`: ! x ``` ``` -------------------------------- ### Start a Span Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Initiates a new span. Spans represent operations within a trace. Ensure the tracer is obtained from a provider. ```R trc$start_span() ``` -------------------------------- ### Get Default Logger Provider Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Retrieves the default logger provider. This is the entry point for obtaining loggers. ```R get_default_logger_provider() ``` -------------------------------- ### Get Default Tracer Provider Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Retrieves the default tracer provider. This is the entry point for obtaining tracers. ```R get_default_tracer_provider() ``` -------------------------------- ### Meter Retrieval Functions Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Functions to get the default meter. ```APIDOC ## get_default_meter ### Description Retrieves the default OpenTelemetry meter. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R mtr <- get_meter() ``` ### Response #### Success Response (Meter Object) - **mtr** (object) - The default meter object. #### Response Example ``` # Message indicating an error if meter cannot be retrieved OpenTelemetry error: nope ``` ## get_meter_dev ### Description Development function to retrieve the default meter, may provide more detailed error information. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R get_meter_dev() ``` ### Response #### Success Response (Meter Object) - **Output** (object) - The default meter object. #### Response Example ``` # Potential error output if meter cannot be retrieved Error in `get_default_meter_provider()`: ! x ``` ``` -------------------------------- ### Handle NULL Input Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/checks.md The as_string function does not accept NULL input unless explicitly allowed (e.g., with null = TRUE). This example shows the default behavior where NULL is rejected. ```R as_string(s4, null = FALSE) ``` -------------------------------- ### Get Default Meter Provider Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Retrieves the default meter provider. This is the entry point for obtaining meters. ```R get_default_meter_provider() ``` -------------------------------- ### Span Management Functions Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Functions for starting, ending, and managing spans. ```APIDOC ## start_local_active_span ### Description Starts a new span and makes it the active span in the current context. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R span4 <- start_local_active_span() ``` ### Response #### Success Response (Span Object) - **span4** (object) - The newly created and activated span. #### Response Example ``` # Message indicating an error if span cannot be started OpenTelemetry error: nope ``` ## start_local_active_span_dev ### Description Development version of `start_local_active_span`, may provide more detailed error information. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R start_local_active_span_dev() ``` ### Response #### Success Response (Span Object) - **Output** (object) - The newly created and activated span. #### Response Example ``` # Potential error output if span cannot be started Error in `get_tracer()`: ! nope ``` ## start_span ### Description Starts a new span. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R sessx <- start_span() ``` ### Response #### Success Response (Span Object) - **sessx** (object) - The newly created span. #### Response Example ``` # Message indicating an error if span cannot be started OpenTelemetry error: nope ``` ## start_span_dev ### Description Development version of `start_span`, may provide more detailed error information. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R start_span_dev() ``` ### Response #### Success Response (Span Object) - **Output** (object) - The newly created span. #### Response Example ``` # Potential error output if span cannot be started Error in `get_tracer()`: ! nope ``` ## end_span ### Description Ends the specified span. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters - **span** (object) - Required - The span to end. ### Request Example ```R end_span(span) ``` ### Response #### Success Response (NULL) - **Output** (NULL) - Indicates successful completion. #### Response Example ``` # Message indicating an error if span cannot be ended OpenTelemetry error: not yet ``` ## end_span_dev ### Description Development version of `end_span`, may provide more detailed error information. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters - **span** (object) - Required - The span to end. ### Request Example ```R end_span_dev(span) ``` ### Response #### Success Response (NULL) - **Output** (NULL) - Indicates successful completion. #### Response Example ``` # Potential error output if span cannot be ended Error in `identity()`: ! not yet ``` ``` -------------------------------- ### Logger Retrieval Functions Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Functions to get the default logger. ```APIDOC ## get_default_logger ### Description Retrieves the default OpenTelemetry logger. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R lgr <- get_logger() ``` ### Response #### Success Response (Logger Object) - **lgr** (object) - The default logger object. #### Response Example ``` # Message indicating an error if logger cannot be retrieved OpenTelemetry error: nope ``` ## get_logger_dev ### Description Development function to retrieve the default logger, may provide more detailed error information. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R get_logger_dev() ``` ### Response #### Success Response (Logger Object) - **Output** (object) - The default logger object. #### Response Example ``` # Potential error output if logger cannot be retrieved Error in `get_default_logger_provider()`: ! x ``` ``` -------------------------------- ### Tracer Provider Management Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/defaults.md Functions for getting and setting the default OpenTelemetry tracer provider. ```APIDOC ## get_default_tracer_provider ### Description Retrieves the default OpenTelemetry tracer provider. ### Method GET ### Endpoint /r-lib/otel/get_default_tracer_provider ### Request Example ```r tp <- get_default_tracer_provider() ``` ### Response #### Success Response (200) - **tp** (object) - The default tracer provider object. #### Response Example ```r # Example response structure (actual object may vary) ``` ## setup_default_tracer_provider ### Description Sets up the default OpenTelemetry tracer provider. This function can encounter various errors related to exporter configuration. ### Method POST ### Endpoint /r-lib/otel/setup_default_tracer_provider ### Parameters #### Query Parameters - **OTEL_R_TRACES_EXPORTER** (string) - Optional - Specifies the trace exporter to use. Can be an environment variable. ### Request Example ```r setup_default_tracer_provider() ``` ### Response #### Success Response (200) - This function primarily signals success through the absence of errors or warnings. #### Error Handling Examples - **OpenTelemetry error: nope** - **Warning: OpenTelemetry: Jaeger trace exporter is not supported yet** - **Warning: OpenTelemetry: Zipkin trace exporter is not supported yet** - **Error: Unknown OpenTelemetry exporter from OTEL_R_TRACES_EXPORTER environment variable: invalid** - **Error: Cannot set trace exporter bad_package::tracer_provider from OTEL_R_TRACES_EXPORTER environment variable, cannot load package bad_package.** - **Error: Cannot set trace exporter otel::no_such_object from OTEL_R_TRACES_EXPORTER environment variable, cannot find provider no_such_object in package otel.** - **Error: Cannot set trace exporter otel::is_string from OTEL_R_TRACES_EXPORTER environment variable, it is not a list or environment with a 'new' member.** ``` -------------------------------- ### Get Default Tracer Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Retrieve the default tracer using `get_tracer()`. The `_dev` version can indicate problems with the tracer provider. ```R trc <- get_tracer() ``` ```R get_tracer_dev() ``` -------------------------------- ### Check if Logging is Enabled Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Use `is_logging_enabled()` to determine if logging is configured. The `_dev` version can reveal specific issues with logger setup. ```R is_logging_enabled() ``` ```R is_logging_enabled_dev() ``` -------------------------------- ### Start and Activate Local Span for Function Tracing Source: https://context7.com/r-lib/otel/llms.txt Use `start_local_active_span` to trace function execution. The span automatically ends when the function scope exits. Supports adding attributes for detailed context. ```r # Basic function tracing process_data <- function(data) { otel::start_local_active_span("process_data") # Your processing logic here result <- transform(data) # Span automatically ends when function exits return(result) } ``` ```r # With attributes and custom options analyze_dataset <- function(dataset, method = "default") { otel::start_local_active_span( name = "analyze_dataset", attributes = list( "dataset.rows" = nrow(dataset), "dataset.cols" = ncol(dataset), "analysis.method" = method ) ) # Perform analysis result <- summary(dataset) return(result) } ``` ```r # Nested spans create parent-child relationships outer_function <- function() { otel::start_local_active_span("outer") inner_function() # Creates child span } inner_function <- function() { otel::start_local_active_span("inner") # This span is a child of "outer" } ``` ```r # Run with tracing enabled # OTEL_TRACES_EXPORTER=stdout Rscript -e 'outer_function()' ``` -------------------------------- ### Get Default Meter Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Access the default meter using `get_meter()`. The `_dev` version can highlight issues with the meter provider. ```R mtr <- get_meter() ``` ```R get_meter_dev() ``` -------------------------------- ### Meter Provider Management Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/defaults.md Functions for getting and setting the default OpenTelemetry meter provider. ```APIDOC ## get_default_meter_provider ### Description Retrieves the default OpenTelemetry meter provider. ### Method GET ### Endpoint /r-lib/otel/get_default_meter_provider ### Request Example ```r mp <- get_default_meter_provider() ``` ### Response #### Success Response (200) - **mp** (object) - The default meter provider object. #### Response Example ```r # Example response structure (actual object may vary) ``` ## setup_default_meter_provider ### Description Sets up the default OpenTelemetry meter provider. This function can encounter various errors related to exporter configuration. ### Method POST ### Endpoint /r-lib/otel/setup_default_meter_provider ### Parameters #### Query Parameters - **OTEL_R_METRICS_EXPORTER** (string) - Optional - Specifies the metrics exporter to use. Can be an environment variable. ### Request Example ```r setup_default_meter_provider() ``` ### Response #### Success Response (200) - This function primarily signals success through the absence of errors or warnings. #### Error Handling Examples - **Warning: OpenTelemetry: Prometheus trace exporter is not supported yet** - **Error: Unknown OpenTelemetry exporter from OTEL_R_METRICS_EXPORTER environment variable: invalid** - **Error: Cannot set metrics exporter bad_package::meter_provider from OTEL_R_METRICS_EXPORTER environment variable, cannot load package bad_package.** - **Error: Cannot set metrics exporter otel::no_such_object from OTEL_R_METRICS_EXPORTER environment variable, cannot find provider no_such_object in package otel.** - **Error: Cannot set metrics exporter otel::is_string from OTEL_R_METRICS_EXPORTER environment variable, it is not a list or environment with a 'new' member.** ``` -------------------------------- ### Start Span Without Activation for Manual Management Source: https://context7.com/r-lib/otel/llms.txt Use `start_span` for manual span control. Spans must be explicitly ended using `end_span`. `local_active_span` can be used to temporarily activate a span within a scope. ```r # Manual span management process_async <- function() { # Start span without activation spn <- otel::start_span("async_operation") # Always end span, even on error on.exit(otel::end_span(spn), add = TRUE) # Manually activate for specific scopes helper1 <- function() { otel::local_active_span(spn) # spn is active here, child spans will be children of spn child <- otel::start_local_active_span("helper1_work") } helper2 <- function() { otel::local_active_span(spn) child <- otel::start_local_active_span("helper2_work") } helper1() helper2() } ``` ```r # Using with_active_span for expression-scoped activation run_with_span <- function() { spn <- otel::start_span("parent_span") on.exit(otel::end_span(spn), add = TRUE) otel::with_active_span(spn, { # Code here runs with spn as active span otel::start_local_active_span("child_span") result <- expensive_computation() }) return(result) } ``` -------------------------------- ### Tracer Provider API Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Provides methods to get the default tracer provider and manage tracers. ```APIDOC ## Tracer Provider API ### Description Manages tracer instances and provides access to the default tracer provider. ### Methods - **get_default_tracer_provider()**: Returns the default tracer provider. - **get_tracer(name, version, schema_url, attributes)**: Retrieves a tracer instance. - **flush()**: Flushes any pending telemetry data. - **get_spans()**: Retrieves all spans managed by the provider. ``` -------------------------------- ### Logger Provider Management Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/defaults.md Functions for getting and setting the default OpenTelemetry logger provider. ```APIDOC ## get_default_logger_provider ### Description Retrieves the default OpenTelemetry logger provider. ### Method GET ### Endpoint /r-lib/otel/get_default_logger_provider ### Request Example ```r lp <- get_default_logger_provider() ``` ### Response #### Success Response (200) - **lp** (object) - The default logger provider object. #### Response Example ```r # Example response structure (actual object may vary) ``` ## setup_default_logger_provider ### Description Sets up the default OpenTelemetry logger provider. This function can encounter various errors related to exporter configuration. ### Method POST ### Endpoint /r-lib/otel/setup_default_logger_provider ### Parameters #### Query Parameters - **OTEL_R_LOGS_EXPORTER** (string) - Optional - Specifies the logs exporter to use. Can be an environment variable. ### Request Example ```r setup_default_logger_provider() ``` ### Response #### Success Response (200) - This function primarily signals success through the absence of errors or warnings. #### Error Handling Examples - **OpenTelemetry error: nope** - **Error: Unknown OpenTelemetry exporter from OTEL_R_LOGS_EXPORTER environment variable: invalid** - **Error: Cannot set logs exporter bad_package::logger_provider from OTEL_R_LOGS_EXPORTER environment variable, cannot load package bad_package.** - **Error: Cannot set logs exporter otel::no_such_object from OTEL_R_LOGS_EXPORTER environment variable, cannot find provider no_such_object in package otel.** - **Error: Cannot set logs exporter otel::is_string from OTEL_R_LOGS_EXPORTER environment variable, it is not a list or environment with a 'new' member.** ``` -------------------------------- ### Handle Unsupported Types with as_attributes Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/as-attributes.md When `as_attributes()` encounters unsupported types, it converts them to strings. This example shows how a data frame is converted to a character vector of row strings. ```r as_attributes(list(mtcars[1:2, 1:4])) ``` -------------------------------- ### Get Default Logger Provider Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/defaults.md Retrieves the default logger provider. This function may return an error if the provider is not properly configured. ```r tp <- get_default_logger_provider() ``` -------------------------------- ### Get Default Tracer Provider Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/defaults.md Retrieves the default tracer provider. This function may return an error if the provider is not properly configured. ```r tp <- get_default_tracer_provider() ``` -------------------------------- ### Get environment variable with default Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/utils.md Use `get_env_count` to retrieve an environment variable's value as an integer. It requires a non-negative integer for the default value. ```R get_env_count("FOO", -1L) ``` ```R get_env_count("FOO", "bad-default") ``` -------------------------------- ### Get Default Meter Provider Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/defaults.md Retrieves the default meter provider. This function may return an error if the provider is not properly configured. ```r tp <- get_default_meter_provider() ``` -------------------------------- ### Get Default Tracer Name Source: https://context7.com/r-lib/otel/llms.txt Gets the default tracer name, which is automatically deduced from the package name for instrumented packages. Used automatically when creating spans. ```r # In package code, set tracer name at package level otel_tracer_name <- "com.example.mypackage" # The tracer name is used automatically otel::start_local_active_span("my_function") # Uses "com.example.mypackage" as the tracer/instrumentation scope ``` -------------------------------- ### Access setup_r_trace Hook Body Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/onload.md Retrieve the function body for the first element of the `res` output, which represents the user hook for loading. ```r res[[1]] ``` -------------------------------- ### Enable All Telemetry Signals (R) Source: https://context7.com/r-lib/otel/llms.txt Enable all telemetry signals including traces, logs, and metrics by setting their respective exporters to HTTP. ```bash export OTEL_TRACES_EXPORTER=http export OTEL_LOGS_EXPORTER=http export OTEL_METRICS_EXPORTER=http ``` -------------------------------- ### Inspect Cache Contents with otel_restore_cache Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/onload.md Use `as.list(the)` to view the contents of the OpenTelemetry cache environment after restoring. ```r as.list(the) ``` -------------------------------- ### Configure HTTP/OTLP Trace Export (R) Source: https://context7.com/r-lib/otel/llms.txt Configure trace export via HTTP/OTLP to a collector. Ensure the endpoint is correctly set to your collector's address. ```bash export OTEL_TRACES_EXPORTER=http export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 ``` -------------------------------- ### Active Span Retrieval Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Functions to get the currently active span. ```APIDOC ## get_active_span ### Description Retrieves the currently active span. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R spn2 <- get_active_span() ``` ### Response #### Success Response (Span Object) - **spn2** (object) - The active span object. #### Response Example ``` # Message indicating an error if active span cannot be retrieved OpenTelemetry error: ouch! ``` ## get_active_span_dev ### Description Development version of `get_active_span`, may provide more detailed error information. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R get_active_span_dev() ``` ### Response #### Success Response (Span Object) - **Output** (object) - The active span object. #### Response Example ``` # Potential error output if active span cannot be retrieved Error in `get_tracer()`: ! nope! ``` ``` # Alternative potential error output Error in `trc$get_active_span()`: ! nope! ``` ``` -------------------------------- ### Span Context Retrieval Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Functions to get the current span context. ```APIDOC ## get_current_span_context ### Description Retrieves the context of the currently active span. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R spc2 <- get_active_span_context() ``` ### Response #### Success Response (Span Context Object) - **spc2** (object) - The span context object. #### Response Example ``` # Message indicating an error if span context cannot be retrieved OpenTelemetry error: nope! ``` ## get_active_span_context_dev ### Description Development version of `get_active_span_context`, may provide more detailed error information. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None ### Request Example ```R get_active_span_context_dev() ``` ### Response #### Success Response (Span Context Object) - **Output** (object) - The span context object. #### Response Example ``` # Potential error output if span context cannot be retrieved Error in `get_tracer()`: ! nope! ``` ``` # Alternative potential error output Error in `trc$get_active_span_context()`: ! nope! ``` ``` -------------------------------- ### Set Development Mode (R) Source: https://context7.com/r-lib/otel/llms.txt Enable development mode by setting the OTEL_ENV variable to 'dev'. In this mode, errors are thrown instead of being suppressed. ```bash export OTEL_ENV=dev ``` -------------------------------- ### Get Span Context Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Retrieves the context associated with a span. This context can be propagated. ```R trc$start_span()$get_context() ``` -------------------------------- ### Inspect Cache Contents with otel_save_cache Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/onload.md Use `as.list(env)` to view the contents of the OpenTelemetry cache environment after saving. ```r as.list(env) ``` -------------------------------- ### default_tracer_name Source: https://context7.com/r-lib/otel/llms.txt Gets the default tracer name, which is automatically deduced from the package name for instrumented packages. ```APIDOC ## default_tracer_name ### Description Gets the default tracer name, which is automatically deduced from the package name for instrumented packages. ### Method Not applicable (function call) ### Endpoint Not applicable (function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```r # In package code, set tracer name at package level otel_tracer_name <- "com.example.mypackage" # The tracer name is used automatically otel::start_local_active_span("my_function") # Uses "com.example.mypackage" as the tracer/instrumentation scope ``` ### Response #### Success Response (200) - **string** - The default tracer name. #### Response Example ```json { "example": "com.example.mypackage" } ``` ``` -------------------------------- ### Pack HTTP Context Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Packs HTTP context information. Use the `_dev` version for development environments. ```r pack_http_context() ``` ```r pack_http_context_dev() ``` -------------------------------- ### Create a general message string Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/utils.md Use `msg` to construct a general message string. This function is suitable for logging or displaying informational messages. ```R msg("just being busy") ``` ```R msg("nothing to see here") ``` -------------------------------- ### Enable Trace Export to Stdout (R) Source: https://context7.com/r-lib/otel/llms.txt Use this environment variable to enable trace export to standard output, which is useful for debugging purposes. ```bash export OTEL_TRACES_EXPORTER=stdout ``` -------------------------------- ### Handle Empty Character Vector Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/checks.md as_string expects a non-empty character vector. Providing an empty one will result in an error. ```R as_string(s2) ``` -------------------------------- ### Create Gauge Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Creates a gauge metric instrument. Gauges measure values that can arbitrarily change. ```R mtr$create_gauge("gge") ``` -------------------------------- ### Run integration test with otel environment Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/rtrace.md Execute an R script using callr::rscript with the otel environment loaded. This demonstrates the effect of instrumentation on execution flow. ```R callr::rscript(script, env = env) ``` -------------------------------- ### Create Counter Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Creates a counter metric instrument. Counters are used for cumulative measurements. ```R mtr$create_counter("ctr") ``` -------------------------------- ### Create Histogram Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Creates a histogram metric instrument. Histograms record observations and their distributions. ```R mtr$create_histogram("hst") ``` -------------------------------- ### Meter API Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Enables the creation of various metric instruments. ```APIDOC ## Meter API ### Description Represents a meter used for creating and managing metric instruments. ### Methods - **create_counter(name, description, unit)**: Creates a counter instrument. - **create_up_down_counter(name, description, unit)**: Creates an up-down counter instrument. - **create_histogram(name, description, unit)**: Creates a histogram instrument. - **create_gauge(name, description, unit)**: Creates a gauge instrument. ``` -------------------------------- ### Get Active Span Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Retrieve the currently active span using `get_active_span()`. The `_dev` version might indicate errors from the tracer or span retrieval. ```R spn2 <- get_active_span() ``` ```R get_active_span_dev() ``` ```R get_active_span_dev() ``` -------------------------------- ### Get Local Active Span Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Retrieve the local active span using `local_active_span(sess)`. The `_dev` version can indicate errors when activating a span. ```R local_active_span(sess) ``` ```R local_active_span_dev(sess) ``` -------------------------------- ### Get Current Span Context Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Fetch the active span's context with `get_active_span_context()`. The `_dev` version can reveal errors from the tracer or span context retrieval. ```R spc2 <- get_active_span_context() ``` ```R get_active_span_context_dev() ``` ```R get_active_span_context_dev() ``` -------------------------------- ### Visualize execution tree Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/rtrace.md Display the execution tree of traced functions using cli::tree. This provides a visual representation of nested function calls. ```R cli::tree(spnstree, root = root) ``` -------------------------------- ### Set Service Name (R) Source: https://context7.com/r-lib/otel/llms.txt Set the service name for your R application using the OTEL_SERVICE_NAME environment variable. This helps in identifying your application in observability backends. ```bash export OTEL_SERVICE_NAME=my-r-application ``` -------------------------------- ### Info Log Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Logs a message at the info severity level. Requires a logger instance. ```R logger$info(msg, span_context, attributes, ..., .envir) ``` -------------------------------- ### Get and Modify Active Span Source: https://context7.com/r-lib/otel/llms.txt Use `get_active_span` to retrieve the current span and add attributes or events from nested functions. This is useful for enriching trace data dynamically. ```r # Add attributes to active span from helper functions process_request <- function(request) { otel::start_local_active_span("process_request") validate_request(request) handle_request(request) } ``` ```r validate_request <- function(request) { spn <- otel::get_active_span() spn$set_attribute("request.size", length(request)) spn$set_attribute("request.type", class(request)[1]) if (!is_valid(request)) { spn$add_event("validation_failed", attributes = list( "reason" = "invalid format" )) stop("Invalid request") } spn$add_event("validation_passed") } ``` ```r handle_request <- function(request) { spn <- otel::get_active_span() spn$add_event("processing_started", attributes = list( "timestamp" = as.character(Sys.time()) )) # Process request... spn$add_event("processing_completed") } ``` -------------------------------- ### Handle Character Vector Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/checks.md as_string requires a string scalar. A character vector that is not a scalar will cause an error. ```R as_string(s3) ``` -------------------------------- ### Create Up-Down Counter Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Creates an up-down counter metric instrument. These counters can increase or decrease. ```R mtr$create_up_down_counter("ctr") ``` -------------------------------- ### Tracer API Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Enables the creation and management of spans. ```APIDOC ## Tracer API ### Description Represents a tracer used for creating and managing spans. ### Methods - **get_default_tracer_provider()$get_tracer()**: Gets the default tracer. - **start_span(name, attributes, links, options)**: Starts a new span. - **is_enabled()**: Checks if the tracer is enabled. - **flush()**: Flushes any pending telemetry data. ``` -------------------------------- ### Log a Warning Message Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Log a warning message using `log_warn(message)`. The `_dev` version can indicate problems with the logger's log method. ```R lgr2 <- log_warn("another nothing") ``` ```R log_warn_dev("nothing") ``` -------------------------------- ### Manage Distributed Tracing Context with HTTP Source: https://context7.com/r-lib/otel/llms.txt Functions for propagating trace context across processes and services using HTTP headers. Use `extract_http_context` on the server-side to retrieve context from incoming requests and `pack_http_context` on the client-side to prepare context for outgoing requests. ```r # Server-side: Extract context from incoming HTTP request handle_http_request <- function(req) { # Extract trace context from HTTP headers headers <- list( traceparent = req$headers$traceparent, tracestate = req$headers$tracestate ) parent_ctx <- otel::extract_http_context(headers) # Create span with remote parent otel::start_local_active_span( name = "handle_request", options = list(parent = parent_ctx) ) # Process request... process_request(req) } ``` ```r # Client-side: Pack context for outgoing HTTP request call_downstream_service <- function(endpoint, data) { otel::start_local_active_span("call_downstream") # Get HTTP headers for context propagation headers <- otel::pack_http_context() # Include in HTTP request httr::POST( endpoint, body = data, httr::add_headers(.headers = headers) ) } ``` ```r # Subprocess tracing with environment variables spawn_worker <- function(script) { # Get current trace context as headers ctx <- otel::pack_http_context() # Pass to subprocess via environment variables env <- c( Sys.getenv(), TRACEPARENT = ctx["traceparent"], TRACESTATE = ctx["tracestate"] ) processx::run("Rscript", script, env = env) } ``` -------------------------------- ### Log a Message Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Log a message using `log(message)`. The `_dev` version can show errors related to the logger's log method. ```R lgr2 <- log("another nothing") ``` ```R log_dev("nothing") ``` -------------------------------- ### Warn Log Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md Logs a message at the warn severity level. Requires a logger instance. ```R logger$warn(msg, span_context, attributes, ..., .envir) ``` -------------------------------- ### Restrict Telemetry to Specific Packages (R) Source: https://context7.com/r-lib/otel/llms.txt Restrict telemetry collection to specific R packages by listing them in the OTEL_R_EMIT_SCOPES environment variable. ```bash export OTEL_R_EMIT_SCOPES="mypackage,org.r-lib.*" ``` -------------------------------- ### Configure R-Specific Trace Exporter (R) Source: https://context7.com/r-lib/otel/llms.txt Set the R-specific trace exporter to stdout for debugging R-related traces. ```bash export OTEL_R_TRACES_EXPORTER=stdout ``` -------------------------------- ### Create an error message string Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/utils.md Use `errmsg` to construct a formatted error message string from multiple parts. This is useful for building descriptive error messages. ```R errmsg("this is a ", "message instead of an error") ``` -------------------------------- ### Log an Info Message Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Log a message at info level using `log_info(message)`. The `_dev` version might show errors related to the logger's log method. ```R lgr2 <- log_info("another nothing") ``` ```R log_info_dev("nothing") ``` -------------------------------- ### Log a Trace Message Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Log a message at trace level using `log_trace(message)`. The `_dev` version may indicate issues with the logger's log method. ```R lgr2 <- log_trace("another nothing") ``` ```R log_trace_dev("nothing") ``` -------------------------------- ### Gauge API Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/print.md API for recording gauges. ```APIDOC ## Gauge API ### Description Represents a gauge instrument used for recording current values. ### Methods - **(No specific methods listed in the provided text for Gauge creation, only creation via meter)** ``` -------------------------------- ### Convert to String Scalar Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/checks.md Use as_string to convert a string to a string scalar. Ensure the input is a valid string. ```R as_string(s1) ``` -------------------------------- ### Check Code Formatting with 'air' Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/formatting.md Use this command to check if the code in a package adheres to formatting standards. It runs the 'air format --check' command and suppresses errors if the check fails. ```R invisible(processx::run("air", c("format", "--check", pkg), echo = TRUE, error_on_status = FALSE)) ``` -------------------------------- ### Execute with Active Span Source: https://github.com/r-lib/otel/blob/main/tests/testthat/_snaps/api.md Run code within an active span context using `with_active_span(sess, expression)`. The `_dev` version may show errors during span activation. ```R ret <- with_active_span(sess, 1 + 1) ``` ```R with_active_span_dev(sess, 1 + 1) ``` -------------------------------- ### Zero Code Instrumentation Source: https://context7.com/r-lib/otel/llms.txt Automatically instrument R packages without modifying source code using environment variables. ```APIDOC ## Zero Code Instrumentation ### Description Automatically instrument R packages without modifying source code using environment variables. ### Method Environment Variables ### Endpoint N/A ### Parameters #### Environment Variables - **OTEL_TRACES_EXPORTER** (string) - Specifies the exporter for traces (e.g., `http`). - **OTEL_R_INSTRUMENT_PKGS** (string) - Comma-separated list of packages to instrument (e.g., `dplyr,tidyr`). - **OTEL_R_INSTRUMENT_PKGS_[PKG_NAME]_INCLUDE** (string) - Comma-separated list of specific functions to include for instrumentation within a package (e.g., `filter,select,mutate` for `dplyr`). - **OTEL_R_INSTRUMENT_PKGS_[PKG_NAME]_EXCLUDE** (string) - Comma-separated list of specific functions to exclude from instrumentation within a package (e.g., `*_join` for `dplyr`). ### Request Example ```bash # Instrument all functions in dplyr and tidyr packages OTEL_TRACES_EXPORTER=http OTEL_R_INSTRUMENT_PKGS=dplyr,tidyr Rscript script.R # Instrument only specific functions in dplyr OTEL_R_INSTRUMENT_PKGS_DPLYR_INCLUDE=filter,select,mutate # Exclude specific functions in dplyr OTEL_R_INSTRUMENT_PKGS_DPLYR_EXCLUDE=*_join ``` ### Example Script (`script.R`) ```r library(dplyr) library(otel) # All dplyr operations are automatically traced mtcars %>% filter(mpg > 20) %>% select(mpg, cyl, wt) %>% mutate(efficiency = mpg / wt) ``` ### Response #### Success Response (200) N/A (Instrumentation happens at runtime) #### Response Example N/A ```