Project: Grafana Pyroscope (Observability and Analysis / Observability)
File: rust.md

title: "Rust" menuTitle: "Rust" description: "Instrumenting Rust applications for continuous profiling." weight: 60 aliases: /docs/phlare/latest/configure-client/language-sdks/rust Optimize your Rust applications with our advanced Rust Profiler. In collaboration with Pyroscope, it offers real-time profiling capabilities, shedding light on the intricacies of your Rust codebase. This integration is invaluable for developers seeking to enhance performance, reduce resource usage, and achieve efficient code execution in Rust applications. {{< admonition type="note" >}} Refer to for a list of profile types supported by Rust. {{< /admonition >}} To capture and analyze profiling data, you need either a hosted Pyroscope OSS server or a hosted (requires a free Grafana Cloud account). The Pyroscope server can be a local server for development or a remote server for production use. Add the `pyroscope` and `pyroscope_pprofrs` crates to your Cargo.toml: ```bash cargo add pyroscope cargo add pyroscope_pprofrs ``` At a minimum, you need to provide the URL of the Pyroscope server and the name of your application. You also need to configure a profiling backend. For Rust, you can use . ```rust // Configure profiling backend let pprofconfig = PprofConfig::new().samplerate(100); let backendimpl = pprofbackend(pprof_config); // Configure Pyroscope Agent let agent = PyroscopeAgent::builder("http://localhost:4040", "myapp") .backend(backend_impl) .build()?; ``` Users of a secured backend will need to provide authentication details. Grafana Cloud uses Basic authentication. Your username is a numeric value which you can get from the "Details Page" for Pyroscope from your stack on grafana.com. On this same page, create a token and use it as the Basic authentication password. The configuration then would look similar to: ```rust fn main() -> Result<()> { std::env::setvar("RUSTLOG", "debug"); prettyenvlogger::init_timed(); let user = std::env::var("USER").unwrap(); let password = std::env::var("PASSWORD").unwrap(); let url = std::env::var("PYROSCOPE_URL").unwrap(); let samplerate = std::env::var("SAMPLERATE").unwrap().tostring().parse().unwrap(); let application_name = "example.basic"; let agent = PyroscopeAgent::builder(url, applicationname.tostring()) .basicauth(user, password).backend(pprofbackend(PprofConfig::new().sample_rate(samplerate))) .tags([("app", "Rust"), ("TagB", "ValueB")].to_vec()) .build()?; ``` You can start profiling by invoking the following code: ```rust let agent_running = agent.start().unwrap(); ``` The agent can be stopped at any point, and it'll send a last report to the server. The agent can be restarted at a later point. ```rust let agent_ready =

``` It's recommended to shut down the agent before exiting the application. A last request to the server might be missed if the agent is not shutdown properly. ```rust agent_ready.shutdown(); ``` Tags can be added or removed after the agent is started. As of 0.5.0, the Pyroscope Agent supports tagging within threads. Check the and examples for detailed usage. After the agent is started, the `tag_wrapper` function becomes available. `tag_wrapper` returns a tuple of functions to add and remove tags to the agent across thread boundaries. This function is available as long as the agent is running and can be called multiple times. ```rust // Start Profiling let agent_running = agent.start().unwrap(); // Generate Tag Wrapper functions let (addtag, removetag) = agentrunning.tagwrapper(); // Profiled code (with no tags) // Add tags to the agent addtag("key".tostring(), "value".to_string()); // This portion will be profiled with the specified tag. // Remove tags from the agent removetag("key".tostring(), "value".to_string()); // Stop the agent let agentready = runningagent.stop(); ``` The agent accepts additional initial parameters: Backend: Profiling backend. For Rust, it's Sample Rate: Sampling Frequency in Hertz. Default is 100. Tags: Initial tags. ```rust // Configure Profiling backend let pprofconfig = PprofConfig::new().samplerate(100); let pprofbackend = Pprof::new(pprofconfig); // Configure Pyroscope Agent let agent = PyroscopeAgent::builder("http://localhost:4040", "myapp") // Profiling backend .backend(pprof_backend) // Sample rate .sample_rate(100) // Tags .tags(vec![("env", "dev")]) // Create the agent .build()?; ``` Backend: The Pyroscope Agent uses as a backend. As a result, the for pprof-rs also applies. As of 0.5.0, the Pyroscope Agent supports tagging within threads. Check the and examples for usage. Timer: epoll (for Linux) and kqueue (for macOS) are required for a more precise timer. Shutdown: The Pyroscope Agent might take some time (usually less than 10 seconds) to shut down properly and drop its threads. For a proper shutdown, it's recommended that you run the `shutdown` function before dropping the agent. Relevant Links - : Minimal configuration example. : Example using Tags. : Example using Async code with Tokio. : Example using multiple threads. : Example with logging to stdout. : Example with an invalid server address. : Simple Rust application that uses the Pyroscope Library. : A multi-instances web service running on Docker.