├── .circleci └── config.yml ├── .editorconfig ├── .formatter.exs ├── .gitignore ├── LICENSE ├── README.md ├── config └── config.exs ├── dialyzer.ignore-warnings ├── lib └── opencensus │ ├── logger.ex │ ├── span.ex │ ├── span_context.ex │ ├── test_support │ └── span_capture_reporter.ex │ └── trace.ex ├── mix.exs ├── mix.lock └── test ├── opencensus_logger_test.exs ├── opencensus_test.exs ├── opencensus_test_support_span_capture_reporter_test.exs ├── opencensus_trace_async_test.exs └── test_helper.exs /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Elixir CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/language-elixir/ for more details 4 | version: 2.1 5 | 6 | commands: 7 | fetch_deps: 8 | description: "Fetch deps, build, and cache them" 9 | parameters: 10 | elixir_version: 11 | type: string 12 | default: "any" 13 | steps: 14 | - restore_cache: 15 | keys: 16 | - deps-v1-<>-{{ checksum "mix.lock" }}-{{ .Branch }}-{{ .Revision }} 17 | - deps-v1-<>-{{ checksum "mix.lock" }}-{{ .Branch }}- 18 | - deps-v1-<>-{{ checksum "mix.lock" }}- 19 | - deps-v1-<>- 20 | - run: mix do local.hex --force, local.rebar --force 21 | - run: mix do deps.get, deps.compile 22 | - save_cache: 23 | key: deps-v1-{{ .Branch }}-{{ .Revision }} 24 | paths: 25 | - "deps" 26 | - "_build" 27 | 28 | jobs: 29 | test: 30 | parameters: 31 | elixir_version: 32 | type: string 33 | description: Elixir version to test against to 34 | docker: 35 | - image: elixir:<> 36 | working_directory: ~/repo 37 | steps: 38 | - checkout 39 | - fetch_deps: 40 | elixir_version: <> 41 | - run: mkdir -p reports/exunit 42 | - run: mix coveralls.json 43 | - run: bash <(curl -s https://codecov.io/bash) 44 | - store_test_results: 45 | path: reports 46 | 47 | dialyzer: 48 | docker: 49 | - image: elixir:1.8 50 | working_directory: ~/repo 51 | steps: 52 | - checkout 53 | - fetch_deps 54 | - restore_cache: 55 | keys: 56 | - dialyzer-v1-{{ checksum "mix.lock" }} 57 | - dialyzer-v1 58 | - run: mix dialyzer --plt 59 | - save_cache: 60 | key: dialyzer-v1-{{ checksum "mix.lock" }} 61 | paths: 62 | - "_build" 63 | - run: mix dialyzer --halt-exit-status 64 | 65 | format: 66 | docker: 67 | - image: elixir:1.8 68 | working_directory: ~/repo 69 | steps: 70 | - checkout 71 | - fetch_deps 72 | - run: mix format --check-formatted 73 | 74 | inchci: 75 | docker: 76 | # Elixir 1.6 as InchCI do not yet work with 1.7 77 | - image: elixir:1.6 78 | working_directory: ~/repo 79 | steps: 80 | - checkout 81 | - fetch_deps 82 | - run: mix inch.report 83 | 84 | workflows: 85 | version: 2 86 | lints: 87 | jobs: 88 | - dialyzer 89 | - format 90 | - inchci 91 | testing: 92 | jobs: 93 | - test: 94 | name: "Elixir 1.9" 95 | elixir_version: "1.9" 96 | - test: 97 | name: "Elixir 1.8" 98 | elixir_version: "1.8" 99 | - test: 100 | name: "Elixir 1.7" 101 | elixir_version: "1.7" 102 | - test: 103 | name: "Elixir 1.6" 104 | elixir_version: "1.6" 105 | - test: 106 | name: "Elixir 1.5" 107 | elixir_version: "1.5" 108 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | trim_trailing_whitespace = true 7 | charset = utf-8 8 | indent_style = space 9 | 10 | [*.{md}] 11 | indent_size = 4 12 | 13 | [*.{ex,exs}] 14 | indent_size = 2 15 | 16 | [Makefile] 17 | indent_style = tab 18 | -------------------------------------------------------------------------------- /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where 3rd-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | opencensus-*.tar 24 | 25 | # Ignore workspace settings for .vscode 26 | .vscode 27 | 28 | # Ignore .vscode ElixirLS plugin working directory 29 | .elixir_ls 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Opencensus 2 | 3 | [![CircleCI](https://circleci.com/gh/opencensus-beam/opencensus_elixir.svg?style=svg)](https://circleci.com/gh/opencensus-beam/opencensus_elixir) 4 | [![Hex version badge](https://img.shields.io/hexpm/v/opencensus_elixir.svg)](https://hex.pm/packages/opencensus_elixir) 5 | 6 | Wraps some [`:opencensus`][:opencensus] capabilities for Elixir users so 7 | they don't have to [learn them some Erlang][lyse] in order to get 8 | [OpenCensus] distributed tracing. 9 | 10 | [opencensus]: http://opencensus.io 11 | [:opencensus]: https://hex.pm/packages/opencensus 12 | [lyse]: https://learnyousomeerlang.com 13 | 14 | ## Installation 15 | 16 | Add `opencensus_elixir` to your `deps` in `mix.exs`: 17 | 18 | ```elixir 19 | def deps do 20 | [ 21 | {:opencensus, "~> 0.9"}, 22 | {:opencensus_elixir, "~> 0.3.0"} 23 | ] 24 | end 25 | ``` 26 | 27 | ## Usage 28 | 29 | Wrap your code with the 30 | [`Opencensus.Trace.with_child_span/3`][oce-with_child_span-3] macro to 31 | execute it in a fresh span: 32 | 33 | ```elixir 34 | import Opencensus.Trace 35 | 36 | def traced_fn(arg) do 37 | with_child_span "traced" do 38 | :YOUR_CODE_HERE 39 | end 40 | end 41 | ``` 42 | 43 | ## Alternatives 44 | 45 | If you prefer driving Erlang packages directly (see also `:telemetry`), copy 46 | what you need from `lib/opencensus/trace.ex` and call 47 | `Logger.set_logger_metadata/0` if there's any chance of Logger use within 48 | the span. 49 | 50 | ```elixir 51 | def traced_fn() do 52 | try do 53 | :ocp.with_child_span("name", %{fn: :traced_fn, mod: __MODULE__}) 54 | Logger.set_logger_metadata() 55 | 56 | :YOUR_CODE_HERE 57 | after 58 | :ocp.finish_span() 59 | Logger.set_logger_metadata() 60 | end 61 | end 62 | ``` 63 | 64 | If `try .. after .. end` feels too bulky and you're _sure_ you won't need 65 | Logger, try [`:ocp.with_child_span/3`][ocp-with_child_span-3]: 66 | 67 | ```elixir 68 | def traced_fn() do 69 | :ocp.with_child_span("traced", %{fn: :traced_fn, mod: __MODULE__}, fn () -> 70 | :YOUR_CODE_HERE 71 | end) 72 | end 73 | ``` 74 | 75 | ## Troubleshooting 76 | 77 | To see your spans, use the `:oc_reporter_stdout` reporter, either in config: 78 | 79 | ```elixir 80 | config :opencensus, reporters: [{:oc_reporter_stdout, []}] 81 | ``` 82 | 83 | ... or at the `iex` prompt: 84 | 85 | ```plain 86 | iex> :oc_reporter.register(:oc_reporter_stdout) 87 | ``` 88 | 89 | [oce-with_child_span-3]: https://hexdocs.pm/opencensus_elixir/Opencensus.Trace.html#with_child_span/3 90 | [ocp-with_child_span-3]: https://hexdocs.pm/opencensus/ocp.html#with_child_span-3 91 | -------------------------------------------------------------------------------- /config/config.exs: -------------------------------------------------------------------------------- 1 | # This file is responsible for configuring your application 2 | # and its dependencies with the aid of the Mix.Config module. 3 | use Mix.Config 4 | 5 | if Mix.env() == :test do 6 | config :junit_formatter, 7 | report_file: "report.xml", 8 | report_dir: "reports/exunit" 9 | 10 | config :opencensus, 11 | reporters: [{Opencensus.TestSupport.SpanCaptureReporter, []}], 12 | send_interval_ms: 100 13 | end 14 | -------------------------------------------------------------------------------- /dialyzer.ignore-warnings: -------------------------------------------------------------------------------- 1 | :0: Unknown type erlang:stack_item/0 2 | :0: Unknown type opencensus:span_kind/0 3 | -------------------------------------------------------------------------------- /lib/opencensus/logger.ex: -------------------------------------------------------------------------------- 1 | defmodule Opencensus.Logger do 2 | @moduledoc """ 3 | Updates Elixir's Logger metadata to match Erlang's logger metadata. 4 | 5 | `set_logger_metadata/0` and `set_logger_metadata/1` update the following attributes in 6 | `Logger.metadata/0`: 7 | 8 | * `trace_id` 9 | * `span_id` 10 | * `trace_options` 11 | 12 | You won't need to use this module if you use the macros in `Opencensus.Trace`. 13 | 14 | If you use `Logging`, or users of your framework might plausibly use `Logging`, you [SHOULD] 15 | call `set_logger_metadata/0` after using functions in [`:ocp`] to manipulate the span context 16 | stored in the process dictionary. 17 | 18 | [:ocp]: https://hexdocs.pm/opencensus/ocp.html 19 | 20 | We'll be able to deprecate these functions when Elixir unifies `:logger` and `Logger` metadata 21 | in 1.10 or whichever release [first requires Erlang 21 or better][6611]. To check whether that 22 | has already happened, try this at the `iex` prompt: 23 | 24 | ```elixir 25 | :ocp.with_child_span("traced") 26 | :logger.get_process_metadata() 27 | Logger.metadata(() 28 | ``` 29 | 30 | If the metadata output from the second and third lines match, we can start deprecating. 31 | 32 | [6611]: https://github.com/elixir-lang/elixir/issues/6611 33 | [MAY]: https://tools.ietf.org/html/rfc2119#section-5 34 | [SHOULD]: https://tools.ietf.org/html/rfc2119#section-3 35 | """ 36 | 37 | alias Opencensus.SpanContext 38 | 39 | @doc "Sets the Logger metadata according to the current span context." 40 | def set_logger_metadata, do: set_logger_metadata(:ocp.current_span_ctx()) 41 | 42 | @doc "Sets the Logger metadata according to a supplied span context." 43 | @spec set_logger_metadata(:opencensus.span_ctx() | :undefined) :: :ok 44 | def set_logger_metadata(span_ctx) 45 | 46 | def set_logger_metadata(:undefined), do: set_logger_metadata(nil, nil, nil) 47 | 48 | def set_logger_metadata(span_ctx) do 49 | context = SpanContext.from(span_ctx) 50 | 51 | set_logger_metadata( 52 | SpanContext.hex_trace_id(context.trace_id), 53 | SpanContext.hex_span_id(context.span_id), 54 | context.trace_options 55 | ) 56 | end 57 | 58 | defp set_logger_metadata(trace_id, span_id, trace_options) do 59 | Logger.metadata(trace_id: trace_id, span_id: span_id, trace_options: trace_options) 60 | :ok 61 | end 62 | end 63 | -------------------------------------------------------------------------------- /lib/opencensus/span.ex: -------------------------------------------------------------------------------- 1 | defmodule Opencensus.Span do 2 | @moduledoc """ 3 | Elixir convenience translation of `:opencensus.span`. 4 | 5 | Most likely to be of use while writing unit tests, or packages that deal with spans. 6 | Less likely to be of use while writing application code. 7 | """ 8 | 9 | alias Opencensus.SpanContext 10 | 11 | require Record 12 | @fields Record.extract(:span, from_lib: "opencensus/include/opencensus.hrl") 13 | Record.defrecordp(:span, @fields) 14 | 15 | defstruct Keyword.keys(@fields) 16 | 17 | @doc "Get a span struct given a record." 18 | @spec from(:opencensus.span()) :: %__MODULE__{} 19 | def from(record) when Record.is_record(record, :span), do: struct!(__MODULE__, span(record)) 20 | 21 | @doc "Load a span from ETS. Only works until it has been sent." 22 | @spec load(:opencensus.span_ctx() | integer() | :undefined) :: %__MODULE__{} | nil 23 | def load(span_id_or_ctx) 24 | 25 | def load(:undefined), do: nil 26 | 27 | def load(span_id) when is_integer(span_id) do 28 | case :ets.lookup(:oc_span_tab, span_id) do 29 | [record] -> from(record) 30 | [] -> nil 31 | end 32 | end 33 | 34 | def load(span_ctx) when is_tuple(span_ctx) do 35 | span_ctx |> SpanContext.from() |> Map.get(:span_id) |> load() 36 | end 37 | 38 | @doc false 39 | def began_monotonic(record) when Record.is_record(record, :span) do 40 | {native_time, _native_offset} = span(record, :start_time) 41 | native_time 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /lib/opencensus/span_context.ex: -------------------------------------------------------------------------------- 1 | defmodule Opencensus.SpanContext do 2 | @moduledoc """ 3 | Elixir convenience translation of `:opencensus.span_ctx`. 4 | 5 | Most likely to be of use while writing unit tests, or packages that deal with spans. 6 | Less likely to be of use while writing application code. 7 | """ 8 | 9 | require Record 10 | @fields Record.extract(:span_ctx, from_lib: "opencensus/include/opencensus.hrl") 11 | Record.defrecordp(:span_ctx, @fields) 12 | 13 | defstruct Keyword.keys(@fields) 14 | 15 | @doc """ 16 | Convert a span context. 17 | 18 | iex> :opencensus.span_ctx() 19 | :undefined 20 | iex> :opencensus.span_ctx() |> Opencensus.SpanContext.from() 21 | nil 22 | 23 | iex> trace_id = 158162877550332985110351567058860353513 24 | iex> span_id = 13736401818514315360 25 | iex> span_ctx = {:span_ctx, trace_id, span_id, 1, :undefined} 26 | iex> Opencensus.SpanContext.from(span_ctx) 27 | %Opencensus.SpanContext{ 28 | span_id: 13736401818514315360, 29 | trace_id: 158162877550332985110351567058860353513, 30 | trace_options: 1, 31 | tracestate: :undefined 32 | } 33 | """ 34 | @spec from(:opencensus.span_ctx() | :undefined) :: %__MODULE__{} 35 | def from(record) 36 | 37 | def from(record) when Record.is_record(record, :span_ctx), 38 | do: struct!(__MODULE__, span_ctx(record)) 39 | 40 | def from(:undefined), do: nil 41 | 42 | @doc "Return the 32-digit hex representation of a trace ID." 43 | @spec hex_trace_id(:undefined | integer()) :: String.t() 44 | def hex_trace_id(trace_id) 45 | 46 | def hex_trace_id(n) when is_integer(n) and n > 0, 47 | do: :io_lib.format("~32.16.0b", [n]) |> to_string() 48 | 49 | def hex_trace_id(_), do: nil 50 | 51 | @doc "Return the 16-digit hex representation of a span ID." 52 | @spec hex_span_id(:undefined | integer()) :: String.t() 53 | def hex_span_id(span_id) 54 | 55 | def hex_span_id(n) when is_integer(n) and n > 0, 56 | do: :io_lib.format("~16.16.0b", [n]) |> to_string() 57 | 58 | def hex_span_id(_), do: nil 59 | end 60 | -------------------------------------------------------------------------------- /lib/opencensus/test_support/span_capture_reporter.ex: -------------------------------------------------------------------------------- 1 | defmodule Opencensus.TestSupport.SpanCaptureReporter do 2 | @moduledoc """ 3 | An `:opencensus.reporter` to capture spans for tests. 4 | 5 | `:oc_reporter` can't unregister reporters, but `:telemetry` can detach handlers, so we configure 6 | `:opencensus` to send spans to use our reporter, in `mix.exs`: 7 | 8 | ```elixir 9 | if Mix.env() == :test do 10 | config :opencensus, 11 | send_interval_ms: 100, 12 | reporters: [{Opencensus.TestSupport.SpanCaptureReporter, []}] 13 | end 14 | ``` 15 | 16 | It'll call `:telemetry.execute/3` whenever spans are reported. If you've called `attach/0`, 17 | the handler will convert the spans to structs with `Span.from/1` and deliver them to your 18 | process inbox. To collect them, call `collect/0`. When you're finished, call `detach/0`: 19 | 20 | ```elixir 21 | defmodule NyApp.SpanCaptureTest do 22 | use ExUnit.Case, async: false 23 | 24 | alias Opencensus.TestSupport.SpanCaptureReporter 25 | 26 | setup do 27 | SpanCaptureReporter.attach() 28 | on_exit(make_ref(), &SpanCaptureReporter.detach/0) 29 | end 30 | 31 | test "can gather spans" do 32 | :ocp.with_child_span("our span name") 33 | :ocp.finish_span() 34 | [span] = SpanCaptureReporter.collect() 35 | assert span.name == "our span name" 36 | end 37 | end 38 | ``` 39 | """ 40 | 41 | alias Opencensus.Span 42 | 43 | @behaviour :oc_reporter 44 | 45 | @impl true 46 | def init([]), do: [] 47 | 48 | @impl true 49 | def report(spans, []) do 50 | :telemetry.execute([__MODULE__], %{}, %{spans: spans}) 51 | :ok 52 | end 53 | 54 | @doc false 55 | def handler([__MODULE__], %{}, %{spans: spans}, {pid, attached_monotonic}) do 56 | started_after_attach? = fn span -> span |> Span.began_monotonic() >= attached_monotonic end 57 | filtered = spans |> Enum.filter(started_after_attach?) 58 | send(pid, {:spans, filtered}) 59 | end 60 | 61 | @doc "Attach the reporter to deliver spans to your process inbox." 62 | def attach do 63 | :telemetry.attach(__MODULE__, [__MODULE__], &handler/4, {self(), :erlang.monotonic_time()}) 64 | end 65 | 66 | @doc """ 67 | Detach the reporter to stop delivering spans to your process inbox. 68 | 69 | If still attached, triggers span delivery before detaching. 70 | """ 71 | def detach do 72 | if handler_attached?(), do: trigger_and_wait_for_span_delivery() 73 | :telemetry.detach(__MODULE__) 74 | end 75 | 76 | @doc """ 77 | Collect spans from your process inbox. 78 | 79 | If still attached, triggers span delivery before collection. 80 | """ 81 | @spec collect() :: list(%Span{}) 82 | def collect do 83 | if handler_attached?(), do: trigger_and_wait_for_span_delivery() 84 | collect_span_records([]) |> Enum.map(&Span.from/1) 85 | end 86 | 87 | defp trigger_and_wait_for_span_delivery do 88 | send(:oc_reporter, :report_spans) 89 | :timer.sleep(1) 90 | end 91 | 92 | defp handler_attached? do 93 | :telemetry.list_handlers([__MODULE__]) != [] 94 | end 95 | 96 | defp collect_span_records(acc) when is_list(acc) do 97 | receive do 98 | {:spans, spans} -> collect_span_records(acc ++ spans) 99 | after 100 | 1 -> acc 101 | end 102 | end 103 | end 104 | -------------------------------------------------------------------------------- /lib/opencensus/trace.ex: -------------------------------------------------------------------------------- 1 | defmodule Opencensus.Trace do 2 | @moduledoc """ 3 | Macros to help Elixir programmers use OpenCensus tracing. 4 | """ 5 | 6 | @doc """ 7 | Wrap the given block in a child span with the given label/name and optional attributes. 8 | 9 | Sets `Logger.metadata/0` with `Opencensus.Logger.set_logger_metadata/0` after changing the span 10 | context tracked in the process dictionary. 11 | 12 | No attributes: 13 | 14 | ```elixir 15 | with_child_span "child_span" do 16 | :do_something 17 | end 18 | 19 | with_child_span "child_span", %{} do 20 | :do_something 21 | end 22 | ``` 23 | 24 | Custom attributes: 25 | 26 | ```elixir 27 | with_child_span "child_span", [:module, :function, %{"custom_id" => "xxx"}] do 28 | :do_something 29 | end 30 | ``` 31 | 32 | Automatic insertion of the `module`, `file`, `line`, or `function`: 33 | 34 | ```elixir 35 | with_child_span "child_span", [:module, :function, %{}] do 36 | :do_something 37 | end 38 | ``` 39 | 40 | Collapsing multiple attribute maps (last wins): 41 | 42 | ```elixir 43 | with_child_span "child_span", [:function, %{"a" => "b", "c" => "d"}, %{"c" => "e"}] do 44 | :do_something 45 | end 46 | ``` 47 | """ 48 | defmacro with_child_span(label, attributes \\ quote(do: %{}), do: block) do 49 | line = __CALLER__.line 50 | module = __CALLER__.module 51 | file = __CALLER__.file 52 | function = format_function(__CALLER__.function) 53 | 54 | computed_attributes = 55 | compute_attributes(attributes, %{ 56 | line: line, 57 | module: module, 58 | file: file, 59 | function: function 60 | }) 61 | 62 | quote do 63 | parent_span_ctx = :ocp.current_span_ctx() 64 | 65 | new_span_ctx = 66 | :oc_trace.start_span(unquote(label), parent_span_ctx, %{ 67 | :attributes => unquote(computed_attributes) 68 | }) 69 | 70 | _ = :ocp.with_span_ctx(new_span_ctx) 71 | Opencensus.Logger.set_logger_metadata() 72 | 73 | try do 74 | unquote(block) 75 | after 76 | _ = :oc_trace.finish_span(new_span_ctx) 77 | _ = :ocp.with_span_ctx(parent_span_ctx) 78 | Opencensus.Logger.set_logger_metadata() 79 | end 80 | end 81 | end 82 | 83 | defp compute_attributes(attributes, default_attributes) when is_list(attributes) do 84 | {atoms, custom_attributes} = Enum.split_with(attributes, &is_atom/1) 85 | 86 | default_attributes = compute_default_attributes(atoms, default_attributes) 87 | 88 | case Enum.split_with(custom_attributes, fn 89 | ## map ast 90 | {:%{}, _, _} -> true 91 | _ -> false 92 | end) do 93 | {[ca_map | ca_maps], []} -> 94 | ## custom attributes are literal maps, merge 'em 95 | {:%{}, meta, custom_attributes} = 96 | List.foldl(ca_maps, ca_map, fn {:%{}, _, new_pairs}, {:%{}, meta, old_pairs} -> 97 | {:%{}, meta, 98 | :maps.to_list(:maps.merge(:maps.from_list(old_pairs), :maps.from_list(new_pairs)))} 99 | end) 100 | 101 | {:%{}, meta, 102 | :maps.to_list(:maps.merge(:maps.from_list(custom_attributes), default_attributes))} 103 | 104 | {_ca_maps, _other_calls} -> 105 | [f_ca | r_ca] = custom_attributes 106 | 107 | quote do 108 | unquote( 109 | List.foldl(r_ca ++ [Macro.escape(default_attributes)], f_ca, fn ca, acc -> 110 | quote do 111 | Map.merge(unquote(acc), unquote(ca)) 112 | end 113 | end) 114 | ) 115 | end 116 | end 117 | end 118 | 119 | defp compute_attributes(attributes, _default_attributes) do 120 | attributes 121 | end 122 | 123 | defp compute_default_attributes(atoms, default_attributes) do 124 | List.foldl(atoms, %{}, fn 125 | :default, _acc -> 126 | default_attributes 127 | 128 | atom, acc -> 129 | Map.put(acc, atom, Map.fetch!(default_attributes, atom)) 130 | end) 131 | end 132 | 133 | defp format_function(nil), do: nil 134 | defp format_function({name, arity}), do: "#{name}/#{arity}" 135 | 136 | @doc """ 137 | Drop-in replacement for `Task.async/1` that propagates the process' span context. 138 | 139 | Does NOT start a new span for what's inside. Consider `with_child_span/3`. 140 | """ 141 | @spec async((() -> any())) :: Task.t() 142 | def async(fun) when is_function(fun, 0) do 143 | async(:erlang, :apply, [fun, []]) 144 | end 145 | 146 | @doc """ 147 | Drop-in replacement for `Task.async/3` that propagates the process' span context. 148 | 149 | Does NOT start a new span for what's inside. Consider `with_child_span/3`. 150 | """ 151 | @spec async(module(), atom(), [term()]) :: Task.t() 152 | def async(module, function_name, args) 153 | when is_atom(module) and is_atom(function_name) and is_list(args) do 154 | original_span_ctx = :ocp.current_span_ctx() 155 | 156 | wrapper = fn -> 157 | :ocp.with_span_ctx(original_span_ctx) 158 | apply(module, function_name, args) 159 | end 160 | 161 | Task.async(wrapper) 162 | end 163 | 164 | @doc """ 165 | Drop-in replacement for `Task.await/2`. 166 | """ 167 | @spec await(Task.t(), :infinity | pos_integer()) :: term() 168 | defdelegate await(task, timeout \\ 5000), to: Task 169 | end 170 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule OpencensusElixir.MixProject do 2 | use Mix.Project 3 | 4 | def project do 5 | [ 6 | app: :opencensus_elixir, 7 | version: "0.5.0", 8 | elixir: "~> 1.5", 9 | start_permanent: Mix.env() == :prod, 10 | deps: deps(), 11 | dialyzer: dialyzer(), 12 | test_coverage: [tool: ExCoveralls], 13 | aliases: aliases(), 14 | description: description(), 15 | package: package(), 16 | preferred_cli_env: [ 17 | coveralls: :test, 18 | "coveralls.html": :test, 19 | "coveralls.json": :test, 20 | credo: :test, 21 | docs: :docs, 22 | "inchci.add": :docs, 23 | "inch.report": :docs, 24 | "test.watch": :test 25 | ] 26 | ] 27 | end 28 | 29 | # Run "mix help compile.app" to learn about applications. 30 | def application do 31 | [ 32 | extra_applications: [:logger] 33 | ] 34 | end 35 | 36 | # Run "mix help deps" to learn about dependencies. 37 | defp deps do 38 | [ 39 | {:opencensus, "~> 0.9"}, 40 | 41 | # Documentation 42 | {:ex_doc, ">= 0.0.0", only: [:docs]}, 43 | {:inch_ex, "~> 1.0", only: [:docs]}, 44 | 45 | # Testing 46 | {:credo, "~> 1.1.0", only: [:test]}, 47 | {:dialyxir, ">= 0.0.0", runtime: false, only: [:dev, :test]}, 48 | {:excoveralls, "~> 0.10.3", only: [:test]}, 49 | {:junit_formatter, ">= 0.0.0", only: [:test]}, 50 | {:mix_test_watch, "~> 0.8", runtime: false, only: [:test]}, 51 | {:telemetry, "~> 0.4 or ~> 1.0"} 52 | ] 53 | end 54 | 55 | defp dialyzer() do 56 | [ 57 | ignore_warnings: "dialyzer.ignore-warnings", 58 | list_unused_filters: true, 59 | plt_add_apps: [], 60 | plt_add_deps: [:app_tree] 61 | ] 62 | end 63 | 64 | defp aliases do 65 | [ 66 | test: "test --no-start" 67 | ] 68 | end 69 | 70 | defp description() do 71 | "Elixir library for OpenCensus tracing" 72 | end 73 | 74 | defp package() do 75 | [ 76 | licenses: ["Apache 2.0"], 77 | links: %{ 78 | "GitHub" => "https://github.com/opencensus-beam/opencensus_elixir", 79 | "OpenCensus" => "https://opencensus.io", 80 | "OpenCensus Erlang" => "https://github.com/census-instrumentation/opencensus-erlang", 81 | "OpenCensus BEAM" => "https://github.com/opencensus-beam" 82 | } 83 | ] 84 | end 85 | end 86 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "bunt": {:hex, :bunt, "0.2.0", "951c6e801e8b1d2cbe58ebbd3e616a869061ddadcc4863d0a2182541acae9a38", [:mix], [], "hexpm", "7af5c7e09fe1d40f76c8e4f9dd2be7cebd83909f31fee7cd0e9eadc567da8353"}, 3 | "certifi": {:hex, :certifi, "2.9.0", "6f2a475689dd47f19fb74334859d460a2dc4e3252a3324bd2111b8f0429e7e21", [:rebar3], [], "hexpm", "266da46bdb06d6c6d35fde799bcb28d36d985d424ad7c08b5bb48f5b5cdd4641"}, 4 | "counters": {:hex, :counters, "0.2.1", "aa3d97e88f92573488987193d0f48efce0f3b2cd1443bf4ee760bc7f99322f0c", [:mix, :rebar3], [], "hexpm", "a020c714992f7db89178d27e1f39909e5d77da3b80daa4d6015877ed0c94b8ab"}, 5 | "credo": {:hex, :credo, "1.1.5", "caec7a3cadd2e58609d7ee25b3931b129e739e070539ad1a0cd7efeeb47014f4", [:mix], [{:bunt, "~> 0.2.0", [hex: :bunt, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "d0bbd3222607ccaaac5c0340f7f525c627ae4d7aee6c8c8c108922620c5b6446"}, 6 | "ctx": {:hex, :ctx, "0.6.0", "8ff88b70e6400c4df90142e7f130625b82086077a45364a78d208ed3ed53c7fe", [:rebar3], [], "hexpm", "a14ed2d1b67723dbebbe423b28d7615eb0bdcba6ff28f2d1f1b0a7e1d4aa5fc2"}, 7 | "dialyxir": {:hex, :dialyxir, "1.1.0", "c5aab0d6e71e5522e77beff7ba9e08f8e02bad90dfbeffae60eaf0cb47e29488", [:mix], [{:erlex, ">= 0.2.6", [hex: :erlex, repo: "hexpm", optional: false]}], "hexpm", "07ea8e49c45f15264ebe6d5b93799d4dd56a44036cf42d0ad9c960bc266c0b9a"}, 8 | "earmark": {:hex, :earmark, "1.3.0", "17f0c38eaafb4800f746b457313af4b2442a8c2405b49c645768680f900be603", [:mix], [], "hexpm", "f8b8820099caf0d5e72ae6482d2b0da96f213cbbe2b5b2191a37966e119eaa27"}, 9 | "earmark_parser": {:hex, :earmark_parser, "1.4.25", "2024618731c55ebfcc5439d756852ec4e85978a39d0d58593763924d9a15916f", [:mix], [], "hexpm", "56749c5e1c59447f7b7a23ddb235e4b3defe276afc220a6227237f3efe83f51e"}, 10 | "erlex": {:hex, :erlex, "0.2.6", "c7987d15e899c7a2f34f5420d2a2ea0d659682c06ac607572df55a43753aa12e", [:mix], [], "hexpm", "2ed2e25711feb44d52b17d2780eabf998452f6efda104877a3881c2f8c0c0c75"}, 11 | "ex_doc": {:hex, :ex_doc, "0.28.4", "001a0ea6beac2f810f1abc3dbf4b123e9593eaa5f00dd13ded024eae7c523298", [:mix], [{:earmark_parser, "~> 1.4.19", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_elixir, "~> 0.14", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1", [hex: :makeup_erlang, repo: "hexpm", optional: false]}], "hexpm", "bf85d003dd34911d89c8ddb8bda1a958af3471a274a4c2150a9c01c78ac3f8ed"}, 12 | "excoveralls": {:hex, :excoveralls, "0.10.6", "e2b9718c9d8e3ef90bc22278c3f76c850a9f9116faf4ebe9678063310742edc2", [:mix], [{:hackney, "~> 1.13", [hex: :hackney, repo: "hexpm", optional: false]}, {:jason, "~> 1.0", [hex: :jason, repo: "hexpm", optional: false]}], "hexpm", "b06c73492aa9940c4c29cfc1356bcf5540ae318f17b423749a0615a66ee3e049"}, 13 | "file_system": {:hex, :file_system, "0.2.10", "fb082005a9cd1711c05b5248710f8826b02d7d1784e7c3451f9c1231d4fc162d", [:mix], [], "hexpm", "41195edbfb562a593726eda3b3e8b103a309b733ad25f3d642ba49696bf715dc"}, 14 | "hackney": {:hex, :hackney, "1.18.1", "f48bf88f521f2a229fc7bae88cf4f85adc9cd9bcf23b5dc8eb6a1788c662c4f6", [:rebar3], [{:certifi, "~>2.9.0", [hex: :certifi, repo: "hexpm", optional: false]}, {:idna, "~>6.1.0", [hex: :idna, repo: "hexpm", optional: false]}, {:metrics, "~>1.0.0", [hex: :metrics, repo: "hexpm", optional: false]}, {:mimerl, "~>1.1", [hex: :mimerl, repo: "hexpm", optional: false]}, {:parse_trans, "3.3.1", [hex: :parse_trans, repo: "hexpm", optional: false]}, {:ssl_verify_fun, "~>1.1.0", [hex: :ssl_verify_fun, repo: "hexpm", optional: false]}, {:unicode_util_compat, "~>0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "a4ecdaff44297e9b5894ae499e9a070ea1888c84afdd1fd9b7b2bc384950128e"}, 15 | "idna": {:hex, :idna, "6.1.1", "8a63070e9f7d0c62eb9d9fcb360a7de382448200fbbd1b106cc96d3d8099df8d", [:rebar3], [{:unicode_util_compat, "~>0.7.0", [hex: :unicode_util_compat, repo: "hexpm", optional: false]}], "hexpm", "92376eb7894412ed19ac475e4a86f7b413c1b9fbb5bd16dccd57934157944cea"}, 16 | "inch_ex": {:hex, :inch_ex, "1.0.1", "1f0af1a83cec8e56f6fc91738a09c838e858db3d78ef5f2ec040fe4d5a62dabf", [:mix], [{:poison, "~> 1.5 or ~> 2.0 or ~> 3.0", [hex: :poison, repo: "hexpm", optional: false]}], "hexpm", "08fd8a9205d3e1aefad9d7cb2a7f6b346e4a3e6ff09e139f6ec978f3a479ba14"}, 17 | "jason": {:hex, :jason, "1.3.0", "fa6b82a934feb176263ad2df0dbd91bf633d4a46ebfdffea0c8ae82953714946", [:mix], [{:decimal, "~> 1.0 or ~> 2.0", [hex: :decimal, repo: "hexpm", optional: true]}], "hexpm", "53fc1f51255390e0ec7e50f9cb41e751c260d065dcba2bf0d08dc51a4002c2ac"}, 18 | "jsx": {:hex, :jsx, "2.9.0", "d2f6e5f069c00266cad52fb15d87c428579ea4d7d73a33669e12679e203329dd", [:mix, :rebar3], [], "hexpm"}, 19 | "junit_formatter": {:hex, :junit_formatter, "3.3.1", "c729befb848f1b9571f317d2fefa648e9d4869befc4b2980daca7c1edc468e40", [:mix], [], "hexpm", "761fc5be4b4c15d8ba91a6dafde0b2c2ae6db9da7b8832a55b5a1deb524da72b"}, 20 | "makeup": {:hex, :makeup, "1.1.0", "6b67c8bc2882a6b6a445859952a602afc1a41c2e08379ca057c0f525366fc3ca", [:mix], [{:nimble_parsec, "~> 1.2.2 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "0a45ed501f4a8897f580eabf99a2e5234ea3e75a4373c8a52824f6e873be57a6"}, 21 | "makeup_elixir": {:hex, :makeup_elixir, "0.16.0", "f8c570a0d33f8039513fbccaf7108c5d750f47d8defd44088371191b76492b0b", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "28b2cbdc13960a46ae9a8858c4bebdec3c9a6d7b4b9e7f4ed1502f8159f338e7"}, 22 | "makeup_erlang": {:hex, :makeup_erlang, "0.1.1", "3fcb7f09eb9d98dc4d208f49cc955a34218fc41ff6b84df7c75b3e6e533cc65f", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "174d0809e98a4ef0b3309256cbf97101c6ec01c4ab0b23e926a9e17df2077cbb"}, 23 | "metrics": {:hex, :metrics, "1.0.1", "25f094dea2cda98213cecc3aeff09e940299d950904393b2a29d191c346a8486", [:rebar3], [], "hexpm", "69b09adddc4f74a40716ae54d140f93beb0fb8978d8636eaded0c31b6f099f16"}, 24 | "mimerl": {:hex, :mimerl, "1.2.0", "67e2d3f571088d5cfd3e550c383094b47159f3eee8ffa08e64106cdf5e981be3", [:rebar3], [], "hexpm", "f278585650aa581986264638ebf698f8bb19df297f66ad91b18910dfc6e19323"}, 25 | "mix_test_watch": {:hex, :mix_test_watch, "0.9.0", "c72132a6071261893518fa08e121e911c9358713f62794a90c95db59042af375", [:mix], [{:file_system, "~> 0.2.1 or ~> 0.3", [hex: :file_system, repo: "hexpm", optional: false]}], "hexpm", "817dec4a7f6edf260258002f99ac8ffaf7a8f395b27bf2d13ec24018beecec8a"}, 26 | "nimble_parsec": {:hex, :nimble_parsec, "1.2.3", "244836e6e3f1200c7f30cb56733fd808744eca61fd182f731eac4af635cc6d0b", [:mix], [], "hexpm", "c8d789e39b9131acf7b99291e93dae60ab48ef14a7ee9d58c6964f59efb570b0"}, 27 | "opencensus": {:hex, :opencensus, "0.9.3", "a7bb2771b40593f8513fc14eb70d822e88bea1b2fb552e19a1e2e6f98371427a", [:rebar3], [{:counters, "~> 0.2.1", [hex: :counters, repo: "hexpm", optional: false]}, {:ctx, "~> 0.5", [hex: :ctx, repo: "hexpm", optional: false]}, {:wts, "~> 0.3", [hex: :wts, repo: "hexpm", optional: false]}], "hexpm", "9495b4fa817f10a7cdf8b69cca929470aeda0633a04ea18cff6a0a9ea03a03e9"}, 28 | "parse_trans": {:hex, :parse_trans, "3.3.1", "16328ab840cc09919bd10dab29e431da3af9e9e7e7e6f0089dd5a2d2820011d8", [:rebar3], [], "hexpm", "07cd9577885f56362d414e8c4c4e6bdf10d43a8767abb92d24cbe8b24c54888b"}, 29 | "poison": {:hex, :poison, "3.1.0", "d9eb636610e096f86f25d9a46f35a9facac35609a7591b3be3326e99a0484665", [:mix], [], "hexpm", "fec8660eb7733ee4117b85f55799fd3833eb769a6df71ccf8903e8dc5447cfce"}, 30 | "rfc3339": {:hex, :rfc3339, "0.9.0", "2075653dc9407541c84b1e15f8bda2abe95fb17c9694025e079583f2d19c1060", [:mix, :rebar], [], "hexpm", "182314de35c9f4180b22eb5f22916d8d7a799c1109a060c752970273a9332ad6"}, 31 | "ssl_verify_fun": {:hex, :ssl_verify_fun, "1.1.6", "cf344f5692c82d2cd7554f5ec8fd961548d4fd09e7d22f5b62482e5aeaebd4b0", [:make, :mix, :rebar3], [], "hexpm", "bdb0d2471f453c88ff3908e7686f86f9be327d065cc1ec16fa4540197ea04680"}, 32 | "telemetry": {:hex, :telemetry, "0.4.3", "a06428a514bdbc63293cd9a6263aad00ddeb66f608163bdec7c8995784080818", [:rebar3], [], "hexpm", "eb72b8365ffda5bed68a620d1da88525e326cb82a75ee61354fc24b844768041"}, 33 | "unicode_util_compat": {:hex, :unicode_util_compat, "0.7.0", "bc84380c9ab48177092f43ac89e4dfa2c6d62b40b8bd132b1059ecc7232f9a78", [:rebar3], [], "hexpm", "25eee6d67df61960cf6a794239566599b09e17e668d3700247bc498638152521"}, 34 | "wts": {:hex, :wts, "0.4.0", "62d9dc400ad29f0d233f0665b9c75c8f8eb0a8af75eec921056ba4a73b0605a2", [:rebar3], [], "hexpm", "711bb675de2ce2b3ebab80a613ac93b994f74df44af4cff7970dc9eebe724869"}, 35 | } 36 | -------------------------------------------------------------------------------- /test/opencensus_logger_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Opencensus.LoggerTest do 2 | use ExUnit.Case, async: false 3 | 4 | describe "set_logger_metadata/1" do 5 | test "can set trace metadata" do 6 | # Make sure Logger doesn't already have any metadata 7 | assert Logger.metadata() == [], "setup: metadata not empty" 8 | :ocp.with_child_span("can set span") 9 | 10 | # Start a new span in the current process, and capture its details 11 | ctx = :ocp.current_span_ctx() 12 | {:span_ctx, trace_id, span_id, _, _} = ctx 13 | 14 | # Make sure Logger still doesn't have any metadata 15 | # If this fails, we can no-op set_logger_metadata for this Elixir+Erlang version. 16 | assert Logger.metadata() == [], "setup: ocp.with_child_span set Logger metadata!" 17 | 18 | # Act 19 | Opencensus.Logger.set_logger_metadata(ctx) 20 | 21 | # Assert 22 | assert Logger.metadata() == [ 23 | trace_options: 1, 24 | span_id: span_id |> hexify(16), 25 | trace_id: trace_id |> hexify(32) 26 | ] 27 | end 28 | 29 | test "can unset trace metadata" do 30 | # Make sure Logger doesn't already have any metadata 31 | assert Logger.metadata() == [], "setup: metadata not empty" 32 | 33 | # Give it some 34 | Logger.metadata( 35 | trace_options: 1, 36 | span_id: "b999f8f0c8cb65b3", 37 | trace_id: "82aebfb4ef02a0000000000000000001" 38 | ) 39 | 40 | # Make sure it got some 41 | assert Logger.metadata() != [] 42 | 43 | # Act 44 | Opencensus.Logger.set_logger_metadata(:undefined) 45 | 46 | # Assert 47 | assert Logger.metadata() == [] 48 | end 49 | end 50 | 51 | describe "set_logger_metadata/0" do 52 | test "can set and unset trace metadata" do 53 | assert Logger.metadata() == [], "setup: metadata not empty" 54 | :ocp.with_child_span("can set span") 55 | ctx = :ocp.current_span_ctx() 56 | {:span_ctx, trace_id, span_id, _, _} = ctx 57 | assert Logger.metadata() == [], "setup: ocp.with_child_span set Logger metadata!" 58 | 59 | Opencensus.Logger.set_logger_metadata() 60 | 61 | assert Logger.metadata() == [ 62 | trace_options: 1, 63 | span_id: span_id |> hexify(16), 64 | trace_id: trace_id |> hexify(32) 65 | ] 66 | 67 | :ocp.finish_span() 68 | Opencensus.Logger.set_logger_metadata() 69 | 70 | assert Logger.metadata() == [] 71 | end 72 | end 73 | 74 | defp hexify(n, digits) do 75 | n 76 | |> Integer.to_string(16) 77 | |> String.pad_leading(digits, "0") 78 | |> String.downcase() 79 | end 80 | end 81 | -------------------------------------------------------------------------------- /test/opencensus_test.exs: -------------------------------------------------------------------------------- 1 | defmodule OpencensusTest do 2 | use ExUnit.Case 3 | 4 | import Opencensus.TestSupport.SpanCaptureReporter 5 | import Opencensus.Trace 6 | 7 | alias Opencensus.Span 8 | 9 | test "verify attributes", _state do 10 | attach() 11 | on_exit(make_ref(), &detach/0) 12 | 13 | assert Logger.metadata() == [] 14 | assert :ocp.current_span_ctx() == :undefined 15 | 16 | with_child_span "child_span" do 17 | :do_something 18 | 19 | assert :ocp.current_span_ctx() != :undefined 20 | 21 | assert Logger.metadata() |> Keyword.keys() |> Enum.sort() == [ 22 | :span_id, 23 | :trace_id, 24 | :trace_options 25 | ] 26 | end 27 | 28 | assert [%Span{attributes: %{}}] = collect() 29 | 30 | with_child_span "child_span", %{"attr-1" => "value-1"} do 31 | :do_something 32 | end 33 | 34 | assert [%Span{attributes: %{"attr-1" => "value-1"}}] = collect() 35 | 36 | with_child_span "child_span", [:module, %{"attr-1" => "value-1"}] do 37 | :do_something 38 | end 39 | 40 | assert [%Span{attributes: %{"attr-1" => "value-1", module: OpencensusTest}}] = collect() 41 | 42 | with_child_span "child_span", [%{"attr-1" => "value-1"}, %{"attr-2" => "value-2"}] do 43 | :do_something 44 | end 45 | 46 | assert [%Span{attributes: %{"attr-1" => "value-1", "attr-2" => "value-2"}}] = collect() 47 | 48 | custom_attrs = %{"attr-1" => "value-1"} 49 | 50 | with_child_span "child_span", [:module, custom_attrs] do 51 | :do_something 52 | end 53 | 54 | assert [%Span{attributes: %{"attr-1" => "value-1", module: OpencensusTest}}] = collect() 55 | 56 | custom_attrs1 = %{"attr-1" => "value-1"} 57 | custom_attrs2 = %{"attr-2" => "value-2"} 58 | 59 | with_child_span "child_span", [ 60 | :module, 61 | %{"attr" => "value"}, 62 | custom_attrs1, 63 | :line, 64 | custom_attrs2 65 | ] do 66 | :do_something 67 | end 68 | 69 | assert [ 70 | %Span{ 71 | attributes: %{ 72 | "attr" => "value", 73 | "attr-1" => "value-1", 74 | "attr-2" => "value-2", 75 | line: line, 76 | module: OpencensusTest 77 | } 78 | } 79 | ] = collect() 80 | 81 | assert is_integer(line) 82 | 83 | with_child_span "child_span", [:function, %{"a" => "b", "c" => "d"}, %{"c" => "e"}] do 84 | :do_something 85 | end 86 | 87 | assert [ 88 | %Span{ 89 | attributes: %{ 90 | "a" => "b", 91 | "c" => "e", 92 | function: "test verify attributes/1" 93 | } 94 | } 95 | ] = collect() 96 | end 97 | end 98 | -------------------------------------------------------------------------------- /test/opencensus_test_support_span_capture_reporter_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Opencensus.TestSupport.SpanCaptureReporterTest do 2 | use ExUnit.Case, async: false 3 | import Opencensus.Trace 4 | 5 | alias Opencensus.TestSupport.SpanCaptureReporter 6 | 7 | describe "Opencensus.TestSupport.SpanCaptureReporter.collect/3" do 8 | defp loop_count do 9 | case System.get_env("CI") do 10 | nil -> 10 11 | _ -> 1000 12 | end 13 | end 14 | 15 | test "before detach, gets the just-finished span" do 16 | for _ <- 1..loop_count() do 17 | SpanCaptureReporter.attach() 18 | 19 | with_child_span "inner" do 20 | [0, 1, 1, 2, 2, 2, 2, 3, 3, 4] |> Enum.random() |> :timer.sleep() 21 | :... 22 | end 23 | 24 | assert SpanCaptureReporter.collect() |> length() == 1 25 | SpanCaptureReporter.detach() 26 | end 27 | end 28 | 29 | test "after detach, gets the just-finished span" do 30 | for _ <- 1..loop_count() do 31 | SpanCaptureReporter.attach() 32 | 33 | with_child_span "inner" do 34 | [0, 1, 1, 2, 2, 2, 2, 3, 3, 4] |> Enum.random() |> :timer.sleep() 35 | :... 36 | end 37 | 38 | SpanCaptureReporter.detach() 39 | assert SpanCaptureReporter.collect() |> length() == 1 40 | end 41 | end 42 | end 43 | end 44 | -------------------------------------------------------------------------------- /test/opencensus_trace_async_test.exs: -------------------------------------------------------------------------------- 1 | defmodule Opencensus.AsyncTest do 2 | use ExUnit.Case, async: false 3 | 4 | require Opencensus.Trace 5 | 6 | alias Opencensus.Span 7 | alias Opencensus.Trace 8 | 9 | test "Trace.async/1" do 10 | assert :ocp.current_span_ctx() == :undefined 11 | 12 | {inner, outer} = 13 | Trace.with_child_span "outside" do 14 | outer = :ocp.current_span_ctx() |> Span.load() 15 | 16 | Trace.async(fn -> 17 | Trace.with_child_span "inside" do 18 | inner = :ocp.current_span_ctx() |> Span.load() 19 | {inner, outer} 20 | end 21 | end) 22 | |> Trace.await(10) 23 | end 24 | 25 | assert inner.trace_id == outer.trace_id 26 | assert inner.parent_span_id == outer.span_id 27 | assert outer.parent_span_id == :undefined 28 | end 29 | 30 | defmodule M do 31 | def f(outer) do 32 | Trace.with_child_span "inside" do 33 | inner = :ocp.current_span_ctx() |> Span.load() 34 | {inner, outer} 35 | end 36 | end 37 | end 38 | 39 | test "Trace.async/3" do 40 | assert :ocp.current_span_ctx() == :undefined 41 | 42 | {inner, outer} = 43 | Trace.with_child_span "outside" do 44 | outer = :ocp.current_span_ctx() |> Span.load() 45 | Trace.async(M, :f, [outer]) |> Trace.await(10) 46 | end 47 | 48 | assert inner.trace_id == outer.trace_id 49 | assert inner.parent_span_id == outer.span_id 50 | assert outer.parent_span_id == :undefined 51 | end 52 | end 53 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.configure( 2 | formatters: 3 | if System.get_env("CI") do 4 | [JUnitFormatter, ExUnit.CLIFormatter] 5 | else 6 | [ExUnit.CLIFormatter] 7 | end 8 | ) 9 | 10 | :application.ensure_all_started(:opencensus) 11 | :application.ensure_all_started(:telemetry) 12 | ExUnit.start() 13 | --------------------------------------------------------------------------------