{"id":24864145,"url":"https://github.com/reoring/trasy","last_synced_at":"2025-06-22T22:38:02.676Z","repository":{"id":237619216,"uuid":"794907372","full_name":"reoring/trasy","owner":"reoring","description":"Trasy is a Rust library designed to facilitate rich error handling by integrating traced errors with backtraces.","archived":false,"fork":false,"pushed_at":"2024-05-03T08:48:53.000Z","size":35,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-27T17:59:02.270Z","etag":null,"topics":["backtrace","rust","tracing"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/reoring.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-05-02T07:42:51.000Z","updated_at":"2024-07-18T04:07:53.000Z","dependencies_parsed_at":"2024-05-02T21:05:11.105Z","dependency_job_id":"695bfc74-ee07-4a92-8210-6fcee606cd8f","html_url":"https://github.com/reoring/trasy","commit_stats":null,"previous_names":["reoring/trasy"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reoring%2Ftrasy","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reoring%2Ftrasy/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reoring%2Ftrasy/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/reoring%2Ftrasy/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/reoring","download_url":"https://codeload.github.com/reoring/trasy/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":236600331,"owners_count":19175170,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backtrace","rust","tracing"],"created_at":"2025-01-31T23:49:55.520Z","updated_at":"2025-01-31T23:49:56.059Z","avatar_url":"https://github.com/reoring.png","language":"Rust","readme":"# Trasy\n\nTrasy is a Rust library designed to facilitate rich error handling by integrating traced errors with backtraces. It is particularly useful in applications where detailed context and error origin tracing are critical for debugging and error resolution.\n\n## Features\n\n- **Traced Errors**: Integrates with `tracing_error::SpanTrace` to capture and display the context of errors.\n- **Backtrace Support**: Optionally attaches backtraces to errors to provide a detailed stack trace when an error occurs.\n- **Macros for Convenience**: Includes macros `error!` and `bail!` to simplify error creation and propagation.\n\n## Installation\n\nAdd `Trasy` to your Cargo.toml:\n\n```toml\n[dependencies]\ntrasy = \"0.1.0\"  # Use the latest version\n```\n\n\n## Environment Setup and Instrumentation\n\n### Enabling Backtrace\n\nTo fully utilize the backtrace functionality in Rust, you need to set the `RUST_BACKTRACE` environment variable. This can be done by running your application with the variable set to `1`:\n\n```bash\nRUST_BACKTRACE=1 cargo run\n```\n\nThis setting tells Rust to capture detailed backtraces when errors occur.\n\n### Using `#[instrument]` with Tracing\n\nTo enhance the diagnostics of your Rust applications, use the `#[instrument]` attribute from the `tracing` crate. This attribute automatically instruments your functions, recording the entry and exit of calls, and captures arguments to the functions:\n\n```rust\nuse tracing::instrument;\n\n#[instrument]\nfn compute_value(x: i32, y: i32) -\u003e i32 {\n    x + y\n}\n```\n\nUsing `#[instrument]` provides valuable insights into function calls and can be coupled with error handling to trace error sources more effectively.\n\n## User Outcome\n\nUsing `TrasyError`, developers can get and read both span trace and backtrace simultaneously, providing a dual-layer of error context that enhances debugging capabilities. The output when an error occurs would look something like this:\n\n**Error Context:**\n\n```\nAn error occurred:\nError Context:\n   0: tracing::foo\n             at src/main.rs:158\n   1: tracing::bar\n           with hoge=\"hoge\"\n             at src/main.rs:153\n```\n\n**Backtrace:**\n\n```\nBacktrace:\nBacktrace [{ fn: \"tracing::foo::{{closure}}\", file: \"./src/main.rs\", line: 163 }, { fn: \"tracing::foo\", file: \"./src/main.rs\", line: 158 }, { fn: \"tracing::bar\", file: \"./src/main.rs\", line: 155 }, ...]\n```\n\n## Usage\n\n### Basic Usage\n\nTo use `Trasy`, first import it along with its macros:\n\n```rust\nuse trasy::{TrasyError, error, bail};\n```\n\nCreate and propagate errors easily using the `error!` macro:\n\n```rust\nfn example_function() -\u003e Result\u003c(), TrasyError\u003cString\u003e\u003e {\n    let some_result = some_error_prone_operation();\n\n    some_result.map_err(|e| error!(e))\n}\n```\n\n### Using Backtrace\n\nTo attach a backtrace to your error, simply use the error in a context where the backtrace will be captured:\n\n```rust\nfn example_function() -\u003e Result\u003c(), TrasyError\u003cString\u003e\u003e {\n    let some_result = another_error_prone_operation();\n    some_result.map_err(|e| bail!(e))\n}\n```\n\n### Implementing for Custom Error Types\n\n`Trasy` can wrap any error type that implements `std::fmt::Debug` and `std::fmt::Display`. Here's how you can implement it for a custom error type:\n\n```rust\n#[derive(Debug)]\nenum MyError {\n    Io(std::io::Error),\n    Num(std::num::ParseIntError),\n}\n\nimpl fmt::Display for MyError {\n    fn fmt(\u0026self, f: \u0026mut fmt::Formatter\u003c'_\u003e) -\u003e fmt::Result {\n        match *self {\n            MyError::Io(ref err) =\u003e write!(f, \"IO error: {}\", err),\n            MyError::Num(ref err) =\u003e write!(f, \"Parse error: {}\", err),\n        }\n    }\n}\n\nimpl Error for MyError {\n    fn source(\u0026self) -\u003e Option\u003c\u0026(dyn Error + 'static)\u003e {\n        match *self {\n            MyError::Io(ref err) =\u003e Some(err),\n            MyError::Num(ref err) =\u003e Some(err),\n        }\n    }\n}\n```\n\n### Implementing with thiserror\n\n```rust\nuse thiserror::Error;\n\nuse trasy::TrasyError;\nuse trasy::bail;\n\n#[derive(Error, Debug)]\npub enum AppError {\n    #[error(\"Failed to perform operation\")]\n    OperationError,\n\n    #[error(\"IO error occurred: {0}\")]\n    IoError(#[from] std::io::Error),\n}\n\ntrait AppErrorExt {\n    fn new(error: AppError) -\u003e Self;\n}\n\nimpl AppErrorExt for TrasyError\u003cAppError\u003e {\n    fn new(error: AppError) -\u003e Self {\n        TrasyError::new(error)\n    }\n}\n\nfn might_fail(flag: bool) -\u003e Result\u003c(), TrasyError\u003cAppError\u003e\u003e {\n    if flag {\n        bail!(AppError::OperationError)\n    } else {\n        Ok(())\n    }\n}\n\nfn main() {\n    match might_fail(true) {\n        Ok(_) =\u003e println!(\"Success!\"),\n        Err(e) =\u003e println!(\"Error: {}\", e),\n    }\n}\n```\n\n## OpenTelemetry Integration\n\n`Trasy` supports OpenTelemetry, allowing you to trace your applications and export telemetry data to your chosen backend (e.g., Jaeger, Zipkin). This section describes how to configure and use OpenTelemetry in your application.\n\n### Configuration\n\nTo use OpenTelemetry with `TrasyError`, you first need to set up the telemetry configuration. Here's how you can configure and enable telemetry:\n\n#### 1. Define the Configuration\n\nConfigure the telemetry settings using the `TelemetryConfig` struct. You can specify the service name, the endpoint, whether to use batch or simple span processing, and optionally, a custom span exporter.\n\n```rust\nuse trasy_error::TelemetryConfig;\n\nlet config = TelemetryConfig {\n    service_name: \"my-awesome-service\".to_string(),\n    endpoint: \"http://my-telemetry-collector:4318\".to_string(),\n    use_batch: true,\n    oltp_exporter: None, // Use default OTLP exporter\n};\n```\n\n#### 2. Set Up OpenTelemetry\n\nPass the configuration to the `setup_opentelemetry` function to initialize the telemetry. This function sets up the tracing layer that you can then use with the `tracing` subscriber.\n\n```rust\nuse trasy_error::setup_opentelemetry;\n\nlet telemetry_layer = setup_opentelemetry(config).await.expect(\"Failed to set up OpenTelemetry\");\n\n// Now you can use `telemetry_layer` with your tracing subscriber setup\n```\n\n### Example: Full Setup with Tracing Subscriber\n\nHere is a complete example that shows how to set up tracing using `trasy_error` with OpenTelemetry and `tracing_subscriber`.\n\n```rust\nuse trasy_error::{TelemetryConfig, setup_opentelemetry};\nuse tracing_subscriber::{layer::SubscriberExt, Registry};\n\n#[tokio::main]\nasync fn main() -\u003e Result\u003c(), Box\u003cdyn std::error::Error\u003e\u003e {\n    let config = TelemetryConfig::default().with_oltp_exporter(\n        opentelemetry_otlp::new_exporter().http().with_endpoint(\"http://localhost:4318\")\n    );\n\n    let telemetry_layer = setup_opentelemetry(config).await?;\n\n    let subscriber = Registry::default()\n        .with(telemetry_layer)\n        .with(tracing_subscriber::fmt::layer());\n\n    tracing::subscriber::set_global_default(subscriber)?;\n\n    // Your application code here\n    tracing::info!(\"Application started\");\n\n    Ok(())\n}\n```\n\n### Custom Exporters\n\nIf you need to use a custom exporter, configure it as part of your `TelemetryConfig`:\n\n```rust\nlet custom_exporter = opentelemetry_otlp::new_exporter()\n    .grpc()\n    .with_endpoint(\"my-custom-endpoint:4317\");\n\nlet config = TelemetryConfig {\n    service_name: \"my-service\".to_string(),\n    use_batch: false,\n    oltp_exporter: Some(custom_exporter.into()),\n    ..Default::default()\n};\n```\n\n### Note\n\n- Make sure your OpenTelemetry collector or backend is properly configured to receive telemetry data from your application.\n- Adjust the OpenTelemetry setup according to your specific environment needs and the OpenTelemetry SDK documentation.\n\nThis integration allows `TrasyError` to be a powerful tool in not only handling errors but also in observing and diagnosing them in distributed systems.\n\nCertainly! To incorporate the usage of your Docker setup with Jaeger into the `README.md`, you can provide a detailed guide on how to run the Jaeger instance using Docker and how to connect it with your application. Below is the section you can add to your `README.md` to cover this:\n\n---\n\n## Integrating Jaeger for Tracing Visualization\n\n`Trasy` is configured to work seamlessly with Jaeger, a distributed tracing system. By using the provided Docker configuration, you can easily set up a Jaeger instance to visualize traces collected from your application. Here's how to get started:\n\n### Setting Up Jaeger with Docker\n\nTo start the Jaeger container which will collect and visualize your application's tracing data, follow these steps:\n\n1. Ensure Docker and Docker Compose are installed on your system. For installation instructions, see [Docker](https://docs.docker.com/get-docker/) and [Docker Compose](https://docs.docker.com/compose/install/).\n2. Create a `docker-compose.yml` file with the following content:\n\n    ```yaml\n    version: '3.8'\n\n    services:\n      jaeger:\n        image: jaegertracing/all-in-one:1.56\n        container_name: jaeger\n        ports:\n          - \"6831:6831/udp\"   # Jaeger Thrift Compact Protocol\n          - \"6832:6832/udp\"   # Jaeger Thrift Binary Protocol\n          - \"16686:16686\"     # Jaeger UI\n          - \"14268:14268\"     # Jaeger HTTP collector\n          - \"4317:4317\"       # OTLP gRPC port\n          - \"4318:4318\"       # OTLP gRPC http port\n        environment:\n          - COLLECTOR_OTLP_ENABLED=true\n    ```\n\n3. Run the following command in the directory where your `docker-compose.yml` is located:\n\n    ```bash\n    docker-compose up -d\n    ```\n\n   This command will download the Jaeger image and start the Jaeger service.\n\n### Connecting Your Application to Jaeger\n\nTo send traces from your application to Jaeger, configure the `TelemetryConfig` to use the correct endpoint. Here’s an example using the default setup provided in the Docker configuration:\n\n```rust\nlet config = TelemetryConfig {\n    service_name: \"my-awesome-service\".to_string(),\n    endpoint: \"http://localhost:4318\",\n    use_batch: true,\n    oltp_exporter: None, // This will use the default OTLP HTTP exporter\n};\n\nlet telemetry_layer = setup_opentelemetry(config).await.expect(\"Failed to set up OpenTelemetry\");\n```\n\n### Viewing Traces in Jaeger\n\nAfter running your application configured to send traces to Jaeger, you can view these traces by:\n\n1. Opening a web browser.\n2. Navigating to `http://localhost:16686`.\n\nThis URL is the Jaeger UI, where you can query and visualize traces collected from your application.\n\n### Note\n\n- Make sure the port numbers in the Jaeger Docker setup match those expected by your application’s telemetry configuration.\n- If running within different Docker networks or on different machines, ensure network connectivity between your application and the Jaeger service.\n\nThis setup provides a powerful way to visualize and debug the behavior of your distributed applications.\n\n## Contributing\n\nContributions to `Trasy` are welcome! Here are some ways you can contribute:\n\n- Reporting bugs\n- Suggesting enhancements\n- Adding more integrations and features\n- Improving documentation\n\nPlease feel free to fork the repository and submit pull requests.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freoring%2Ftrasy","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Freoring%2Ftrasy","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freoring%2Ftrasy/lists"}