├── .github ├── images │ ├── banner-dark.svg │ └── banner-light.svg └── workflows │ └── ci.yaml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── deny.toml ├── examples ├── README.md ├── fmt │ └── main.rs ├── layers │ └── main.rs ├── noenv │ └── main.rs └── simple │ └── main.rs ├── rust-toolchain └── src ├── builder.rs ├── error.rs └── lib.rs /.github/images/banner-dark.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | -------------------------------------------------------------------------------- /.github/images/banner-light.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | pull_request: 5 | branches: 6 | - main 7 | push: 8 | branches: 9 | - main 10 | tags: 11 | - "v*" 12 | 13 | jobs: 14 | rust_fmt_check: 15 | name: Rustfmt check 16 | runs-on: ubuntu-latest 17 | steps: 18 | - uses: actions/checkout@v3 19 | - uses: actions/cache@v3 20 | with: 21 | path: | 22 | ~/.cargo/registry 23 | ~/.cargo/git 24 | target 25 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 26 | - name: Run cargo fmt 27 | uses: actions-rs/cargo@v1 28 | with: 29 | command: fmt 30 | args: -- --check 31 | clippy_check: 32 | name: Clippy check 33 | runs-on: ubuntu-latest 34 | steps: 35 | - uses: actions/checkout@v3 36 | - uses: actions/cache@v3 37 | with: 38 | path: | 39 | ~/.cargo/registry 40 | ~/.cargo/git 41 | target 42 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 43 | - name: Install clippy 44 | run: rustup component add clippy 45 | - name: Run clippy check 46 | uses: actions-rs/clippy-check@v1 47 | with: 48 | token: ${{ secrets.GITHUB_TOKEN }} 49 | test: 50 | name: Run tests 51 | runs-on: ubuntu-latest 52 | steps: 53 | - uses: actions/checkout@v3 54 | - uses: actions/cache@v3 55 | with: 56 | path: | 57 | ~/.cargo/registry 58 | ~/.cargo/git 59 | target 60 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 61 | - name: Run cargo test 62 | env: 63 | AXIOM_TOKEN: ${{ secrets.AXIOM_TOKEN }} 64 | AXIOM_URL: https://cloud.dev.axiomtestlabs.co 65 | AXIOM_DATASET: _traces 66 | run: cargo test 67 | 68 | validate-crate: 69 | name: Validate crate 70 | runs-on: ubuntu-latest 71 | steps: 72 | - uses: actions/checkout@v3 73 | - uses: actions/cache@v3 74 | with: 75 | path: | 76 | ~/.cargo/registry 77 | ~/.cargo/git 78 | target 79 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 80 | - name: Test publish 81 | run: cargo publish --dry-run 82 | 83 | publish_on_crates_io: 84 | name: Publish on crates.io 85 | runs-on: ubuntu-latest 86 | if: github.repository_owner == 'axiomhq' && startsWith(github.ref, 'refs/tags') 87 | needs: 88 | - rust_fmt_check 89 | - clippy_check 90 | - test 91 | steps: 92 | - uses: actions/checkout@v3 93 | - name: Publish on crates.io 94 | env: 95 | CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} 96 | run: cargo publish 97 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | /examples/target 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tracing-axiom" 3 | version = "0.7.0" 4 | authors = [ 5 | "Arne Bahlo ", 6 | "Darach Ennis ", 7 | "Heinz Gies ", 8 | ] 9 | edition = "2021" 10 | rust-version = "1.73" 11 | license = "MIT OR Apache-2.0" 12 | description = "The tracing layer for shipping traces to Axiom" 13 | homepage = "https://axiom.co" 14 | repository = "https://github.com/axiomhq/tracing-axiom" 15 | documentation = "https://docs.rs/tracing-axiom" 16 | keywords = ["tracing", "axiom", "instrumentation", "opentelemetry"] 17 | readme = "README.md" 18 | include = [ 19 | "src/**/*.rs", 20 | "examples", 21 | "README.md", 22 | "LICENSE-APACHE", 23 | "LICENSE-MIT", 24 | ] 25 | resolver = "2" 26 | 27 | [dependencies] 28 | url = "2.4.1" 29 | thiserror = "1" 30 | 31 | tracing-core = { version = "0.1", default-features = false, features = ["std"] } 32 | tracing-opentelemetry = { version = "0.23", default-features = false } 33 | tracing-subscriber = { version = "0.3", default-features = false, features = [ 34 | "smallvec", 35 | "std", 36 | "registry", 37 | "fmt", 38 | "json", 39 | ] } 40 | 41 | 42 | reqwest = { version = "0.11", default-features = false } 43 | opentelemetry = { version = "0.22" } 44 | opentelemetry-otlp = { version = "0.15", features = [ 45 | "prost", 46 | "tokio", 47 | "http-proto", 48 | "reqwest-client", 49 | ] } 50 | opentelemetry-semantic-conventions = "0.15" 51 | opentelemetry_sdk = { version = "0.22", features = ["rt-tokio"] } 52 | 53 | [dev-dependencies] 54 | tokio = { version = "1", features = ["full", "tracing"] } 55 | tracing = { version = "0.1", features = ["log"] } 56 | tracing-subscriber = { version = "0.3", default-features = false, features = [ 57 | "smallvec", 58 | "std", 59 | "registry", 60 | "fmt", 61 | "json", 62 | "ansi", 63 | ] } 64 | 65 | # Example that demonstrates how to use the `tracing-axiom` layer with the `tracing-subscriber` crate. 66 | [[example]] 67 | name = "layers" 68 | 69 | # Simple most example use of `tracing-axiom`. 70 | [[example]] 71 | name = "simple" 72 | 73 | # Example that demonstrates using a nice color and formating 74 | [[example]] 75 | name = "fmt" 76 | 77 | # Demonstrate setting config in the code 78 | [[example]] 79 | name = "noenv" 80 | 81 | [features] 82 | default = ["rustls-tls"] 83 | default-tls = ["reqwest/default-tls"] 84 | native-tls = ["reqwest/native-tls"] 85 | rustls-tls = ["reqwest/rustls-tls"] 86 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Axiom, Inc. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tracing-axiom 2 | 3 | 4 | 5 | 6 | 7 | 8 | Axiom.co banner 9 | 10 | 11 |   12 | 13 | [![docs.rs](https://docs.rs/tracing-axiom/badge.svg)](https://docs.rs/tracing-axiom/) 14 | [![build](https://img.shields.io/github/workflow/status/axiomhq/tracing-axiom/CI?ghcache=unused)](https://github.com/axiomhq/tracing-axiom/actions?query=workflow%3ACI) 15 | [![crates.io](https://img.shields.io/crates/v/tracing-axiom.svg)](https://crates.io/crates/tracing-axiom) 16 | [![License](https://img.shields.io/crates/l/tracing-axiom)](LICENSE-APACHE) 17 | 18 | [Axiom](https://axiom.co) unlocks observability at any scale. 19 | 20 | - **Ingest with ease, store without limits:** Axiom’s next-generation datastore enables ingesting petabytes of data with ultimate efficiency. Ship logs from Kubernetes, AWS, Azure, Google Cloud, DigitalOcean, Nomad, and others. 21 | - **Query everything, all the time:** Whether DevOps, SecOps, or EverythingOps, query all your data no matter its age. No provisioning, no moving data from cold/archive to “hot”, and no worrying about slow queries. All your data, all. the. time. 22 | - **Powerful dashboards, for continuous observability:** Build dashboards to collect related queries and present information that’s quick and easy to digest for you and your team. Dashboards can be kept private or shared with others, and are the perfect way to bring together data from different sources 23 | 24 | For more information check out the [official documentation](https://axiom.co/docs). 25 | 26 | ## Usage 27 | 28 | Add the following to your `Cargo.toml`: 29 | 30 | ```toml 31 | [dependencies] 32 | tracing-axiom = "0.7" 33 | ``` 34 | 35 | Create a dataset in Axiom and export the name as `AXIOM_DATASET`. 36 | Then create an API token with ingest permission into that dataset in 37 | [the Axiom settings](https://cloud.axiom.co/settings/profile) and export it as 38 | `AXIOM_TOKEN`. 39 | 40 | Now you can set up tracing like this: 41 | 42 | ```rust,no_run 43 | use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt as _, Registry}; 44 | #[tokio::main] 45 | async fn main() -> Result<(), Box> { 46 | let axiom_layer = tracing_axiom::default("readme")?; // Set AXIOM_DATASET and AXIOM_TOKEN in your env! 47 | Registry::default().with(axiom_layer).init(); 48 | say_hello(); 49 | Ok(()) 50 | } 51 | 52 | #[tracing::instrument] 53 | pub fn say_hello() { 54 | tracing::info!("Hello, world!"); 55 | } 56 | ``` 57 | 58 | For further examples, head over to the [examples](examples) directory. 59 | 60 | > **Note**: Due to a limitation of an underlying library, [events outside of a 61 | > span are not recorded](https://docs.rs/tracing-opentelemetry/latest/src/tracing_opentelemetry/layer.rs.html#807). 62 | 63 | ## Features 64 | 65 | The following are a list of 66 | [Cargo features](https://doc.rust-lang.org/stable/cargo/reference/features.html#the-features-section) 67 | that can be enabled or disabled: 68 | 69 | - **rustls-tls** _(enabled by default)_: Enables TLS functionality provided by `rustls`. 70 | - **default-tls**: uses reqwest default TLS library. 71 | - **native-tls**: Enables TLS functionality provided by `native-tls`. 72 | 73 | ## FAQ & Troubleshooting 74 | 75 | ### How do I log traces to the console in addition to Axiom? 76 | You can use this library to get a [`tracing-subscriber::layer`](https://docs.rs/tracing-subscriber/latest/tracing_subscriber/layer/index.html) 77 | and combine it with other layers, for example one that prints traces to the 78 | console. 79 | You can see how this works in the [fmt example](./examples/fmt). 80 | 81 | ### My test function hangs indefinitely 82 | This can happen when you use `#[tokio::test]` as that defaults to a 83 | single-threaded executor, but the 84 | [`opentelemetry`](https://docs.rs/opentelemetry) crate requires a multi-thread 85 | executor. 86 | 87 | ## License 88 | 89 | Licensed under either of 90 | 91 | - Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or [apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)) 92 | - MIT license ([LICENSE-MIT](LICENSE-MIT) or [opensource.org/licenses/MIT](http://opensource.org/licenses/MIT)) 93 | 94 | at your option. 95 | -------------------------------------------------------------------------------- /deny.toml: -------------------------------------------------------------------------------- 1 | # 2 | # Ensure we do not use any libraries that have licenses incompatible ASL-2 / MIT 3 | # 4 | 5 | [licenses] 6 | unlicensed = "deny" 7 | default = "deny" 8 | copyleft = "deny" 9 | allow = [ 10 | # "0BSD", 11 | "Apache-2.0", 12 | # "BSD-2-Clause", 13 | "BSD-3-Clause", 14 | "BSL-1.0", 15 | # "CC0-1.0", 16 | # "ISC", 17 | "MIT", 18 | # "OpenSSL", 19 | "Unicode-DFS-2016", 20 | "Zlib" 21 | ] 22 | 23 | exceptions = [ 24 | # MPL-2.0 are added case-by-case to make sure we are in compliance. To be in 25 | # compliance we cannot be modifying the source files. 26 | ] 27 | 28 | [licenses.private] 29 | ignore = true 30 | 31 | [[licenses.clarify]] 32 | name = "ring" 33 | version = "*" 34 | expression = "MIT AND ISC AND OpenSSL" 35 | license-files = [ 36 | { path = "LICENSE", hash = 0xbd0eed23 } 37 | ] 38 | 39 | [advisories] 40 | ignore = [ ] 41 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | * [simple](./simple) - Uses defaults provided by Axiom and is a one line setup. 4 | * [fmt](./fmt) - Uses layers with out of the box local formatting and Axiom remote endpoint. 5 | * [layers](./layers) - The kitchen sink. If you have a rich tracing setup, just plug tracing-axiom into your existing setup. 6 | * [noenv]('./noenv) - Example that does not use environment variables for tracing setup. 7 | 8 | ## Setup 9 | 10 | The `sdk` and `layers` examples assume the existance of a dataset called `tracing-axiom-examples` in your axiom 11 | environment. You can setup a dataset using the `Axiom Cli` ([docs](https://axiom.co/docs/reference/cli), [github](https://github.com/axiomhq/cli)) as follows: 12 | 13 | ```shell 14 | axiom dataset create --name tracing-axiom-examples --description "Dataset for testing tracing axiom" 15 | export AXIOM_DATASET=tracing-axiom-examples 16 | ``` 17 | 18 | If the environment variable is not set, the examples will fail with an error. 19 | -------------------------------------------------------------------------------- /examples/fmt/main.rs: -------------------------------------------------------------------------------- 1 | use tracing::{info, instrument}; 2 | use tracing_subscriber::prelude::*; 3 | 4 | #[tokio::main] 5 | async fn main() -> Result<(), Box> { 6 | let axiom_layer = tracing_axiom::builder("fmt").build()?; 7 | let fmt_layer = tracing_subscriber::fmt::layer().pretty(); 8 | tracing_subscriber::registry() 9 | .with(fmt_layer) 10 | .with(axiom_layer) 11 | .try_init()?; 12 | 13 | say_hello(); 14 | 15 | // Ensure that the tracing provider is shutdown correctly 16 | opentelemetry::global::shutdown_tracer_provider(); 17 | 18 | Ok(()) 19 | } 20 | 21 | #[instrument] 22 | fn say_hello() { 23 | info!("hello world") 24 | } 25 | -------------------------------------------------------------------------------- /examples/layers/main.rs: -------------------------------------------------------------------------------- 1 | use opentelemetry::global; 2 | use opentelemetry_sdk::propagation::TraceContextPropagator; 3 | use tracing::{info, instrument}; 4 | use tracing_subscriber::Registry; 5 | use tracing_subscriber::{prelude::__tracing_subscriber_SubscriberExt, util::SubscriberInitExt}; 6 | 7 | #[instrument] 8 | fn say_hi(id: u64, name: impl Into + std::fmt::Debug) { 9 | info!(?id, "Hello, {}!", name.into()); 10 | } 11 | 12 | fn setup_tracing(tags: &[(&'static str, &'static str)]) -> Result<(), tracing_axiom::Error> { 13 | info!("Axiom OpenTelemetry tracing endpoint is configured:"); 14 | // Setup an AWS CloudWatch compatible tracing layer 15 | let cloudwatch_layer = tracing_subscriber::fmt::layer() 16 | .json() 17 | .with_ansi(false) 18 | .without_time() 19 | .with_target(false); 20 | 21 | // Setup an Axiom OpenTelemetry compatible tracing layer 22 | let tag_iter = tags.iter().copied(); 23 | let axiom_layer = tracing_axiom::builder("layers") 24 | .with_tags(tag_iter) 25 | .build()?; 26 | 27 | // Setup our multi-layered tracing subscriber 28 | Registry::default() 29 | .with(axiom_layer) 30 | .with(cloudwatch_layer) 31 | .init(); 32 | 33 | global::set_text_map_propagator(TraceContextPropagator::new()); 34 | 35 | Ok(()) 36 | } 37 | 38 | const TAGS: &[(&str, &str)] = &[ 39 | ("aws_region", "us-east-1"), // NOTE - example for illustrative purposes only 40 | ]; 41 | 42 | #[tokio::main(flavor = "multi_thread")] 43 | async fn main() -> Result<(), Box> { 44 | setup_tracing(TAGS)?; // NOTE we depend on environment variable 45 | 46 | say_hi(42, "world"); 47 | 48 | // do something with result ... 49 | 50 | // Ensure that the tracing provider is shutdown correctly 51 | opentelemetry::global::shutdown_tracer_provider(); 52 | 53 | Ok(()) 54 | } 55 | -------------------------------------------------------------------------------- /examples/noenv/main.rs: -------------------------------------------------------------------------------- 1 | use tracing::{info, instrument}; 2 | use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt as _, Registry}; 3 | 4 | #[instrument] 5 | fn say_hi(id: u64, name: impl Into + std::fmt::Debug) { 6 | info!(?id, "Hello, {}!", name.into()); 7 | } 8 | 9 | #[tokio::main(flavor = "multi_thread")] 10 | async fn main() -> Result<(), Box> { 11 | let axiom_layer = tracing_axiom::builder("noenv") 12 | .with_tags([("aws_region", "us-east-1")].iter().copied()) // Set otel tags 13 | .with_dataset("tracing-axiom-examples")? // Set dataset 14 | .with_token("xaat-some-valid-token")? // Set API token 15 | .with_url("http://localhost:4318")? // Set URL, can be changed to any OTEL endpoint 16 | .build()?; // Initialize tracing 17 | 18 | Registry::default().with(axiom_layer).init(); 19 | 20 | say_hi(42, "world"); 21 | 22 | // do something with result ... 23 | 24 | // Ensure that the tracing provider is shutdown correctly 25 | opentelemetry::global::shutdown_tracer_provider(); 26 | 27 | Ok(()) 28 | } 29 | -------------------------------------------------------------------------------- /examples/simple/main.rs: -------------------------------------------------------------------------------- 1 | use tracing::{error, instrument}; 2 | use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt as _, Registry}; 3 | 4 | #[instrument] 5 | fn say_hello() { 6 | error!("hello world") 7 | } 8 | 9 | #[tokio::main] 10 | async fn main() -> Result<(), Box> { 11 | let axiom_layer = tracing_axiom::default("simple")?; 12 | 13 | Registry::default().with(axiom_layer).init(); 14 | 15 | say_hello(); 16 | 17 | // Ensure that the tracing provider is shutdown correctly 18 | opentelemetry::global::shutdown_tracer_provider(); 19 | 20 | Ok(()) 21 | } 22 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | stable -------------------------------------------------------------------------------- /src/builder.rs: -------------------------------------------------------------------------------- 1 | use crate::Error; 2 | use opentelemetry::{Key, KeyValue, Value}; 3 | use opentelemetry_otlp::WithExportConfig; 4 | use opentelemetry_sdk::{ 5 | trace::{Config as TraceConfig, Tracer}, 6 | Resource, 7 | }; 8 | use opentelemetry_semantic_conventions::resource::{ 9 | SERVICE_NAME, TELEMETRY_SDK_LANGUAGE, TELEMETRY_SDK_NAME, TELEMETRY_SDK_VERSION, 10 | }; 11 | use reqwest::Url; 12 | use std::{ 13 | collections::HashMap, 14 | env::{self, VarError}, 15 | time::Duration, 16 | }; 17 | use tracing_core::Subscriber; 18 | use tracing_opentelemetry::OpenTelemetryLayer; 19 | use tracing_subscriber::registry::LookupSpan; 20 | 21 | const CLOUD_URL: &str = "https://api.axiom.co"; 22 | 23 | /// Builder for creating a tracing tracer, a layer or a subscriber that sends traces to 24 | /// Axiom via the `OpenTelemetry` protocol. The API token is read from the `AXIOM_TOKEN` 25 | /// environment variable. The dataset name is read from the `AXIOM_DATASET` environment 26 | /// variable. The URL defaults to Axiom Cloud whose URL is `https://cloud.axiom.co` but 27 | /// can be overridden by setting the `AXIOM_URL` environment variable for testing purposes 28 | /// 29 | #[derive(Debug, Default)] 30 | pub struct Builder { 31 | dataset_name: Option, 32 | token: Option, 33 | url: Option, 34 | tags: Vec, 35 | trace_config: Option, 36 | service_name: Option, 37 | timeout: Option, 38 | } 39 | 40 | fn get_env(env_var_name: &'static str) -> Result, Error> { 41 | match env::var(env_var_name) { 42 | Ok(maybe_ok_var) => Ok(Some(maybe_ok_var)), 43 | Err(VarError::NotPresent) => Ok(None), 44 | Err(VarError::NotUnicode(_)) => Err(Error::EnvVarNotUnicode(env_var_name.to_string())), 45 | } 46 | } 47 | 48 | impl Builder { 49 | /// Set the Axiom dataset name to use. The dataset name is the name of the 50 | /// persistent dataset in Axiom cloud that will store the traces and make 51 | /// them available for querying using APL, the Axiom SDK or the Axiom CLI. 52 | /// 53 | /// # Errors 54 | /// If the dataset name is empty. 55 | pub fn with_dataset(mut self, dataset_name: impl Into) -> Result { 56 | let dataset_name: String = dataset_name.into(); 57 | if dataset_name.is_empty() { 58 | Err(Error::EmptyDataset) 59 | } else { 60 | self.dataset_name = Some(dataset_name); 61 | Ok(self) 62 | } 63 | } 64 | 65 | /// Set the Axiom API token to use. 66 | /// 67 | /// # Errors 68 | /// If the token is empty or does not start with `xaat-` (aka is not a api token). 69 | pub fn with_token(mut self, token: impl Into) -> Result { 70 | let token: String = token.into(); 71 | if token.is_empty() { 72 | Err(Error::EmptyToken) 73 | } else if !token.starts_with("xaat-") { 74 | Err(Error::InvalidToken) 75 | } else { 76 | self.token = Some(token); 77 | Ok(self) 78 | } 79 | } 80 | 81 | /// Set the Axiom API URL to use. Defaults to Axiom Cloud. When not set Axiom Cloud is used. 82 | /// 83 | /// # Errors 84 | /// If the URL is not a valid URL. 85 | pub fn with_url(mut self, url: &str) -> Result { 86 | self.url = Some(url.parse()?); 87 | Ok(self) 88 | } 89 | 90 | /// Set the trace config. 91 | #[must_use] 92 | pub fn with_trace_config(mut self, trace_config: impl Into) -> Self { 93 | self.trace_config = Some(trace_config.into()); 94 | self 95 | } 96 | 97 | /// Set the service name. It will be set as a resource attribute with the 98 | /// name `service_name`. 99 | #[must_use] 100 | pub fn with_service_name(mut self, service_name: impl Into) -> Self { 101 | self.service_name = Some(service_name.into()); 102 | self 103 | } 104 | 105 | /// Set the resource tags for the open telemetry tracer that publishes to Axiom. 106 | /// These tags will be added to all spans. 107 | #[must_use] 108 | pub fn with_tags(mut self, tags: T) -> Self 109 | where 110 | K: Into, 111 | V: Into, 112 | T: Iterator, 113 | { 114 | self.tags = tags.map(|(k, v)| KeyValue::new(k, v)).collect::>(); 115 | self 116 | } 117 | 118 | /// Sets the collector timeout for the OTLP exporter. 119 | /// The default is 3 seconds. 120 | /// 121 | #[must_use] 122 | pub fn with_timeout(mut self, timeout: Duration) -> Self { 123 | self.timeout = Some(timeout); 124 | self 125 | } 126 | 127 | /// Load defaults from environment variables, if variables were set before this call they will not be replaced. 128 | /// 129 | /// The following environment variables are used: 130 | /// - `AXIOM_TOKEN` 131 | /// - `AXIOM_DATASET` 132 | /// - `AXIOM_URL` 133 | /// 134 | /// # Errors 135 | /// If an environment variable is not valid UTF8, or any of their values are invalid. 136 | pub fn with_env(mut self) -> Result { 137 | if self.token.is_none() { 138 | if let Some(t) = get_env("AXIOM_TOKEN")? { 139 | self = self.with_token(t)?; 140 | } 141 | }; 142 | 143 | if self.dataset_name.is_none() { 144 | if let Some(d) = get_env("AXIOM_DATASET")? { 145 | self = self.with_dataset(d)?; 146 | } 147 | }; 148 | if self.url.is_none() { 149 | if let Some(u) = get_env("AXIOM_URL")? { 150 | self = self.with_url(&u)?; 151 | } 152 | }; 153 | 154 | Ok(self) 155 | } 156 | 157 | /// Create a layer which sends traces to Axiom that can be added to the tracing layers. 158 | /// 159 | /// # Errors 160 | /// 161 | /// Returns an error if any of the settings are not valid 162 | pub fn build(self) -> Result, Error> 163 | where 164 | S: Subscriber + for<'span> LookupSpan<'span>, 165 | { 166 | Ok(tracing_opentelemetry::layer().with_tracer(self.tracer()?)) 167 | } 168 | 169 | fn tracer(self) -> Result { 170 | let token = self.token.ok_or(Error::MissingToken)?; 171 | let dataset_name = self.dataset_name.ok_or(Error::MissingDataset)?; 172 | let url = self 173 | .url 174 | .unwrap_or_else(|| CLOUD_URL.to_string().parse().expect("this is a valid URL")); 175 | 176 | let mut headers = HashMap::with_capacity(2); 177 | headers.insert("Authorization".to_string(), format!("Bearer {token}")); 178 | headers.insert("X-Axiom-Dataset".to_string(), dataset_name); 179 | headers.insert( 180 | "User-Agent".to_string(), 181 | format!("tracing-axiom/{}", env!("CARGO_PKG_VERSION")), 182 | ); 183 | 184 | let mut tags = self.tags.clone(); 185 | tags.extend(vec![ 186 | KeyValue::new(TELEMETRY_SDK_NAME, env!("CARGO_PKG_NAME").to_string()), 187 | KeyValue::new(TELEMETRY_SDK_VERSION, env!("CARGO_PKG_VERSION").to_string()), 188 | KeyValue::new(TELEMETRY_SDK_LANGUAGE, "rust".to_string()), 189 | ]); 190 | 191 | if let Some(service_name) = self.service_name { 192 | // TODO: Is there a way to get the name of the bin crate using this? 193 | tags.push(KeyValue::new(SERVICE_NAME, service_name)); 194 | } 195 | 196 | let trace_config = self 197 | .trace_config 198 | .unwrap_or_default() 199 | .with_resource(Resource::new(tags)); 200 | 201 | let pipeline = opentelemetry_otlp::new_exporter() 202 | .http() 203 | .with_http_client(reqwest::Client::new()) 204 | .with_endpoint(url) 205 | .with_headers(headers) 206 | .with_timeout(self.timeout.unwrap_or(Duration::from_secs(3))); 207 | let tracer = opentelemetry_otlp::new_pipeline() 208 | .tracing() 209 | .with_exporter(pipeline) 210 | .with_trace_config(trace_config) 211 | .install_batch(opentelemetry_sdk::runtime::Tokio)?; 212 | Ok(tracer) 213 | } 214 | } 215 | 216 | #[cfg(test)] 217 | mod tests { 218 | 219 | use tracing_subscriber::Registry; 220 | 221 | use super::{Error, *}; 222 | fn cache_axiom_env() -> Result, Box> { 223 | let mut saved_env = std::env::vars().collect::>(); 224 | // Cache AXIOM env vars and remove from env for test 225 | for ref key in std::env::vars().map(|(key, _)| key) { 226 | if key.starts_with("AXIOM") { 227 | saved_env.insert(key.clone(), std::env::var(key)?); 228 | std::env::remove_var(key); 229 | } 230 | } 231 | 232 | Ok(saved_env) 233 | } 234 | 235 | fn restore_axiom_env(saved_env: HashMap) { 236 | for (key, value) in saved_env { 237 | std::env::set_var(key, value); 238 | } 239 | } 240 | 241 | #[tokio::test(flavor = "multi_thread")] 242 | async fn test_no_env_skips_env_variables() -> Result<(), Error> { 243 | let builder = Builder::default(); 244 | assert_eq!(builder.token, None); 245 | assert_eq!(builder.dataset_name, None); 246 | assert_eq!(builder.url, None); 247 | 248 | let err: Result = Builder::default().tracer(); 249 | matches!(err, Err(Error::MissingToken)); 250 | 251 | let builder = Builder::default() 252 | .with_token("xaat-snot")? 253 | .with_dataset("test")?; 254 | matches!(builder.tracer(), Err(Error::MissingDataset)); 255 | 256 | let builder = Builder::default() 257 | .with_token("xaat-snot")? 258 | .with_dataset("test")?; 259 | matches!(builder.tracer(), Err(Error::MissingDataset)); 260 | 261 | let builder = Builder::default() 262 | .with_token("xaat-snot")? 263 | .with_dataset("test")?; 264 | assert!(builder.tracer().is_ok()); 265 | 266 | matches!( 267 | Builder::default().with_url(""), 268 | Err(Error::InvalidUrl(url::ParseError::RelativeUrlWithoutBase)) 269 | ); 270 | 271 | Ok(()) 272 | } 273 | 274 | #[tokio::test] 275 | async fn with_env_respects_env_variables() -> Result<(), Box> { 276 | let cached_env = cache_axiom_env()?; 277 | 278 | let err = Builder::default().tracer(); 279 | matches!(err, Err(Error::EnvVarMissing("AXIOM_TOKEN"))); 280 | 281 | std::env::set_var("AXIOM_TOKEN", "xaat-snot"); 282 | let err = Builder::default().tracer(); 283 | matches!(err, Err(Error::EnvVarMissing("AXIOM_DATASET"))); 284 | 285 | std::env::set_var("AXIOM_DATASET", "test"); 286 | let ok = Builder::default().with_env()?.tracer(); 287 | assert!(ok.is_ok()); 288 | 289 | // NOTE We let this hang wet rather than fake the endpoint as 290 | // the tracer will try to connect to it and this may hang the 291 | // test if the endpoint is not reachable. 292 | // 293 | // std::env::set_var("AXIOM_URL", "http://localhost:8080"); 294 | // let ok = Builder::new().tracer(); 295 | // assert!(ok.is_ok()); 296 | 297 | restore_axiom_env(cached_env); 298 | Ok(()) 299 | } 300 | 301 | #[test] 302 | fn test_missing_token() { 303 | matches!(Builder::default().tracer(), Err(Error::MissingToken)); 304 | } 305 | 306 | #[test] 307 | fn test_empty_token() { 308 | matches!(Builder::default().with_token(""), Err(Error::EmptyToken)); 309 | } 310 | 311 | #[test] 312 | fn test_invalid_token() { 313 | matches!( 314 | Builder::default().with_token("invalid"), 315 | Err(Error::InvalidToken) 316 | ); 317 | } 318 | 319 | #[test] 320 | fn test_invalid_url() -> Result<(), Error> { 321 | matches!( 322 | Builder::default() 323 | .with_token("xaat-123456789")? 324 | .with_dataset("test")? 325 | .with_url(""), 326 | Err(Error::InvalidUrl(_)) 327 | ); 328 | Ok(()) 329 | } 330 | 331 | #[tokio::test(flavor = "multi_thread")] 332 | async fn test_valid_token() -> Result<(), Error> { 333 | // Note that we can't test the init/try_init funcs here because OTEL 334 | // gets confused with the global subscriber. 335 | 336 | let result = Builder::default() 337 | .with_dataset("test")? 338 | .with_token("xaat-123456789")? 339 | .build::(); 340 | 341 | assert!(result.is_ok(), "{:?}", result.err()); 342 | Ok(()) 343 | } 344 | 345 | #[tokio::test(flavor = "multi_thread")] 346 | async fn test_valid_token_env() -> Result<(), Error> { 347 | // Note that we can't test the init/try_init funcs here because OTEL 348 | // gets confused with the global subscriber. 349 | 350 | let env_backup = env::var("AXIOM_TOKEN"); 351 | env::set_var("AXIOM_TOKEN", "xaat-1234567890"); 352 | 353 | let result = Builder::default() 354 | .with_dataset("test")? 355 | .with_env()? 356 | .build::(); 357 | 358 | if let Ok(token) = env_backup { 359 | env::set_var("AXIOM_TOKEN", token); 360 | } 361 | 362 | assert!(result.is_ok(), "{:?}", result.err()); 363 | Ok(()) 364 | } 365 | } 366 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use opentelemetry::trace; 2 | use tracing_subscriber::util::TryInitError; 3 | 4 | /// The error type for this crate. 5 | #[derive(thiserror::Error, Debug)] 6 | pub enum Error { 7 | /// Failed to configure the tracer. 8 | #[error("Failed to configure tracer: {0}")] 9 | TraceError(#[from] trace::TraceError), 10 | 11 | /// Failed to initialize the tracing-subscriber registry. 12 | #[error("Failed to initialize registry: {0}")] 13 | InitErr(#[from] TryInitError), 14 | 15 | /// The required Axiom API token is missing. 16 | #[error("Token is missing")] 17 | MissingToken, 18 | 19 | /// The required Axiom API token is empty. 20 | #[error("Token is empty")] 21 | EmptyToken, 22 | 23 | /// The required Axiom token is missing. 24 | #[error("Invalid token (please provide a valid API token)")] 25 | InvalidToken, 26 | 27 | /// The required Axiom dataset name is missing. 28 | #[error("Dataset is missing")] 29 | MissingDataset, 30 | 31 | /// The required Axiom dataset name is empty. 32 | #[error("Dataset is empty")] 33 | EmptyDataset, 34 | 35 | /// The required Axiom dataset name is invalid. 36 | #[error("Invalid URL: {0}")] 37 | InvalidUrl(#[from] url::ParseError), 38 | 39 | /// The environment variable is malformed unicode. 40 | #[error("Environment variable {0} contains invalid non Unciode ( UTF-8 ) content")] 41 | EnvVarNotUnicode(String), 42 | 43 | /// The environment variable is not present. 44 | #[error("Environment variable {0} is required but missing")] 45 | EnvVarMissing(&'static str), 46 | } 47 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![deny(warnings)] 2 | #![deny(missing_docs)] 3 | #![recursion_limit = "1024"] 4 | #![deny( 5 | clippy::all, 6 | clippy::unwrap_used, 7 | clippy::unnecessary_unwrap, 8 | clippy::pedantic, 9 | clippy::mod_module_files 10 | )] 11 | 12 | //! Send traces to Axiom with a single line. 13 | //! 14 | //! # Example 15 | //! 16 | //! In a project that uses [Tokio](https://tokio.rs) and 17 | //! [tracing](https://docs.rs/tracing) run `cargo add tracing-axiom` and 18 | //! configure it like this: 19 | //! 20 | //! ```rust,no_run 21 | //! use tracing_subscriber::{layer::SubscriberExt as _, util::SubscriberInitExt as _, Registry}; 22 | //! #[tokio::main] 23 | //! async fn main() -> Result<(), Box> { 24 | //! let axiom_layer = tracing_axiom::default("doctests")?; // Set AXIOM_DATASET and AXIOM_TOKEN in your env! 25 | //! Registry::default().with(axiom_layer).init(); 26 | //! say_hello(); 27 | //! Ok(()) 28 | //! } 29 | //! 30 | //! #[tracing::instrument] 31 | //! pub fn say_hello() { 32 | //! tracing::info!("Hello, world!"); 33 | //! } 34 | //! ``` 35 | //! 36 | //! The example above gets the Axiom API token from the `AXIOM_TOKEN` env and 37 | //! the dataset name from `AXIOM_DATASET`. For more advanced configuration, see [`builder()`]. 38 | 39 | mod builder; 40 | mod error; 41 | 42 | pub use builder::Builder; 43 | pub use error::Error; 44 | use opentelemetry_sdk::trace::Tracer; 45 | use tracing_core::Subscriber; 46 | use tracing_opentelemetry::OpenTelemetryLayer; 47 | use tracing_subscriber::registry::LookupSpan; 48 | 49 | #[cfg(doctest)] 50 | #[doc = include_str!("../README.md")] 51 | pub struct ReadmeDoctests; 52 | 53 | /// Creates a default [`OpenTelemetryLayer`] with a [`Tracer`] that sends traces to Axiom. 54 | /// 55 | /// It uses the environment variables `AXIOM_TOKEN` and optionally `AXIOM_URL` and `AXIOM_DATASET` 56 | /// to configure the endpoint. 57 | /// If you want to manually set these or other attributres, use `builder()` or `builder_with_env()`. 58 | /// 59 | /// # Errors 60 | /// 61 | /// Errors if the initialization was unsuccessful, likely because a global 62 | /// subscriber was already installed or `AXIOM_TOKEN` and/or `AXIOM_DATASET` 63 | /// is not set or invalid. 64 | pub fn default(service_name: &str) -> Result, Error> 65 | where 66 | S: Subscriber + for<'span> LookupSpan<'span>, 67 | { 68 | builder_with_env(service_name)?.build() 69 | } 70 | 71 | /// Create a new [`Builder`] and set the configuratuin from the environment. 72 | /// 73 | /// # Errors 74 | /// If any of the environment variables are invalid, missing variables are not causing errors as 75 | /// they can be set later. 76 | pub fn builder_with_env(service_name: &str) -> Result { 77 | Ok(Builder::default() 78 | .with_env()? 79 | .with_service_name(service_name)) 80 | } 81 | 82 | /// Create a new [`Builder`] with no defaults set. 83 | #[must_use] 84 | pub fn builder(service_name: &str) -> Builder { 85 | Builder::default().with_service_name(service_name) 86 | } 87 | --------------------------------------------------------------------------------