├── .github └── workflows │ └── test.yml ├── .gitignore ├── LICENSE ├── README.md ├── gleam.toml ├── rebar.config ├── rebar.lock ├── src ├── gleam_sentry.app.src └── gleam_sentry.gleam └── test └── gleam_sentry_test.gleam /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - main 8 | pull_request: 9 | 10 | jobs: 11 | test: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2.0.0 15 | - uses: gleam-lang/setup-erlang@v1.1.0 16 | with: 17 | otp-version: 22.1 18 | - uses: gleam-lang/setup-gleam@v1.0.2 19 | with: 20 | gleam-version: 0.13.2 21 | - run: rebar3 install_deps 22 | - run: rebar3 eunit 23 | - run: gleam format --check src test 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.beam 2 | *.iml 3 | *.o 4 | *.plt 5 | *.swo 6 | *.swp 7 | *~ 8 | .erlang.cookie 9 | .eunit 10 | .idea 11 | .rebar 12 | .rebar3 13 | _* 14 | _build 15 | docs 16 | ebin 17 | erl_crash.dump 18 | gen 19 | log 20 | logs 21 | rebar3.crashdump 22 | -------------------------------------------------------------------------------- /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 | Copyright {{copyright_year}}, {{author_name}} <{{author_email}}>. 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | 192 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gleam_sentry 2 | 3 | Report runtime exceptions to https://sentry.io 4 | 5 | ## Usage 6 | 7 | #### Intialise a client with your DSN and environment name. 8 | 9 | ```rust 10 | import gleam_sentry as sentry 11 | 12 | let dsn = "https://public_key@o0.ingest.sentry.io/123" 13 | let environment = "production" 14 | assert Ok(client) = sentry.init(dsn, environment) 15 | ``` 16 | 17 | #### Capture an exception 18 | 19 | ```rust 20 | sentry.capture_exception(client, reason, stacktrace, timestamp) 21 | ``` 22 | 23 | The types for reason and stacktrace are defined in the [gleam/beam](https://github.com/midas-framework/beam) project along with cast functions that allow you to get these values form logger events. 24 | 25 | #### Logger integration 26 | 27 | ```rust 28 | // my_app/logger.gleam 29 | import gleam/beam.{ExitReason, Stacktrace} 30 | 31 | pub fn handle(client, reason: ExitReason, stacktrace: Stacktrace, timestamp) { 32 | sentry.capture_exception(client, reason, stacktrace, timestamp) 33 | Nil 34 | } 35 | ``` 36 | 37 | ```rust 38 | // During startup 39 | import gleam/beam/logger 40 | import my_app/logger as my_logger 41 | 42 | pub fn start(){ 43 | logger.add_handler(my_logger.handle(client, _, _, _)) 44 | } 45 | ``` 46 | 47 | ## Future 48 | 49 | gleam_sentry currently reports errors from the beam runtime system, and as such could be implemented as an erlang library. 50 | I have not used existing projects (see prior art below) as only Elixir projects are based on the new logger. 51 | 52 | I would like this project to be useful in erlang projects. 53 | It would also be interesting to have a more general purpose span/context/error handling framework that this could plug in to. 54 | 55 | ## Prior Art 56 | 57 | ### Raven 58 | 59 | https://github.com/artemeff/raven-erlang 60 | 61 | erlang project, integrates with lager and error_logger. 62 | 63 | - Has an empty supervisor, just so it can be started as an app which adds a logger handler. 64 | - Every capture results in a call to sentry. https://github.com/artemeff/raven-erlang/blob/master/src/raven.erl#L46 65 | - Uses httpc and manually calls zlib. https://github.com/artemeff/raven-erlang/blob/master/src/raven.erl#L76-L86 66 | - Has a bunch of hardcoded mappers from error types. https://github.com/artemeff/raven-erlang/blob/master/src/raven_error_logger.erl#L108-L184 67 | - NOTE: these are old format so not useful to reproduce 68 | 69 | ### Sparrow 70 | 71 | https://github.com/ExpressApp/sparrow/tree/master/lib/sparrow 72 | 73 | Elixir project, uses new logger 74 | 75 | - Starts a coordinator and task supervisor, is this necessary with the infrastructure that already exists in logger? 76 | - It has a Client behaviour module but only one implementation directly in the library. -------------------------------------------------------------------------------- /gleam.toml: -------------------------------------------------------------------------------- 1 | name = "gleam_sentry" 2 | 3 | # [docs] 4 | # links = [ 5 | # { title = 'GitHub', href = 'https://github.com/username/project_name' } 6 | # ] 7 | -------------------------------------------------------------------------------- /rebar.config: -------------------------------------------------------------------------------- 1 | {erl_opts, [debug_info]}. 2 | {src_dirs, ["src", "gen/src"]}. 3 | 4 | {profiles, [ 5 | {test, [{src_dirs, ["src", "test", "gen/src", "gen/test"]}]} 6 | ]}. 7 | 8 | {project_plugins, [rebar_gleam, rebar3_hex]}. 9 | 10 | {deps, [ 11 | {gleam_stdlib, "0.14.0"}, 12 | {gleam_beam, "0.1.0"}, 13 | {gleam_http, "2.0.0"}, 14 | {gleam_httpc, "1.0.1"}, 15 | {gleam_json, "0.1.0"} 16 | ]}. 17 | -------------------------------------------------------------------------------- /rebar.lock: -------------------------------------------------------------------------------- 1 | {"1.2.0", 2 | [{<<"gleam_beam">>,{pkg,<<"gleam_beam">>,<<"0.1.0">>},0}, 3 | {<<"gleam_http">>,{pkg,<<"gleam_http">>,<<"2.0.0">>},0}, 4 | {<<"gleam_httpc">>,{pkg,<<"gleam_httpc">>,<<"1.0.1">>},0}, 5 | {<<"gleam_json">>,{pkg,<<"gleam_json">>,<<"0.1.0">>},0}, 6 | {<<"gleam_stdlib">>,{pkg,<<"gleam_stdlib">>,<<"0.14.0">>},0}, 7 | {<<"jsone">>,{pkg,<<"jsone">>,<<"1.5.2">>},1}]}. 8 | [ 9 | {pkg_hash,[ 10 | {<<"gleam_beam">>, <<"A0B11F71DD98321327C4F26CE9B9E5C40FE90ABACF9DD91ED7D16C5D3262CC2B">>}, 11 | {<<"gleam_http">>, <<"5CEDF334F58A5C646A302DB98CEFAFC36C34606C8F479CB5AB27ED3C06A5C546">>}, 12 | {<<"gleam_httpc">>, <<"78482F39CFC384398C7CA610D205BCF9D4B5888DDB8D1D252C790E1770734DAE">>}, 13 | {<<"gleam_json">>, <<"8740EB85E079F38A15F2627D53C306491D90C43C423AAE56A4ABC371319CC346">>}, 14 | {<<"gleam_stdlib">>, <<"765D90AC06F97D7A8E8F7AC4BEDA373879D98C78A27FD8DEACC98AA34DA2DDCE">>}, 15 | {<<"jsone">>, <<"87ADEA283C9CF24767B4DEED44602989A5331156DF5D60A2660E9C9114D54046">>}]}, 16 | {pkg_hash_ext,[ 17 | {<<"gleam_beam">>, <<"4DEE5F5DBEC6C8C36FDF9069161B8846A8A1DB26F05EF1B373BA3C42C39AE4EE">>}, 18 | {<<"gleam_http">>, <<"0FC0D01067E15E7AEC0A46F5897962217EAE9D3EA12FBAB1C0B6813822B6A1F3">>}, 19 | {<<"gleam_httpc">>, <<"3EC8F3110888AF78A81D5E96AEF32CBD1D40D13D3E29DB04D175954840DDFCBE">>}, 20 | {<<"gleam_json">>, <<"8C6F144BC4F2DDCB0347A84C4DEE134BD771A8A7C95C135A31D373D5EA95652B">>}, 21 | {<<"gleam_stdlib">>, <<"9107F6A859CB96945AD9A099085DB028CA2BEBB3C8EA42EEC227B51C614CC2E0">>}, 22 | {<<"jsone">>, <<"170C171CE7F6DD70C858065154A3305B8564833C6DCCA17E10B676CA31EA976F">>}]} 23 | ]. 24 | -------------------------------------------------------------------------------- /src/gleam_sentry.app.src: -------------------------------------------------------------------------------- 1 | {application, gleam_sentry, 2 | [{description, "Gleam Client for Sentry Error tracking"}, 3 | {vsn, "0.1.1"}, 4 | {registered, []}, 5 | {applications, 6 | [kernel, 7 | stdlib, 8 | gleam_stdlib 9 | ]}, 10 | {env,[]}, 11 | {modules, []}, 12 | 13 | {include_files, ["gleam.toml", "gen"]}, 14 | {licenses, ["Apache 2.0"]}, 15 | {links, []} 16 | ]}. 17 | -------------------------------------------------------------------------------- /src/gleam_sentry.gleam: -------------------------------------------------------------------------------- 1 | //// https://develop.sentry.dev/sdk/unified-api/ 2 | //// 3 | //// 4 | 5 | import gleam/atom 6 | import gleam/base 7 | import gleam/bit_string 8 | import gleam/int 9 | import gleam/list 10 | import gleam/option.{Some} 11 | import gleam/string 12 | import gleam/uri 13 | import gleam/beam 14 | import gleam/http 15 | import gleam/httpc 16 | import gleam/json 17 | 18 | external fn compress(String) -> String = 19 | "zlib" "compress" 20 | 21 | const sentry_version = 7 22 | 23 | const sentry_client = "sentry_gleam/0.1" 24 | 25 | /// A Client is the part of the SDK that is responsible for event creation. 26 | /// To give an example, the Client should convert an exception to a Sentry event. 27 | /// The Client should be stateless, it gets the Scope injected and delegates the work of sending the event to the Transport. 28 | pub type Client { 29 | Client( 30 | host: String, 31 | // This is the public_key, the secret_key is deprecated 32 | key: String, 33 | project_id: String, 34 | // I can't see any reason not to make environment required, and it should not vary by scope. 35 | environment: String, 36 | ) 37 | } 38 | 39 | // pub type Option{ 40 | // Environment(String) 41 | // } 42 | // Maybe scope has environment 43 | fn auth_header(key, timestamp) { 44 | string.concat([ 45 | "Sentry sentry_version=", 46 | int.to_string(sentry_version), 47 | ", sentry_client=", 48 | sentry_client, 49 | ", sentry_timestamp=", 50 | int.to_string(timestamp), 51 | ", sentry_key=", 52 | key, 53 | ]) 54 | } 55 | 56 | /// Initialise a Sentry client with a DSN and environment. 57 | pub fn init(dsn, environment) { 58 | try client = case uri.parse(dsn) { 59 | Ok(uri.Uri(userinfo: Some(key), host: Some(host), path: path, ..)) -> { 60 | try project_id = case string.split_once(path, "/") { 61 | Ok(tuple("", project_id)) -> Ok(project_id) 62 | _ -> Error(Nil) 63 | } 64 | Ok(Client(host, key, project_id, environment)) 65 | } 66 | _ -> Error(Nil) 67 | } 68 | Ok(client) 69 | } 70 | 71 | pub fn capture_event(client, event, timestamp) { 72 | let Client(host, key, project_id, ..) = client 73 | let path = string.concat(["/api/", project_id, "/store/"]) 74 | let body = 75 | base.encode64(bit_string.from_string(compress(json.encode(event))), False) 76 | let request = 77 | http.default_req() 78 | |> http.set_method(http.Post) 79 | |> http.set_scheme(http.Https) 80 | // https://e3b301fb356a4e61bebf8edb110af5b3@o351506.ingest.sentry.io/5574979 81 | |> http.set_host(host) 82 | |> http.set_path(path) 83 | |> http.prepend_req_header("content-type", "application/json") 84 | |> http.prepend_req_header("x-sentry-auth", auth_header(key, timestamp)) 85 | |> http.prepend_req_header("user-agent", "sentry_gleam/1") 86 | |> http.prepend_req_header("accept", "applicaton/json") 87 | |> http.set_req_body(body) 88 | httpc.send(request) 89 | } 90 | 91 | // Theres probably a datastructure here that does a job for level + exception + etc 92 | // client can have an a -> event function 93 | /// capture an erlang runtime exception 94 | pub fn capture_exception(client, exception, stacktrace, timestamp) { 95 | let Client(environment: environment, ..) = client 96 | 97 | let event = 98 | json.object([ 99 | // tuple("id"), 100 | tuple("timestamp", json.int(timestamp)), 101 | tuple("environment", json.string(environment)), 102 | tuple("exception", exception_to_json(exception, stacktrace)), 103 | // I don't know why all exceptions are reported as JS 104 | tuple("platform", json.string("other")), 105 | ]) 106 | 107 | capture_event(client, event, timestamp) 108 | } 109 | 110 | fn exception_detail(reason) { 111 | case reason { 112 | beam.Badarg -> tuple("badarg", "") 113 | beam.Badarith -> tuple("badarith", "") 114 | beam.Badmatch(term) -> tuple("badmatch", beam.format(term)) 115 | beam.FunctionClause -> tuple("function_clause", "") 116 | beam.CaseClause(term) -> tuple("case_clause", beam.format(term)) 117 | beam.IfClause -> tuple("if_clause", "") 118 | beam.TryClause(term) -> tuple("try_clause", beam.format(term)) 119 | beam.Undef -> tuple("undef", "") 120 | beam.Badfun(term) -> tuple("badfun", beam.format(term)) 121 | beam.Badarity(term) -> tuple("badarity", beam.format(term)) 122 | beam.TimeoutValue -> tuple("timeout_value", "") 123 | beam.Noproc -> tuple("noproc", "") 124 | beam.Nocatch(term) -> tuple("nocatch", beam.format(term)) 125 | beam.SystemLimit -> tuple("system_limit", "") 126 | } 127 | } 128 | 129 | fn exception_to_json(exception, stacktrace) { 130 | let detail = exception_detail(exception) 131 | json.object([ 132 | tuple("type", json.string(detail.0)), 133 | tuple("value", json.string(detail.1)), 134 | tuple("stacktrace", stacktrace_to_json(stacktrace)), 135 | ]) 136 | } 137 | 138 | pub fn stacktrace_to_json(stacktrace) { 139 | let frames = 140 | json.list(list.map(list.reverse(stacktrace), stack_frame_to_json)) 141 | json.object([tuple("frames", frames)]) 142 | } 143 | 144 | fn stack_frame_to_json(frame) { 145 | let tuple(module, function, arity, filename, line_number) = frame 146 | let function = string.join([function, int.to_string(arity)], "/") 147 | json.object([ 148 | tuple("filename", json.string(filename)), 149 | tuple("function", json.string(function)), 150 | tuple("module", json.string(atom.to_string(module))), 151 | tuple("lineno", json.int(line_number)), 152 | ]) 153 | } 154 | -------------------------------------------------------------------------------- /test/gleam_sentry_test.gleam: -------------------------------------------------------------------------------- 1 | import gleam_sentry 2 | import gleam/should 3 | --------------------------------------------------------------------------------