github.com/grafana/pyroscope@v1.18.0/docs/sources/configure-client/language-sdks/rust.md (about)

     1  ---
     2  title: "Rust"
     3  menuTitle: "Rust"
     4  description: "Instrumenting Rust applications for continuous profiling."
     5  weight: 60
     6  aliases:
     7    - /docs/phlare/latest/configure-client/language-sdks/rust
     8  ---
     9  
    10  # Rust
    11  
    12  Optimize your Rust applications with our advanced Rust Profiler.
    13  In collaboration with Pyroscope, it offers real-time profiling capabilities, shedding light on the intricacies of your Rust codebase.
    14  This integration is invaluable for developers seeking to enhance performance, reduce resource usage, and achieve efficient code execution in Rust applications.
    15  
    16  {{< admonition type="note" >}}
    17  Refer to [Available profiling types](https://grafana.com/docs/pyroscope/<PYROSCOPE_VERSION>/configure-client/profile-types/) for a list of profile types supported by Rust.
    18  {{< /admonition >}}
    19  
    20  ## Before you begin
    21  
    22  To capture and analyze profiling data, you need either a hosted Pyroscope OSS server or a hosted [Pyroscope instance with Grafana Cloud Profiles](/products/cloud/profiles-for-continuous-profiling/) (requires a free Grafana Cloud account).
    23  
    24  The Pyroscope server can be a local server for development or a remote server for production use.
    25  
    26  ## Add Rust profiling to your application
    27  
    28  Add the `pyroscope` and `pyroscope_pprofrs` crates to your Cargo.toml:
    29  
    30  ```bash
    31  cargo add pyroscope
    32  cargo add pyroscope_pprofrs
    33  ```
    34  
    35  ## Configure the Rust client
    36  
    37  At a minimum, you need to provide the URL of the Pyroscope server and the name
    38  of your application. You also need to configure a profiling backend. For Rust,
    39  you can use [pprof-rs](https://github.com/pyroscope-io/pyroscope-rs/tree/main/pyroscope_backends/pyroscope_pprofrs).
    40  
    41  ```rust
    42  // Configure profiling backend
    43  let pprof_config = PprofConfig::new().sample_rate(100);
    44  let backend_impl = pprof_backend(pprof_config);
    45  
    46  // Configure Pyroscope Agent
    47  let agent = PyroscopeAgent::builder("http://localhost:4040", "myapp")
    48      .backend(backend_impl)
    49      .build()?;
    50  ```
    51  
    52  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:
    53  
    54  ```rust
    55  fn  main() ->  Result<()> {
    56  std::env::set_var("RUST_LOG", "debug");
    57  pretty_env_logger::init_timed();
    58  let user = std::env::var("USER").unwrap();
    59  let password = std::env::var("PASSWORD").unwrap();
    60  let url = std::env::var("PYROSCOPE_URL").unwrap();
    61  let samplerate = std::env::var("SAMPLE_RATE").unwrap().to_string().parse().unwrap();
    62  let application_name = "example.basic";
    63  
    64  let agent = PyroscopeAgent::builder(url, application_name.to_string())
    65      .basic_auth(user, password).backend(pprof_backend(PprofConfig::new().sample_rate(samplerate)))
    66      .tags([("app", "Rust"), ("TagB", "ValueB")].to_vec())
    67      .build()?;
    68  ```
    69  
    70  You can start profiling by invoking the following code:
    71  
    72  ```rust
    73  let agent_running = agent.start().unwrap();
    74  ```
    75  
    76  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.
    77  
    78  ```rust
    79  let agent_ready = agent.stop().unwrap();
    80  ```
    81  
    82  It's recommended to shut down the agent before exiting the application. A last
    83  request to the server might be missed if the agent is not shutdown properly.
    84  
    85  ```rust
    86  agent_ready.shutdown();
    87  ```
    88  
    89  ### Locate the URL, user, and password in Grafana Cloud Profiles
    90  
    91  [//]: # 'Shared content for URl location in Grafana Cloud Profiles'
    92  [//]: # 'This content is located in /pyroscope/docs/sources/shared/locate-url-pw-user-cloud-profiles.md'
    93  
    94  {{< docs/shared source="pyroscope" lookup="locate-url-pw-user-cloud-profiles.md" version="latest" >}}
    95  
    96  ## Add profiling labels to Rust applications
    97  
    98  Tags can be added or removed after the agent is started. As of 0.5.0, the
    99  Pyroscope Agent supports tagging within threads. Check the [tags](https://github.com/pyroscope-io/pyroscope-rs/blob/main/examples/tags.rs) and [multi-thread](https://github.com/pyroscope-io/pyroscope-rs/blob/main/examples/multi-thread.rs) examples for detailed usage.
   100  
   101  After the agent is started, the `tag_wrapper` function becomes available.
   102  `tag_wrapper` returns a tuple of functions to add and remove tags to the agent
   103  across thread boundaries. This function is available as long as the agent is
   104  running and can be called multiple times.
   105  
   106  ```rust
   107  // Start Profiling
   108  let agent_running = agent.start().unwrap();
   109  
   110  // Generate Tag Wrapper functions
   111  let (add_tag, remove_tag) = agent_running.tag_wrapper();
   112  
   113  // Profiled code (with no tags)
   114  
   115  // Add tags to the agent
   116  add_tag("key".to_string(), "value".to_string());
   117  
   118  // This portion will be profiled with the specified tag.
   119  
   120  // Remove tags from the agent
   121  remove_tag("key".to_string(), "value".to_string());
   122  
   123  // Stop the agent
   124  let agent_ready = running_agent.stop();
   125  ```
   126  
   127  ## Rust client configuration options
   128  
   129  The agent accepts additional initial parameters:
   130  
   131  - **Backend**: Profiling backend. For Rust, it's [pprof-rs](https://github.com/pyroscope-io/pyroscope-rs/tree/main/pyroscope_backends/pyroscope_pprofrs)
   132  - **Sample Rate**: Sampling Frequency in Hertz. Default is 100.
   133  - **Tags**: Initial tags.
   134  
   135  ```rust
   136  // Configure Profiling backend
   137  let pprof_config = PprofConfig::new().sample_rate(100);
   138  let pprof_backend = Pprof::new(pprof_config);
   139  
   140  // Configure Pyroscope Agent
   141  let agent =
   142  PyroscopeAgent::builder("http://localhost:4040", "myapp")
   143  // Profiling backend
   144  .backend(pprof_backend)
   145  // Sample rate
   146  .sample_rate(100)
   147  // Tags
   148  .tags(vec![("env", "dev")])
   149  // Create the agent
   150  .build()?;
   151  ```
   152  
   153  ## Technical details
   154  
   155  - **Backend**: The Pyroscope Agent uses [pprof-rs](https://github.com/tikv/pprof-rs) as a backend. As a result, the [limitations](https://github.com/tikv/pprof-rs#why-not-) for pprof-rs also applies.
   156  As of 0.5.0, the Pyroscope Agent supports tagging within threads. Check the [tags](https://github.com/pyroscope-io/pyroscope-rs/blob/main/examples/tags.rs) and [multi-thread](https://github.com/pyroscope-io/pyroscope-rs/blob/main/examples/multi-thread.rs) examples for usage.
   157  - **Timer**: epoll (for Linux) and kqueue (for macOS) are required for a more precise timer.
   158  - **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.
   159  
   160  - **Relevant Links**
   161    - [GitHub Repository](https://github.com/pyroscope-io/pyroscope-rs)
   162    - [Cargo crate](https://crates.io/crates/pyroscope)
   163    - [Crate documentation](https://docs.rs/pyroscope/latest/pyroscope/index.html)
   164  
   165  ## Examples
   166  
   167  ### Usage examples
   168  
   169  - [**basic**](https://github.com/pyroscope-io/pyroscope-rs/blob/main/examples/basic.rs): Minimal configuration example.
   170  - [**tags**](https://github.com/pyroscope-io/pyroscope-rs/blob/main/examples/tags.rs): Example using Tags.
   171  - [**async**](https://github.com/pyroscope-io/pyroscope-rs/blob/main/examples/async.rs): Example using Async code with Tokio.
   172  - [**multi-thread**](https://github.com/pyroscope-io/pyroscope-rs/blob/main/examples/multi-thread.rs): Example using multiple threads.
   173  - [**with-logger**](https://github.com/pyroscope-io/pyroscope-rs/blob/main/examples/with-logger.rs): Example with logging to stdout.
   174  - [**error**](https://github.com/pyroscope-io/pyroscope-rs/blob/main/examples/error.rs): Example with an invalid server address.
   175  
   176  #### Stand-alone examples
   177  
   178  - [**basic**](https://github.com/grafana/pyroscope/tree/main/examples/language-sdk-instrumentation/rust/basic): Simple Rust application that uses the Pyroscope Library.
   179  - [**rideshare**](https://github.com/grafana/pyroscope/tree/main/examples/language-sdk-instrumentation/rust/rideshare): A multi-instances web service running on Docker.