├── .editorconfig ├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── .gitignore ├── CHANGELOG.md ├── CODEOWNERS ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── RELEASING.md ├── SECURITY.md ├── build.gradle ├── docs └── dashboard.png ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── integrationTests ├── disable │ ├── build.gradle │ └── src │ │ └── test │ │ └── java │ │ └── com │ │ └── grafana │ │ └── opentelemetry │ │ ├── DemoApplication.java │ │ ├── DisableOpenTelemetryTest.java │ │ └── HelloController.java ├── log4j │ ├── build.gradle │ └── src │ │ └── test │ │ └── java │ │ └── com │ │ └── grafana │ │ └── opentelemetry │ │ └── log4j │ │ ├── DemoApplication.java │ │ ├── HelloController.java │ │ └── Log4jIntegrationTest.java └── main │ ├── build.gradle │ └── src │ └── test │ ├── java │ └── com │ │ └── grafana │ │ └── opentelemetry │ │ ├── DemoApplication.java │ │ ├── HelloController.java │ │ └── IntegrationTest.java │ └── resources │ └── application.yaml ├── scripts ├── release.sh └── update_readme.sh ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── grafana │ │ └── opentelemetry │ │ ├── DistributionVersion.java │ │ ├── GrafanaProperties.java │ │ ├── Log4jConfig.java │ │ ├── LogAppenderConfigurer.java │ │ ├── LogbackConfig.java │ │ └── OpenTelemetryConfig.java └── resources │ ├── META-INF │ └── spring │ │ └── org.springframework.boot.autoconfigure.AutoConfiguration.imports │ └── grafana-otel-starter.properties └── test └── java └── com └── grafana └── opentelemetry └── OpenTelemetryConfigTest.java /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*.xml] 4 | indent_size = 2 5 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gradle 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | tags: ['**'] 7 | pull_request: 8 | branches: [main] 9 | 10 | jobs: 11 | build: 12 | runs-on: ${{ matrix.os }}-latest 13 | strategy: 14 | fail-fast: false 15 | matrix: 16 | os: [ubuntu] 17 | java: ['17'] 18 | steps: 19 | - uses: actions/checkout@v3 20 | - name: Set up JDK 21 | uses: actions/setup-java@v3 22 | with: 23 | java-version: ${{ matrix.java }} 24 | distribution: 'adopt' 25 | - name: Validate Gradle wrapper 26 | uses: gradle/wrapper-validation-action@v1.0.5 27 | - name: Test and build Jar 28 | uses: gradle/gradle-build-action@v2.4.2 29 | env: 30 | CHECK_GENERATED_FILES: true 31 | with: 32 | arguments: test jar 33 | publish: 34 | needs: [ build ] 35 | if: always() && (needs.build.result == 'success') && github.repository == 'grafana/grafana-opentelemetry-starter' && github.event_name != 'pull_request' && startsWith(github.ref, 'refs/tags/') 36 | runs-on: ubuntu-latest 37 | steps: 38 | - uses: actions/checkout@v3 39 | - name: Set up Java 40 | uses: actions/setup-java@v3 41 | with: 42 | java-version: '17' 43 | distribution: 'adopt' 44 | - name: Validate Gradle wrapper 45 | uses: gradle/wrapper-validation-action@v1.0.5 46 | - name: Publish package 47 | uses: gradle/gradle-build-action@v2.4.2 48 | with: 49 | arguments: publishToSonatype closeAndReleaseSonatypeStagingRepository 50 | env: 51 | OSSRH_USERNAME: ${{ secrets.OSSRH_USERNAME }} 52 | OSSRH_PASSWORD: ${{ secrets.OSSRH_PASSWORD }} 53 | SIGNING_KEY: ${{ secrets.SIGNING_KEY }} 54 | SIGNING_PASSWORD: ${{ secrets.SIGNING_PASSWORD }} 55 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | build/ 3 | .env 4 | .idea/ 5 | README.generated 6 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## Version 1.4.0 (2023-12-07) 4 | 5 | * This version supports Spring Boot 3.2.0 6 | * Add resource attributes `telemetry.distro.name` = `grafana-opentelemetry-starter` and `telemetry.distro.version` = `1.4.0` 7 | 8 | ## Version 1.3.2 (2023-07-19) 9 | 10 | * You can now disable the starter by setting `spring.opentelemetry.enabled=false` in your application.yaml or application.properties 11 | 12 | ## Version 1.3.1 (2023-06-29) 13 | 14 | * Fix histogram bucket boundaries - it was a lower bound of 1 - regardless of the unit (and 1s is too large for server response times) 15 | * enable histograms for "http.server.requests" 16 | * Logger is configured automatically for Logback and Log4j2 - no need to add any configuration to your application (if you have configured the OpenTelemetry logger already, it will be used) 17 | 18 | ## Version 1.3.0 (2023-06-26) 19 | 20 | * Broken for log4j - use 1.3.1 instead 21 | 22 | ## Version 1.2.0 (2023-06-06) 23 | 24 | * Set the base time unit to "seconds" - which ensures future compatibility with upcoming versions of the Grafana Agent 25 | * Support thread name for logging 26 | 27 | ## Version 1.1.0 (2023-06-02) 28 | 29 | * Add support for log4j 30 | * Bugfix: starter can now be used with maven 31 | 32 | ## Version 1.0.1 (2023-05-23) 33 | 34 | ### Enhancements 35 | 36 | * Include open-telemetry resources [(#14)](https://github.com/grafana/grafana-opentelemetry-starter/pull/14) 37 | 38 | ## Version 1.0.0 (2023-04-24) 39 | 40 | * Initial release 41 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # https://help.github.com/articles/about-codeowners/ 2 | # https://git-scm.com/docs/gitignore#_pattern_format 3 | 4 | * @zeitlinger kjrun316 5 | 6 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | - Using welcoming and inclusive language 12 | - Being respectful of differing viewpoints and experiences 13 | - Gracefully accepting constructive criticism 14 | - Focusing on what is best for the community 15 | - Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | - The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | - Trolling, insulting/derogatory comments, and personal or political attacks 21 | - Public or private harassment 22 | - Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | - Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at conduct@grafana.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Changes to GrafanaProperties 2 | 3 | The properties in README.md are generated from GrafanaProperties.java. 4 | 5 | - Go to https://delight-im.github.io/Javadoc-to-Markdown/ 6 | - Copy the content of GrafanaProperties.java 7 | - Paste the result into README.generated (create the file if it doesn't exist) 8 | - `scripts/update_readme.sh` 9 | - Paste README.generated into README.md starting with `# Properties` 10 | 11 | # Update README.md 12 | 13 | Please create a PR to the [docs page](https://github.com/grafana/opentelemetry-docs/blob/main/docs/sources/instrumentation/spring-starter.md) 14 | when there's a significant change to the README.md. 15 | The docs page contains everything from the README.md, except the properties section. 16 | The content can be copied over - but some links become relative links and need to be fixed manually - this hasn't been 17 | automated yet. 18 | -------------------------------------------------------------------------------- /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 | ## Overview 2 | 3 | > ⚠️ This project is archived and no longer maintained. 4 | > 5 | > The Grafana OpenTelemetry Starter is deprecated and will not receive any further updates. 6 | > 7 | > If you are looking for a way to get started with OpenTelemetry in Java for **Grafana Cloud** or Grafana OSS, 8 | > please use the [Grafana OpenTelemetry Distribution for Java](https://github.com/grafana/grafana-opentelemetry-java). 9 | > 10 | > If you are looking for an OpenTelemetry **Spring Boot starter**, please use the 11 | > [OpenTelemetry Spring Boot Starter](https://opentelemetry.io/docs/zero-code/java/spring-boot-starter/). 12 | 13 | The grafana-opentelemetry-starter makes it easy to use Metrics, Traces, and Logs with OpenTelemetry 14 | in Grafana Cloud or the Grafana OSS stack. 15 | 16 | ## Compatibility 17 | 18 | | Spring Boot Version | Java Version | Recommended Setup | 19 | |---------------------|--------------|----------------------------------------------------------------------------------------------------------| 20 | | 3.2.x | 17+ | Use this starter in version 1.4.x | 21 | | 3.1.x | 17+ | Use this starter in version 1.3.x | 22 | | 3.0.4 < 3.1.0 | 17+ | Use this starter in version 1.0.0 (only works with gradle) | 23 | | 2.x | 8+ | Use [Grafana OpenTelemetry Distribution for Java](https://github.com/grafana/grafana-opentelemetry-java) | 24 | 25 | Logging is supported with Logback and Log4j2 26 | (a separate appender is added automatically, leaving your console or file appenders untouched). 27 | 28 | ## Getting Started 29 | 30 | Follow these three steps to get started with Grafana OpenTelemetry: 31 | 32 | - [Add the Grafana OpenTelemetry Starter dependency](#step-1-add-the-grafana-opentelemetry-starter-dependency) 33 | - [Configure the application](#step-2-configuration) 34 | - [Observe the service in Application Observability](#step-3-observe-the-service-in-application-observability) 35 | 36 | ### Step 1: Add the Grafana Opentelemetry Starter dependency 37 | 38 | Add the following dependency to your `build.gradle` 39 | 40 | ```groovy 41 | implementation 'com.grafana:grafana-opentelemetry-starter:1.4.0' 42 | ``` 43 | 44 | ... or `pom.xml` 45 | 46 | ```xml 47 | 48 | com.grafana 49 | grafana-opentelemetry-starter 50 | 1.4.0 51 | 52 | ``` 53 | 54 | ### Step 2: Configuration 55 | 56 | Next, configure your application either for [Grafana Cloud OTLP Gateway](#grafana-cloud-otlp-gateway) 57 | or [Grafana Agent](#grafana-agent). 58 | 59 | #### Grafana Cloud OTLP Gateway 60 | 61 | > ⚠️ Please use the Grafana Agent configuration for production use cases. 62 | 63 | The easiest setup is to use the Grafana Cloud OTLP Gateway, because you don't need to run any service to transport 64 | the telemetry data to Grafana Cloud. 65 | The Grafana Cloud OTLP Gateway is a managed service that is available in all Grafana Cloud plans. 66 | 67 | 1. Sign in to [Grafana Cloud](https://grafana.com), register for a Free Grafana Cloud account if required. 68 | 69 | 2. After successful login, the browser will navigate to the Grafana Cloud Portal page . 70 | 71 | A new account will most likely belong to one organization with one stack. 72 | 73 | If the account has access to multiple Grafana Cloud Organizations, select an organization from the 74 | top left **organization dropdown**. 75 | 76 | If the organization has access to multiple Grafana Cloud Stacks, navigate to a stack from the **left side bar** 77 | or the main **Stacks** list. 78 | 79 | 3. With a stack selected, or in the single stack scenario, below **Manage your Grafana Cloud Stack**, 80 | click **Configure** in the **OpenTelemetry** section: 81 | 82 | ![otel tile](https://grafana.com/media/docs/grafana-cloud/application-observability/opentelemetry-tile.png) 83 | 84 | 4. In the **Password / API Token** section, click on **Generate now** to create a new API token: 85 | - Give the API token a name, for example `otel-java` 86 | - Click on **Create token** 87 | - Click on **Close** without copying the token 88 | - Now the environment variables section is populated with all the necessary information to send telemetry data 89 | to Grafana Cloud 90 | - Click on **Copy to Clipboard** to copy the environment variables to the clipboard 91 | 92 | ![otel env vars](https://grafana.com/media/docs/grafana-cloud/application-observability/opentelemetry-env-vars.png) 93 | 94 | 5. Come up with a **Service Name** to identify the service, for example `cart`, and copy it into the shell command 95 | below. Use the `service.namespace` to group multiple services together. 96 | 6. Optional: add resource attributes to the shell command below: 97 | - **deployment.environment**: Name of the deployment environment, for example `staging` or `production` 98 | - **service.namespace**: A namespace to group similar services, for example using `service.namespace=shop` for a 99 | `cart` and `fraud-detection` service would create `shop/cart` and `shop/fraud-detection` in Grafana Cloud 100 | Application Observability with filtering capabilities for easier management 101 | - **service.version**: The application version, to see if a new version has introduced a bug 102 | - **service.instance.id**: The unique instance, for example the Pod name (a UUID is generated by default) 103 | 104 | ```shell 105 | 106 | export OTEL_SERVICE_NAME= 107 | export OTEL_RESOURCE_ATTRIBUTES=deployment.environment=,service.namespace=,service.version= 108 | ``` 109 | 110 | Finally, [Observe the service in Application Observability](#step-3-observe-the-service-in-application-observability). 111 | 112 | #### Grafana Agent 113 | 114 | The Grafana Agent is a single binary that can be deployed as a sidecar or daemonset in Kubernetes, or as a service 115 | in your network. It provides an endpoint where the application can send its telemetry data to. 116 | The telemetry data is then forwarded to Grafana Cloud or a Grafana OSS stack. 117 | 118 | > 💨 Skip this section and let the [OpenTelemetry Integration](https://grafana.com/docs/grafana-cloud/data-configuration/integrations/integration-reference/integration-opentelemetry/) 119 | > create everything for you. 120 | 121 | 1. If the Grafana Agent is not running locally or doesn't use the default grpc endpoint, 122 | adjust OTEL_EXPORTER_OTLP_ENDPOINT or OTEL_EXPORTER_OTLP_PROTOCOL (to `http/protobuf`). 123 | 2. Choose a **Service Name** to identify the service. 124 | 3. Optionally, add attributes to filter data: 125 | - **deployment.environment**: Name of the deployment environment (`staging` or `production`) 126 | - **service.namespace**: A namespace to group similar services 127 | (e.g. `shop` would create `shop/cart` in Application Observability) 128 | - **service.version**: The application version, to see if a new version has introduced a bug 129 | - **service.instance.id**: The unique instance, for example the Pod name (a UUID is generated by default) 130 | 131 | ```shell 132 | export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 133 | export OTEL_EXPORTER_OTLP_PROTOCOL=grpc 134 | export OTEL_SERVICE_NAME= 135 | export OTEL_RESOURCE_ATTRIBUTES=deployment.environment=,service.namespace=,service.version= 136 | ``` 137 | 138 | The application will send data to the Grafana Agent. Please follow the 139 | [Grafana Agent configuration for OpenTelemetry](https://grafana.com/docs/opentelemetry/instrumentation/configuration/grafana-agent/) 140 | guide. 141 | 142 | Finally, [Observe the service in Application Observability](#step-3-observe-the-service-in-application-observability). 143 | 144 | ### Step 3: Observe the Service in Application Observability 145 | 146 | Finally, make some requests to the service to validate data is sent to Grafana Cloud. 147 | It might take up to five minutes for data to appear. 148 | 149 | In Grafana, replace the path of the URL with `/a/grafana-app-observability-app/services` or: 150 | 151 | 1. Click on the menu icon in the top left corner 152 | 2. Open the _Observability_ menu 153 | 3. Click on _Application_ 154 | 155 | **Important**: refer to the [troubleshooting guide](#troubleshooting) if there is no data in Application Observability. 156 | 157 | ### Grafana Dashboard 158 | 159 | Once you've started your application, you can use this [Spring Boot Dashboard](https://grafana.com/grafana/dashboards/18887) 160 | 161 | ![](docs/dashboard.png) 162 | 163 | ### Getting Help 164 | 165 | If anything is not working, or you have questions about the starter, we’re glad to help you on our 166 | [community chat](https://slack.grafana.com/) (#opentelemetry). 167 | 168 | ## Reference 169 | 170 | - All configuration properties are described in the [reference](#properties). 171 | - The `grafana.otlp.cloud` and `grafana.otlp.onprem` properties are mutually exclusive. 172 | - As usual in Spring Boot, you can use environment variables to supply some of the properties, which is especially 173 | useful for secrets, e.g. `GRAFANA_OTLP_CLOUD_API_KEY` instead of `grafana.otlp.cloud.apiKey`. 174 | - In addition, you can use all system properties or environment variables from the 175 | [SDK auto-configuration](https://github.com/open-telemetry/opentelemetry-java/tree/main/sdk-extensions/autoconfigure) - 176 | which will take precedence. 177 | 178 | ### Troubleshooting 179 | 180 | When you start the application, you will also get a log output of the configuration properties as they are translated into SDK properties. 181 | 182 | For example, if you set the `spring.application.name` in `application.yaml`, 183 | you will get the following log output: 184 | 185 | ``` 186 | 11:53:07.724 [main] INFO c.g.o.OpenTelemetryConfig - using config properties: {otel.exporter.otlp.endpoint=https://otlp-gateway-prod-eu-west-0.grafana.net/otlp, otel.logs.exporter=otlp, otel.traces.exporter=otlp, otel.exporter.otlp.headers=Authorization=Basic NTUz..., otel.exporter.otlp.protocol=http/protobuf, otel.resource.attributes=service.name=demo-app, otel.metrics.exporter=otlp} 187 | ``` 188 | 189 | (The `otel.exporter.otlp.headers` field is abbreviated for security reasons.) 190 | 191 | If you still don't see your logs, traces and metrics in Grafana, even though the configuration looks good, 192 | you can turn on [debug logging](#grafanaotlpdebuglogging) to what data the application is emitting. 193 | 194 | ### Properties 195 | 196 | #### grafana.otlp.globalAttributes 197 | 198 | Adds global (resource) attributes to metrics, traces and logs. 199 | 200 | For example, you can add `service.version` to make it easier to see if a new version of the application is causing a problem. 201 | 202 | 203 | 204 | The attributes `service.name`, `service.version`, and `service.instance.id` are automatically detected as outlined below. 205 | 206 | 207 | 208 | For `service.name` the order of precedence is:
  1. environment variable OTEL_SERVICE_NAME
  2. environment variable OTEL_RESOURCE_ATTRIBUTES
  3. Manually set service_name in grafana.otlp.grafana.otlp.globalAttributes
  4. spring.application.name" in application.properties
  5. 'Implementation-Title' in jar's MANIFEST.MF
209 | 210 | The following block can be added to build.gradle to set the application name and version in the jar's MANIFEST.MF:
 bootJar { manifest { attributes('Implementation-Title': 'Demo Application', 'Implementation-Version': version) } } 
The `service.instance.id` attribute will be set if any of the following return a value. The list is in order of precedence.
  1. InetAddress.getLocalHost().getHostName()
  2. environment variable HOSTNAME
  3. environment variable HOST
211 | 212 | #### grafana.otlp.debugLogging 213 | 214 | Log all metrics, traces, and logs that are created for debugging purposes (in addition to sending them to the backend via OTLP). 215 | 216 | This will also send metrics and traces to Loki as an unintended side effect. 217 | 218 | #### grafana.otlp.enabled 219 | 220 | Enable or disable the OpenTelemetry integration (default is enabled). 221 | 222 | This can be used to disable the integration without removing the dependency. 223 | 224 | #### grafana.otlp.cloud.zone 225 | 226 | The Zone can be found when you click on "Details" in the "Grafana" section on grafana.com. 227 | 228 | Use `onprem.grafana.otlp.onprem.endpoint` instead of `grafana.otlp.cloud.zone` when using the Grafana Agent. 229 | 230 | #### grafana.otlp.cloud.instanceId 231 | 232 | The Instance ID can be found when you click on "Details" in the "Grafana" section on grafana.com. 233 | 234 | Leave `grafana.otlp.cloud.instanceId` empty when using the Grafana Agent. 235 | 236 | #### grafana.otlp.cloud.apiKey 237 | 238 | Create an API key under "Security" / "API Keys" (left side navigation tree) on grafana.com. The role should be "MetricsPublisher" 239 | 240 | Leave `grafana.otlp.cloud.apiKey` empty when using the Grafana Agent. 241 | 242 | #### grafana.otlp.onprem.endpoint 243 | 244 | The grafana.otlp.onprem.endpoint of the Grafana Agent. 245 | 246 | You do not need to set an `grafana.otlp.onprem.endpoint` value if your Grafana Agent is running locally with the default gRPC grafana.otlp.onprem.endpoint (localhost:4317). 247 | 248 | Use `cloud.grafana.otlp.cloud.zone` instead of `grafana.otlp.onprem.endpoint` when using the Grafana Cloud. 249 | 250 | #### grafana.otlp.onprem.protocol 251 | 252 | The grafana.otlp.onprem.protocol used to send OTLP data. Can be either `http/protobuf` or `grpc` (default). 253 | -------------------------------------------------------------------------------- /RELEASING.md: -------------------------------------------------------------------------------- 1 | # Releasing 2 | 3 | ## Publish Release via Github Workflow 4 | 5 | ### Prerequisites 6 | 7 | Install github's command line tool, `gh`. 8 | 9 | If you are on a mac, you can install the tool with [Homebrew](https://brew.sh/). 10 | 11 | ``` 12 | > brew install gh 13 | ``` 14 | 15 | Once the tool is installed, you will need to authenticate with github. To do so run: 16 | 17 | ``` 18 | > gh auth login 19 | ``` 20 | You will be asked several questions regarding how you want to log on (i.e. what account and protocol). 21 | 22 | Once authenticated you can continue to the next section. 23 | 24 | ### Prepare for Release 25 | 26 | Create/switch to a new branch off of `main`. 27 | 28 | ``` 29 | git checkout -b Update_for_new_release 30 | ``` 31 | 32 | From the project root, run the following command to update the repo with the new version (ex. 1.0.0) 33 | ``` 34 | > ./scripts/release.sh "" 35 | ``` 36 | Also update the repo's CHANGELOG with details about the release. Then commit/push the changes and open a PR. 37 | Merge the PR once approved. 38 | 39 | ### Tag and Publish New Release 40 | 41 | From the repo's `main` branch `git pull` the new changes. Then run the following 42 | [command](https://cli.github.com/manual/gh_release_create) to create a tag (if one does not already exist 43 | for the version) and publish the release to the 44 | [Sonatype repository](https://s01.oss.sonatype.org/content/groups/staging/com/grafana/grafana-opentelemetry-starter/). Remember to update the version before running. 45 | 46 | ``` 47 | > gh release create 48 | ``` 49 | 50 | You will be asked several questions regarding the release. You can leave the release notes blank 51 | or include details from the CHANGELOG. 52 | 53 | You can review the build/publish workflow script in `/.github/workflows/ci.yml` and review the pipeline's progress in the 54 | repo's [action](https://github.com/grafana/grafana-opentelemetry-starter/actions) page once the command is executed. 55 | 56 | ## Publish Release Manually 57 | 58 | ### Prerequisites 59 | 60 | - Create a sonatype account and create an [issue](https://issues.sonatype.org/browse/OSSRH-90665) to get approved by one of the maintainers 61 | - Get a GPG key - https://central.sonatype.org/publish/requirements/gpg/#credentials 62 | - Push the GPG key to ubuntu - https://central.sonatype.org/publish/requirements/gpg/#credentials 63 | - Export the secret key with `gpg --armor --export-secret-keys @grafana.com > ~/.gnupg/grafana-secret-key.txt`, should look like this: 64 | 65 | ``` 66 | -----BEGIN PGP PRIVATE KEY BLOCK----- 67 | 68 | 69 | 70 | -----END PGP PRIVATE KEY BLOCK----- 71 | ``` 72 | 73 | ### Publish to Nexus Repository 74 | 75 | #### Prepare for Release 76 | 77 | Create/switch to a new branch off of `main`. 78 | 79 | ``` 80 | > git checkout -b Update_for_new_release 81 | ``` 82 | 83 | From the project's root, run the following command to update the repo with the new version (ex. 1.0.0) 84 | ``` 85 | > ./scripts/release.sh "" 86 | ``` 87 | 88 | Also update the repo's CHANGELOG with details about the release. Then commit/push the changes and open a PR. 89 | Merge the PR once approved. 90 | 91 | #### Tag and Publish New Release 92 | 93 | From the repo's `main` branch, `git pull` the new changes. Then export the following environment variables 94 | and run the gradle command to publish. 95 | 96 | ```shell 97 | export OSSRH_USERNAME= 98 | export OSSRH_PASSWORD= 99 | export "SIGNING_KEY=$(cat ~/.gnupg/grafana-secret-key.txt)" 100 | export SIGNING_PASSWORD= 101 | 102 | ./gradlew publishToSonatype closeAndReleaseSonatypeStagingRepository 103 | ``` 104 | 105 | ### Publish to Local Maven Repository 106 | 107 | From the project's root directory, run the following to export the environment variable and publish a release 108 | to your local `~/.m2` repository. 109 | 110 | ```shell 111 | ./gradlew publishToMavenLocal 112 | ``` 113 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Reporting security issues 2 | 3 | If you think you have found a security vulnerability, please send a report to [security@grafana.com](mailto:security@grafana.com). This address can be used for all of Grafana Labs's open source and commercial products (including but not limited to Grafana, Grafana Cloud, Grafana Enterprise, and grafana.com). We can accept only vulnerability reports at this address. 4 | 5 | Please encrypt your message to us; please use our PGP key. The key fingerprint is: 6 | 7 | F988 7BEA 027A 049F AE8E 5CAA D125 8932 BE24 C5CA 8 | 9 | The key is available from [keyserver.ubuntu.com](https://keyserver.ubuntu.com/pks/lookup?search=0xF9887BEA027A049FAE8E5CAAD1258932BE24C5CA&fingerprint=on&op=index). 10 | 11 | Grafana Labs will send you a response indicating the next steps in handling your report. After the initial reply to your report, the security team will keep you informed of the progress towards a fix and full announcement, and may ask for additional information or guidance. 12 | 13 | **Important:** We ask you to not disclose the vulnerability before it have been fixed and announced, unless you received a response from the Grafana Labs security team that you can do so. 14 | 15 | ## Security announcements 16 | 17 | We will post a summary, remediation, and mitigation details for any patch containing security fixes on the Grafana blog. The security announcement blog posts will be tagged with the [security tag](https://grafana.com/tags/security/). 18 | 19 | You can also track security announcements via the [RSS feed](https://grafana.com/tags/security/index.xml). 20 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'maven-publish' 4 | id 'io.github.gradle-nexus.publish-plugin' version '1.3.0' 5 | id 'signing' 6 | id 'org.springframework.boot' version '3.2.0' 7 | id 'io.spring.dependency-management' version '1.1.4' 8 | id "com.diffplug.spotless" version "6.22.0" 9 | } 10 | 11 | sourceCompatibility = JavaVersion.VERSION_17 12 | targetCompatibility = JavaVersion.VERSION_17 13 | 14 | group = "com.grafana" 15 | version = project.properties['grafanaOtelStarterVersion'] 16 | 17 | java { 18 | withJavadocJar() 19 | withSourcesJar() 20 | } 21 | 22 | jar { 23 | // allows maven to read the artifact (by default, it's "plain") 24 | archiveClassifier.set('') 25 | } 26 | 27 | allprojects { 28 | version = rootProject.version 29 | 30 | apply plugin: "java" 31 | apply plugin: "com.diffplug.spotless" 32 | 33 | repositories { 34 | mavenCentral() 35 | maven { 36 | url = uri("https://s01.oss.sonatype.org/content/repositories/snapshots") 37 | mavenContent { 38 | snapshotsOnly() 39 | } 40 | } 41 | } 42 | 43 | test { 44 | useJUnitPlatform() 45 | } 46 | 47 | spotless { 48 | java { 49 | googleJavaFormat() 50 | target("src/**/*.java") 51 | } 52 | } 53 | } 54 | 55 | dependencies { 56 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 57 | 58 | def otelVersion = dependencyManagement.importedProperties['opentelemetry.version'] 59 | implementation "io.opentelemetry:opentelemetry-exporter-otlp" 60 | implementation "io.opentelemetry:opentelemetry-exporter-logging" // only for debug 61 | implementation "io.opentelemetry.instrumentation:opentelemetry-logback-appender-1.0:$otelVersion-alpha" 62 | implementation "io.opentelemetry.instrumentation:opentelemetry-log4j-appender-2.17:$otelVersion-alpha" 63 | compileOnly 'org.springframework.boot:spring-boot-starter-log4j2' 64 | 65 | runtimeOnly "io.opentelemetry.instrumentation:opentelemetry-resources:$otelVersion-alpha" 66 | implementation "io.opentelemetry.instrumentation:opentelemetry-micrometer-1.5:$otelVersion-alpha" 67 | implementation "io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:$otelVersion" 68 | runtimeOnly "io.micrometer:micrometer-tracing-bridge-otel" 69 | 70 | annotationProcessor "org.springframework.boot:spring-boot-configuration-processor" 71 | 72 | testImplementation "org.springframework.boot:spring-boot-starter-test" 73 | testImplementation "org.springframework.boot:spring-boot-starter-web" 74 | } 75 | 76 | publishing { 77 | publications { 78 | mavenJava(MavenPublication) { 79 | from components.java 80 | 81 | pom { 82 | name = 'Grafana OpenTelemetry Starter' 83 | description = 'Spring boot starter to use Metrics, Traces, and Logs with OpenTelemetry in Grafana Cloud or with Grafana Agent (for Grafana Cloud or Grafana OSS stack)' 84 | url = 'https://github.com/grafana/grafana-opentelemetry-starter' 85 | licenses { 86 | license { 87 | name = 'The Apache License, Version 2.0' 88 | url = 'http://www.apache.org/licenses/LICENSE-2.0.txt' 89 | } 90 | } 91 | developers { 92 | developer { 93 | id = "zeitlinger" 94 | name = "Gregor Zeitlinger" 95 | email = "gregor.zeitlinger@grafana.com" 96 | } 97 | } 98 | scm { 99 | connection = 'scm:git:git://github.com/grafana/grafana-opentelemetry-starter.git' 100 | developerConnection = 'scm:git:ssh://github.com/grafana/grafana-opentelemetry-starter.git' 101 | url = 'https://github.com/grafana/grafana-opentelemetry-starter' 102 | } 103 | } 104 | } 105 | } 106 | repositories { 107 | maven { 108 | name = 'OSSRH' 109 | url = 'https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/' 110 | 111 | credentials { 112 | username = System.getenv('OSSRH_USERNAME') 113 | password = System.getenv('OSSRH_PASSWORD') 114 | } 115 | } 116 | } 117 | } 118 | 119 | nexusPublishing { 120 | repositories { 121 | sonatype { 122 | nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/")) 123 | snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")) 124 | 125 | username = System.getenv("OSSRH_USERNAME") 126 | password = System.getenv("OSSRH_PASSWORD") 127 | } 128 | } 129 | } 130 | 131 | if (gradle.startParameter.taskNames.contains("publishToSonatype")) { 132 | signing { 133 | sign publishing.publications.mavenJava 134 | useInMemoryPgpKeys(System.getenv("SIGNING_KEY"), System.getenv("SIGNING_PASSWORD")) 135 | } 136 | } 137 | 138 | def updateGeneratedFile(file, newContent) { 139 | if (System.getenv("CHECK_GENERATED_FILES") == "true") { 140 | def oldContent = file.text 141 | if (oldContent != newContent) { 142 | throw new GradleException("File ${file} was modified in CI. Please update it locally and commit.") 143 | } 144 | } else { 145 | project.mkdir(file.parent) 146 | file.text = newContent 147 | } 148 | } 149 | 150 | task manageVersionClass() { 151 | doLast { 152 | updateGeneratedFile(new File("${projectDir}/src/main/java/com/grafana/opentelemetry", "DistributionVersion.java"), 153 | """/* 154 | * Copyright Grafana Labs 155 | * SPDX-License-Identifier: Apache-2.0 156 | */ 157 | 158 | package com.grafana.opentelemetry; 159 | 160 | // This class is generated by custom/build.gradle. Do not edit. 161 | 162 | public class DistributionVersion { 163 | 164 | public static final String VERSION = "$version"; 165 | } 166 | """) 167 | } 168 | } 169 | 170 | compileJava.dependsOn(manageVersionClass) 171 | 172 | -------------------------------------------------------------------------------- /docs/dashboard.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/grafana/grafana-opentelemetry-starter/8b97f1647dfd10c65e592b100f16bbbed0dab5e9/docs/dashboard.png -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | grafanaOtelStarterVersion=1.4.0 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/grafana/grafana-opentelemetry-starter/8b97f1647dfd10c65e592b100f16bbbed0dab5e9/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /integrationTests/disable/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.2.0' 4 | id 'io.spring.dependency-management' version '1.1.4' 5 | } 6 | 7 | repositories { 8 | mavenCentral() 9 | } 10 | 11 | dependencies { 12 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 13 | implementation 'org.springframework.boot:spring-boot-starter-web' 14 | implementation rootProject 15 | 16 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 17 | } 18 | 19 | test { 20 | useJUnitPlatform() 21 | } 22 | -------------------------------------------------------------------------------- /integrationTests/disable/src/test/java/com/grafana/opentelemetry/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DemoApplication { 8 | public static void main(String[] args) { 9 | SpringApplication.run(DemoApplication.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /integrationTests/disable/src/test/java/com/grafana/opentelemetry/DisableOpenTelemetryTest.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry; 2 | 3 | import org.assertj.core.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | import org.springframework.boot.test.autoconfigure.actuate.observability.AutoConfigureObservability; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.test.context.TestPropertySource; 8 | 9 | @SuppressWarnings("SpringBootApplicationProperties") 10 | @SpringBootTest(classes = {HelloController.class, DemoApplication.class, OpenTelemetryConfig.class}) 11 | @AutoConfigureObservability 12 | @TestPropertySource( 13 | properties = { 14 | "grafana.otlp.enabled = false", 15 | }) 16 | public class DisableOpenTelemetryTest { 17 | 18 | @Test 19 | void starterIsNotApplied() { 20 | // we could also check that no data is sent, but this would require us to wait a certain amount 21 | // of time 22 | // e.g. 10 seconds - and this would make the test slow and complicated 23 | Assertions.assertThat(LogbackConfig.hasAppender(LogbackConfig.getLogger())).isFalse(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /integrationTests/disable/src/test/java/com/grafana/opentelemetry/HelloController.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | @RestController 7 | public class HelloController { 8 | @GetMapping("/hello") 9 | public String sayHello() { 10 | return "hello LGTM"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /integrationTests/log4j/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.2.0' 4 | id 'io.spring.dependency-management' version '1.1.4' 5 | } 6 | 7 | repositories { 8 | mavenCentral() 9 | } 10 | 11 | dependencies { 12 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 13 | implementation 'org.springframework.boot:spring-boot-starter-web' 14 | implementation 'org.springframework.boot:spring-boot-starter-log4j2' 15 | implementation rootProject 16 | 17 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 18 | testImplementation 'org.mock-server:mockserver-spring-test-listener:5.15.0' 19 | testImplementation 'org.awaitility:awaitility:4.2.0' 20 | } 21 | 22 | configurations { 23 | all*.exclude module: 'spring-boot-starter-logging' 24 | } 25 | 26 | test { 27 | useJUnitPlatform() 28 | } 29 | -------------------------------------------------------------------------------- /integrationTests/log4j/src/test/java/com/grafana/opentelemetry/log4j/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry.log4j; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DemoApplication { 8 | public static void main(String[] args) { 9 | SpringApplication.run(DemoApplication.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /integrationTests/log4j/src/test/java/com/grafana/opentelemetry/log4j/HelloController.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry.log4j; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | @RestController 7 | public class HelloController { 8 | @GetMapping("/hello") 9 | public String sayHello() { 10 | return "hello LGTM"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /integrationTests/log4j/src/test/java/com/grafana/opentelemetry/log4j/Log4jIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry.log4j; 2 | 3 | import static java.util.concurrent.TimeUnit.SECONDS; 4 | import static org.awaitility.Awaitility.await; 5 | 6 | import com.grafana.opentelemetry.OpenTelemetryConfig; 7 | import org.junit.jupiter.api.Test; 8 | import org.mockserver.client.MockServerClient; 9 | import org.mockserver.model.HttpRequest; 10 | import org.mockserver.springtest.MockServerTest; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.test.autoconfigure.actuate.observability.AutoConfigureObservability; 13 | import org.springframework.boot.test.context.SpringBootTest; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.http.HttpMethod; 16 | import org.springframework.test.context.TestPropertySource; 17 | 18 | @SpringBootTest( 19 | classes = {HelloController.class, DemoApplication.class, OpenTelemetryConfig.class}, 20 | webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 21 | @MockServerTest 22 | @AutoConfigureObservability 23 | @TestPropertySource( 24 | properties = { 25 | "grafana.otlp.onprem.endpoint = http://localhost:${mockServerPort}", 26 | "grafana.otlp.onprem.protocol = http/protobuf", 27 | }) 28 | public class Log4jIntegrationTest { 29 | 30 | @SuppressWarnings("unused") 31 | private MockServerClient mockServerClient; 32 | 33 | @Autowired private TestRestTemplate restTemplate; 34 | 35 | @Test 36 | void logDataIsSent() { 37 | restTemplate.getForEntity("/hello", String.class); 38 | 39 | await().atMost(10, SECONDS).untilAsserted(this::verifyLogs); 40 | } 41 | 42 | private void verifyLogs() { 43 | // only assert that a request was received, 44 | // because the goal of this test is to make sure that data is still sent when dependabot 45 | // upgrades 46 | // spring boot, which can also update the OpenTelemetry version 47 | mockServerClient.verify( 48 | HttpRequest.request() 49 | .withMethod(HttpMethod.POST.name()) 50 | .withPath("/v1/logs") 51 | .withHeader("Content-Type", "application/x-protobuf")); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /integrationTests/main/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | id 'org.springframework.boot' version '3.2.0' 4 | id 'io.spring.dependency-management' version '1.1.4' 5 | } 6 | 7 | repositories { 8 | mavenCentral() 9 | } 10 | 11 | dependencies { 12 | def otelVersion = dependencyManagement.importedProperties['opentelemetry.version'] 13 | //this dependency is not supposed to be exposed by the starter - so we add it here for testing purposes 14 | implementation "io.opentelemetry:opentelemetry-sdk-extension-autoconfigure:$otelVersion" 15 | 16 | implementation 'org.springframework.boot:spring-boot-starter-actuator' 17 | implementation 'org.springframework.boot:spring-boot-starter-web' 18 | implementation rootProject 19 | 20 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 21 | testImplementation 'org.mock-server:mockserver-spring-test-listener:5.15.0' 22 | testImplementation 'org.awaitility:awaitility:4.2.0' 23 | } 24 | 25 | test { 26 | useJUnitPlatform() 27 | } 28 | -------------------------------------------------------------------------------- /integrationTests/main/src/test/java/com/grafana/opentelemetry/DemoApplication.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class DemoApplication { 8 | public static void main(String[] args) { 9 | SpringApplication.run(DemoApplication.class, args); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /integrationTests/main/src/test/java/com/grafana/opentelemetry/HelloController.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry; 2 | 3 | import org.springframework.web.bind.annotation.GetMapping; 4 | import org.springframework.web.bind.annotation.RestController; 5 | 6 | @RestController 7 | public class HelloController { 8 | @GetMapping("/hello") 9 | public String sayHello() { 10 | return "hello LGTM"; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /integrationTests/main/src/test/java/com/grafana/opentelemetry/IntegrationTest.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry; 2 | 3 | import static java.util.concurrent.TimeUnit.SECONDS; 4 | import static org.awaitility.Awaitility.await; 5 | 6 | import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; 7 | import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; 8 | import java.util.Optional; 9 | import org.apache.commons.lang3.reflect.MethodUtils; 10 | import org.assertj.core.api.Assertions; 11 | import org.junit.jupiter.api.Test; 12 | import org.mockserver.client.MockServerClient; 13 | import org.mockserver.model.HttpRequest; 14 | import org.mockserver.springtest.MockServerTest; 15 | import org.springframework.beans.factory.annotation.Autowired; 16 | import org.springframework.boot.test.autoconfigure.actuate.observability.AutoConfigureObservability; 17 | import org.springframework.boot.test.context.SpringBootTest; 18 | import org.springframework.boot.test.web.client.TestRestTemplate; 19 | import org.springframework.http.HttpMethod; 20 | import org.springframework.test.context.TestPropertySource; 21 | 22 | @SpringBootTest( 23 | classes = {HelloController.class, DemoApplication.class}, 24 | webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 25 | @MockServerTest 26 | @AutoConfigureObservability 27 | @TestPropertySource( 28 | properties = { 29 | "grafana.otlp.onprem.endpoint = http://localhost:${mockServerPort}", 30 | "grafana.otlp.onprem.protocol = grpc" // is overridden by system property 31 | // otel.exporter.otlp.protocol 32 | }) 33 | class IntegrationTest { 34 | 35 | @SuppressWarnings("unused") 36 | private MockServerClient mockServerClient; 37 | 38 | @Autowired private TestRestTemplate restTemplate; 39 | 40 | @Autowired private GrafanaProperties properties; 41 | 42 | @Autowired private Optional sdk; 43 | 44 | static { 45 | String delay = "500"; 46 | System.setProperty("otel.metric.export.interval", delay); 47 | System.setProperty("otel.bsp.schedule.delay", delay); 48 | System.setProperty("otel.exporter.otlp.protocol", "http/protobuf"); 49 | } 50 | 51 | @Test 52 | void testProperties() { 53 | Assertions.assertThat(properties.getCloud().getZone()).isEqualTo("prod-eu-west-0"); 54 | } 55 | 56 | @Test 57 | void systemPropHasPriority() { 58 | Assertions.assertThat(sdk) 59 | .hasValueSatisfying( 60 | v -> { 61 | try { 62 | ConfigProperties p = 63 | (ConfigProperties) MethodUtils.invokeMethod(v, true, "getConfig"); 64 | Assertions.assertThat(p.getString("otel.exporter.otlp.protocol")) 65 | .isEqualTo("http/protobuf"); 66 | } catch (Exception e) { 67 | throw new RuntimeException(e); 68 | } 69 | }); 70 | } 71 | 72 | @Test 73 | void dataIsSent() { 74 | restTemplate.getForEntity("/hello", String.class); 75 | 76 | await() 77 | .atMost(10, SECONDS) 78 | .untilAsserted( 79 | () -> { 80 | verifyPath("/v1/traces"); 81 | verifyPath("/v1/metrics"); 82 | verifyPath("/v1/logs"); 83 | }); 84 | } 85 | 86 | private void verifyPath(String path) { 87 | // only assert that a request was received, 88 | // because the goal of this test is to make sure that data is still sent when dependabot 89 | // upgrades 90 | // spring boot, which can also update the OpenTelemetry version 91 | mockServerClient.verify( 92 | HttpRequest.request() 93 | .withMethod(HttpMethod.POST.name()) 94 | .withPath(path) 95 | .withHeader("Content-Type", "application/x-protobuf")); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /integrationTests/main/src/test/resources/application.yaml: -------------------------------------------------------------------------------- 1 | grafana: 2 | otlp: 3 | cloud: 4 | zone: prod-eu-west-0 5 | -------------------------------------------------------------------------------- /scripts/release.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | newVersion=$1 4 | if [ -z "$newVersion" ]; then 5 | echo "new version is missing" 6 | exit 1 7 | fi 8 | 9 | oldVersion=$(grep -oP "(?<=grafanaOtelStarterVersion=)(.*)" gradle.properties) 10 | sed -i "s/$oldVersion/$newVersion/g" README.md 11 | sed -i "s/$oldVersion/$newVersion/g" gradle.properties 12 | -------------------------------------------------------------------------------- /scripts/update_readme.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | sed -i 's/# Documentation/### Properties/g' README.generated 4 | sed -i --regexp-extended 's/## `(private )?(final )?([^ ]+ )(String> )?([a-zA-Z]+) ?.*`/#### \5/g' README.generated 5 | sed -i 's/endpoint/grafana.otlp.onprem.endpoint/g' README.generated 6 | sed -i 's/protocol/grafana.otlp.onprem.protocol/g' README.generated 7 | sed -i 's/zone/grafana.otlp.cloud.zone/g' README.generated 8 | sed -i 's/apiKey/grafana.otlp.cloud.apiKey/g' README.generated 9 | sed -i 's/instanceId/grafana.otlp.cloud.instanceId/g' README.generated 10 | sed -i 's/debugLogging/grafana.otlp.debugLogging/g' README.generated 11 | sed -i 's/enabled/grafana.otlp.enabled/g' README.generated 12 | sed -i 's/globalAttributes/grafana.otlp.globalAttributes/g' README.generated 13 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'grafana-opentelemetry-starter' 2 | 3 | include( 4 | ":integrationTests:main", 5 | ":integrationTests:disable", 6 | ":integrationTests:log4j" 7 | ) 8 | -------------------------------------------------------------------------------- /src/main/java/com/grafana/opentelemetry/DistributionVersion.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright Grafana Labs 3 | * SPDX-License-Identifier: Apache-2.0 4 | */ 5 | 6 | package com.grafana.opentelemetry; 7 | 8 | // This class is generated by custom/build.gradle. Do not edit. 9 | 10 | public class DistributionVersion { 11 | 12 | public static final String VERSION = "1.4.0"; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/grafana/opentelemetry/GrafanaProperties.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | 7 | @ConfigurationProperties(prefix = "grafana.otlp") 8 | public class GrafanaProperties { 9 | 10 | private CloudProperties cloud = new CloudProperties(); 11 | 12 | private OnPremProperties onPrem = new OnPremProperties(); 13 | 14 | /** 15 | * Adds global (resource) attributes to metrics, traces and logs. 16 | * 17 | *

For example, you can add service.version to make it easier to see if a new 18 | * version of the application is causing a problem. 19 | * 20 | *

The attributes service.name, service.version, and 21 | * service.instance.id are automatically detected as outlined below. 22 | * 23 | *

For service.name the order of precedence is: 24 | * 25 | *

    26 | *
  1. environment variable OTEL_SERVICE_NAME 27 | *
  2. environment variable OTEL_RESOURCE_ATTRIBUTES 28 | *
  3. Manually set service_name in grafana.otlp.globalAttributes 29 | *
  4. spring.application.name" in application.properties 30 | *
  5. 'Implementation-Title' in jar's MANIFEST.MF 31 | *
32 | * 33 | *

The following block can be added to build.gradle to set the application name and version in 34 | * the jar's MANIFEST.MF: 35 | * 36 | *

 37 |    * bootJar {
 38 |    *     manifest {
 39 |    *         attributes('Implementation-Title':   'Demo Application',
 40 |    *                    'Implementation-Version':  version)
 41 |    *     }
 42 |    * }
 43 |    * 
44 | * 45 | * The service.instance.id attribute will be set if any of the following return a 46 | * value. The list is in order of precedence. 47 | * 48 | *
    49 | *
  1. InetAddress.getLocalHost().getHostName() 50 | *
  2. environment variable HOSTNAME 51 | *
  3. environment variable HOST 52 | *
53 | */ 54 | private final Map globalAttributes = new HashMap<>(); 55 | 56 | /** 57 | * Log all metrics, traces, and logs that are created for debugging purposes (in addition to 58 | * sending them to the backend via OTLP). 59 | * 60 | *

This will also send metrics and traces to Loki as an unintended side effect. 61 | */ 62 | private boolean debugLogging; 63 | 64 | /** 65 | * Enable or disable the OpenTelemetry integration (default is enabled). 66 | * 67 | *

This can be used to disable the integration without removing the dependency. 68 | */ 69 | private boolean enabled = true; 70 | 71 | public CloudProperties getCloud() { 72 | return cloud; 73 | } 74 | 75 | public void setCloud(CloudProperties cloud) { 76 | this.cloud = cloud; 77 | } 78 | 79 | public OnPremProperties getOnPrem() { 80 | return onPrem; 81 | } 82 | 83 | public void setOnPrem(OnPremProperties onPrem) { 84 | this.onPrem = onPrem; 85 | } 86 | 87 | public boolean isDebugLogging() { 88 | return debugLogging; 89 | } 90 | 91 | public void setDebugLogging(boolean debugLogging) { 92 | this.debugLogging = debugLogging; 93 | } 94 | 95 | public boolean isEnabled() { 96 | return enabled; 97 | } 98 | 99 | public void setEnabled(boolean enabled) { 100 | this.enabled = enabled; 101 | } 102 | 103 | public Map getGlobalAttributes() { 104 | return globalAttributes; 105 | } 106 | 107 | public static class CloudProperties { 108 | /** 109 | * The Zone can be found when you click on "Details" in the "Grafana" section on grafana.com. 110 | * 111 | *

Use onprem.endpoint instead of zone when using the Grafana 112 | * Agent. 113 | */ 114 | private String zone; 115 | 116 | /** 117 | * The Instance ID can be found when you click on "Details" in the "Grafana" section on 118 | * grafana.com. 119 | * 120 | *

Leave instanceId empty when using the Grafana Agent. 121 | */ 122 | private int instanceId; 123 | 124 | /** 125 | * Create an API key under "Security" / "API Keys" (left side navigation tree) on grafana.com. 126 | * The role should be "MetricsPublisher" 127 | * 128 | *

Leave apiKey empty when using the Grafana Agent. 129 | */ 130 | private String apiKey; 131 | 132 | public String getZone() { 133 | return zone; 134 | } 135 | 136 | public void setZone(String zone) { 137 | this.zone = zone; 138 | } 139 | 140 | public int getInstanceId() { 141 | return instanceId; 142 | } 143 | 144 | public void setInstanceId(int instanceId) { 145 | this.instanceId = instanceId; 146 | } 147 | 148 | public String getApiKey() { 149 | return apiKey; 150 | } 151 | 152 | public void setApiKey(String apiKey) { 153 | this.apiKey = apiKey; 154 | } 155 | } 156 | 157 | public static class OnPremProperties { 158 | /** 159 | * The endpoint of the Grafana Agent. 160 | * 161 | *

You do not need to set an endpoint value if your Grafana Agent is running 162 | * locally with the default gRPC endpoint (localhost:4317). 163 | * 164 | *

Use cloud.zone instead of endpoint when using the Grafana Cloud. 165 | */ 166 | private String endpoint; 167 | 168 | /** 169 | * The protocol used to send OTLP data. Can be either http/protobuf or grpc 170 | * (default). 171 | */ 172 | private String protocol; 173 | 174 | public String getEndpoint() { 175 | return endpoint; 176 | } 177 | 178 | public void setEndpoint(String endpoint) { 179 | this.endpoint = endpoint; 180 | } 181 | 182 | public String getProtocol() { 183 | return protocol; 184 | } 185 | 186 | public void setProtocol(String protocol) { 187 | this.protocol = protocol; 188 | } 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /src/main/java/com/grafana/opentelemetry/Log4jConfig.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry; 2 | 3 | import io.opentelemetry.api.OpenTelemetry; 4 | import io.opentelemetry.instrumentation.log4j.appender.v2_17.OpenTelemetryAppender; 5 | import org.apache.logging.log4j.LogManager; 6 | import org.apache.logging.log4j.Logger; 7 | import org.apache.logging.log4j.core.Appender; 8 | import org.apache.logging.log4j.core.LoggerContext; 9 | import org.apache.logging.log4j.core.config.Configuration; 10 | import org.apache.logging.log4j.core.config.LoggerConfig; 11 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 12 | 13 | @ConditionalOnClass(name = "org.apache.logging.log4j.core.LoggerContext") 14 | public class Log4jConfig implements LogAppenderConfigurer { 15 | 16 | private static final Logger logger = LogManager.getLogger(Log4jConfig.class); 17 | 18 | public void tryAddAppender(OpenTelemetry openTelemetry) { 19 | org.apache.logging.log4j.spi.LoggerContext loggerContextSpi = LogManager.getContext(false); 20 | if (!(loggerContextSpi instanceof LoggerContext)) { 21 | logger.warn("cannot add log4j OpenTelemetryAppender, not running in a LoggerContext"); 22 | return; 23 | } 24 | 25 | LoggerContext context = (LoggerContext) LogManager.getContext(false); 26 | Configuration config = context.getConfiguration(); 27 | boolean found = 28 | config.getAppenders().values().stream() 29 | .anyMatch( 30 | a -> 31 | a 32 | instanceof 33 | io.opentelemetry.instrumentation.log4j.appender.v2_17 34 | .OpenTelemetryAppender); 35 | if (found) { 36 | logger.info("log4j2 OpenTelemetryAppender has already been added"); 37 | OpenTelemetryAppender.install(openTelemetry); 38 | return; 39 | } 40 | 41 | logger.info("adding log4j OpenTelemetryAppender"); 42 | OpenTelemetryAppender appender = 43 | OpenTelemetryAppender.builder() 44 | .setCaptureExperimentalAttributes(true) 45 | .setName("OpenTelemetryAppender") 46 | .setConfiguration(config) 47 | .setOpenTelemetry(openTelemetry) 48 | .build(); 49 | appender.start(); 50 | config.addAppender(appender); 51 | 52 | updateLoggers(appender, config); 53 | } 54 | 55 | private static void updateLoggers(Appender appender, Configuration config) { 56 | for (LoggerConfig loggerConfig : config.getLoggers().values()) { 57 | loggerConfig.addAppender(appender, null, null); 58 | } 59 | config.getRootLogger().addAppender(appender, null, null); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/grafana/opentelemetry/LogAppenderConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry; 2 | 3 | import io.opentelemetry.api.OpenTelemetry; 4 | 5 | public interface LogAppenderConfigurer { 6 | void tryAddAppender(OpenTelemetry openTelemetry); 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/grafana/opentelemetry/LogbackConfig.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry; 2 | 3 | import io.opentelemetry.api.OpenTelemetry; 4 | import io.opentelemetry.instrumentation.logback.appender.v1_0.OpenTelemetryAppender; 5 | import java.util.concurrent.atomic.AtomicBoolean; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 9 | 10 | @ConditionalOnClass(name = "ch.qos.logback.classic.Logger") 11 | public class LogbackConfig implements LogAppenderConfigurer { 12 | 13 | private static final Logger logger = LoggerFactory.getLogger(LogbackConfig.class); 14 | 15 | public void tryAddAppender(OpenTelemetry openTelemetry) { 16 | ch.qos.logback.classic.Logger logbackLogger = getLogger(); 17 | 18 | // check if appender has been added manually already 19 | if (hasAppender(logbackLogger)) { 20 | logger.info("logback OpenTelemetryAppender has already been added"); 21 | OpenTelemetryAppender.install(openTelemetry); 22 | return; 23 | } 24 | 25 | logger.info("adding logback OpenTelemetryAppender"); 26 | OpenTelemetryAppender appender = new OpenTelemetryAppender(); 27 | appender.setCaptureExperimentalAttributes(true); 28 | appender.setOpenTelemetry(openTelemetry); 29 | appender.start(); 30 | logbackLogger.addAppender(appender); 31 | } 32 | 33 | static ch.qos.logback.classic.Logger getLogger() { 34 | return (ch.qos.logback.classic.Logger) 35 | LoggerFactory.getILoggerFactory().getLogger(Logger.ROOT_LOGGER_NAME); 36 | } 37 | 38 | static boolean hasAppender(ch.qos.logback.classic.Logger logbackLogger) { 39 | AtomicBoolean found = new AtomicBoolean(false); 40 | logbackLogger 41 | .iteratorForAppenders() 42 | .forEachRemaining( 43 | appender -> { 44 | if (appender instanceof OpenTelemetryAppender) { 45 | found.set(true); 46 | } 47 | }); 48 | return found.get(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/grafana/opentelemetry/OpenTelemetryConfig.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry; 2 | 3 | import io.micrometer.core.instrument.Clock; 4 | import io.micrometer.core.instrument.MeterRegistry; 5 | import io.opentelemetry.api.OpenTelemetry; 6 | import io.opentelemetry.api.common.AttributeKey; 7 | import io.opentelemetry.instrumentation.micrometer.v1_5.OpenTelemetryMeterRegistry; 8 | import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; 9 | import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder; 10 | import io.opentelemetry.sdk.metrics.Aggregation; 11 | import io.opentelemetry.sdk.metrics.InstrumentSelector; 12 | import io.opentelemetry.sdk.metrics.InstrumentType; 13 | import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; 14 | import io.opentelemetry.sdk.metrics.View; 15 | import io.opentelemetry.sdk.metrics.internal.aggregator.ExplicitBucketHistogramUtils; 16 | import io.opentelemetry.semconv.ResourceAttributes; 17 | import java.net.InetAddress; 18 | import java.net.UnknownHostException; 19 | import java.util.Base64; 20 | import java.util.HashMap; 21 | import java.util.List; 22 | import java.util.Map; 23 | import java.util.Optional; 24 | import java.util.concurrent.TimeUnit; 25 | import java.util.jar.Attributes; 26 | import java.util.jar.Manifest; 27 | import java.util.stream.Collectors; 28 | import org.apache.logging.log4j.util.Strings; 29 | import org.slf4j.Logger; 30 | import org.slf4j.LoggerFactory; 31 | import org.springframework.beans.factory.annotation.Value; 32 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 33 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 34 | import org.springframework.context.annotation.Bean; 35 | import org.springframework.context.annotation.Configuration; 36 | import org.springframework.context.annotation.PropertySource; 37 | 38 | @Configuration(proxyBeanMethods = false) 39 | @ConditionalOnProperty(value = "grafana.otlp.enabled", havingValue = "true", matchIfMissing = true) 40 | @EnableConfigurationProperties(GrafanaProperties.class) 41 | @PropertySource(value = {"classpath:grafana-otel-starter.properties"}) 42 | public class OpenTelemetryConfig { 43 | 44 | public static final String DISTRIBUTION_NAME = "telemetry.distro.name"; 45 | public static final String DISTRIBUTION_VERSION = "telemetry.distro.version"; 46 | 47 | private static final Logger logger = LoggerFactory.getLogger(OpenTelemetryConfig.class); 48 | 49 | public static final String OTLP_HEADERS = "otel.exporter.otlp.headers"; 50 | 51 | @Bean 52 | public MeterRegistry openTelemetryMeterRegistry(OpenTelemetry openTelemetry, Clock clock) { 53 | // note: add setting histogramGaugesEnabled in new otel version 54 | return OpenTelemetryMeterRegistry.builder(openTelemetry) 55 | .setClock(clock) 56 | .setBaseTimeUnit(TimeUnit.SECONDS) 57 | .build(); 58 | } 59 | 60 | @Bean 61 | public OpenTelemetry openTelemetry( 62 | Optional sdk, 63 | List logAppenderConfigurers) { 64 | OpenTelemetry openTelemetry = 65 | sdk.map(AutoConfiguredOpenTelemetrySdk::getOpenTelemetrySdk) 66 | .orElse(OpenTelemetry.noop()); 67 | 68 | tryAddAppender(openTelemetry, logAppenderConfigurers); 69 | return openTelemetry; 70 | } 71 | 72 | static void tryAddAppender( 73 | OpenTelemetry openTelemetry, List logAppenderConfigurers) { 74 | if (logAppenderConfigurers.isEmpty()) { 75 | logger.warn("no logging library found - OpenTelemetryAppender not added"); 76 | } else { 77 | logAppenderConfigurers.forEach( 78 | logAppenderConfigurer -> logAppenderConfigurer.tryAddAppender(openTelemetry)); 79 | } 80 | } 81 | 82 | @Bean 83 | public AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk( 84 | GrafanaProperties properties, 85 | @Value("${spring.application.name:#{null}}") String applicationName) { 86 | AutoConfiguredOpenTelemetrySdkBuilder builder = AutoConfiguredOpenTelemetrySdk.builder(); 87 | builder.addMeterProviderCustomizer((b, configProperties) -> customizeMeterBuilder(b)); 88 | 89 | Map configProperties = getConfigProperties(properties, applicationName); 90 | builder.addPropertiesSupplier(() -> configProperties); 91 | logger.info("using config properties: {}", maskAuthHeader(configProperties)); 92 | 93 | try { 94 | return builder.build(); 95 | } catch (Exception e) { 96 | logger.warn("unable to create OpenTelemetry instance", e); 97 | return null; 98 | } 99 | } 100 | 101 | private static SdkMeterProviderBuilder customizeMeterBuilder( 102 | SdkMeterProviderBuilder meterProviderBuilder) { 103 | // workaround for bug that bucket boundaries are not scaled correctly: bucket boundaries for 104 | // seconds 105 | List buckets = 106 | ExplicitBucketHistogramUtils.DEFAULT_HISTOGRAM_BUCKET_BOUNDARIES.stream() 107 | .map(d -> d * 0.001) 108 | .collect(Collectors.toList()); 109 | 110 | meterProviderBuilder.registerView( 111 | InstrumentSelector.builder().setType(InstrumentType.HISTOGRAM).build(), 112 | View.builder().setAggregation(Aggregation.explicitBucketHistogram(buckets)).build()); 113 | return meterProviderBuilder; 114 | } 115 | 116 | private static Map getConfigProperties( 117 | GrafanaProperties properties, String applicationName) { 118 | String exporters = properties.isDebugLogging() ? "logging,otlp" : "otlp"; 119 | 120 | GrafanaProperties.CloudProperties cloud = properties.getCloud(); 121 | GrafanaProperties.OnPremProperties onPrem = properties.getOnPrem(); 122 | Optional authHeader = getBasicAuthHeader(cloud.getInstanceId(), cloud.getApiKey()); 123 | Map configProperties = 124 | new HashMap<>( 125 | Map.of( 126 | "otel.resource.attributes", getResourceAttributes(properties, applicationName), 127 | "otel.exporter.otlp.protocol", getProtocol(onPrem.getProtocol(), authHeader), 128 | "otel.traces.exporter", exporters, 129 | "otel.metrics.exporter", exporters, 130 | "otel.logs.exporter", exporters)); 131 | authHeader.ifPresent(s -> configProperties.put(OTLP_HEADERS, s)); 132 | getEndpoint(onPrem.getEndpoint(), cloud.getZone(), authHeader) 133 | .ifPresent(s -> configProperties.put("otel.exporter.otlp.endpoint", s)); 134 | return configProperties; 135 | } 136 | 137 | static String getProtocol(String protocol, Optional authHeader) { 138 | boolean hasProto = Strings.isNotBlank(protocol); 139 | if (authHeader.isPresent()) { 140 | if (hasProto) { 141 | logger.warn( 142 | "ignoring grafana.otlp.onprem.protocol, because grafana.otlp.cloud.instanceId was found"); 143 | } 144 | return "http/protobuf"; 145 | } 146 | 147 | return hasProto ? protocol : "grpc"; 148 | } 149 | 150 | static Map maskAuthHeader(Map configProperties) { 151 | return configProperties.entrySet().stream() 152 | .collect( 153 | Collectors.toMap( 154 | Map.Entry::getKey, 155 | e -> { 156 | String v = e.getValue(); 157 | return e.getKey().equals(OTLP_HEADERS) && v.length() > 24 158 | ? v.substring(0, 24) + "..." 159 | : v; 160 | })); 161 | } 162 | 163 | static Optional getEndpoint(String endpoint, String zone, Optional authHeader) { 164 | boolean hasZone = Strings.isNotBlank(zone); 165 | boolean hasEndpoint = Strings.isNotBlank(endpoint); 166 | if (authHeader.isPresent()) { 167 | if (hasEndpoint) { 168 | logger.warn( 169 | "ignoring grafana.otlp.onprem.endpoint, because grafana.otlp.cloud.instanceId was found"); 170 | } 171 | if (hasZone) { 172 | return Optional.of(String.format("https://otlp-gateway-%s.grafana.net/otlp", zone)); 173 | } else { 174 | logger.warn("please specify grafana.otlp.cloud.zone"); 175 | } 176 | } else { 177 | if (hasZone) { 178 | logger.warn( 179 | "ignoring grafana.otlp.cloud.zone, because grafana.otlp.cloud.instanceId was not found"); 180 | } 181 | if (hasEndpoint) { 182 | return Optional.of(endpoint); 183 | } else { 184 | logger.info( 185 | "grafana.otlp.onprem.endpoint not found, using default endpoint for otel.exporter.otlp.protocol"); 186 | } 187 | } 188 | return Optional.empty(); 189 | } 190 | 191 | static Optional getBasicAuthHeader(int instanceId, String apiKey) { 192 | boolean hasKey = Strings.isNotBlank(apiKey); 193 | boolean hasId = instanceId != 0; 194 | if (hasKey && hasId) { 195 | String userPass = String.format("%s:%s", instanceId, apiKey); 196 | return Optional.of( 197 | String.format( 198 | "Authorization=Basic %s", Base64.getEncoder().encodeToString(userPass.getBytes()))); 199 | } 200 | 201 | if (hasKey) { 202 | logger.warn("found grafana.otlp.cloud.apiKey but no grafana.otlp.cloud.instanceId"); 203 | } 204 | if (hasId) { 205 | logger.warn("found grafana.otlp.cloud.instanceId but no grafana.otlp.cloud.apiKey"); 206 | } 207 | 208 | return Optional.empty(); 209 | } 210 | 211 | private static String getResourceAttributes( 212 | GrafanaProperties properties, String applicationName) { 213 | Map resourceAttributes = properties.getGlobalAttributes(); 214 | 215 | String manifestApplicationName = null; 216 | String manifestApplicationVersion = null; 217 | try { 218 | Manifest mf = new Manifest(); 219 | mf.read(ClassLoader.getSystemResourceAsStream("META-INF/MANIFEST.MF")); 220 | Attributes atts = mf.getMainAttributes(); 221 | 222 | Object n = atts.getValue("Implementation-Title"); 223 | if (n != null) { 224 | manifestApplicationName = n.toString(); 225 | } 226 | Object v = atts.getValue("Implementation-Version"); 227 | if (v != null) { 228 | manifestApplicationVersion = v.toString(); 229 | } 230 | } catch (Exception e) { 231 | // ignore error reading manifest 232 | } 233 | 234 | updateResourceAttribute( 235 | resourceAttributes, 236 | ResourceAttributes.SERVICE_NAME, 237 | applicationName, 238 | manifestApplicationName); 239 | updateResourceAttribute( 240 | resourceAttributes, ResourceAttributes.SERVICE_VERSION, manifestApplicationVersion); 241 | 242 | String hostName; 243 | try { 244 | hostName = InetAddress.getLocalHost().getHostName(); 245 | } catch (UnknownHostException e) { 246 | hostName = System.getenv("HOSTNAME"); 247 | } 248 | updateResourceAttribute( 249 | resourceAttributes, 250 | ResourceAttributes.SERVICE_INSTANCE_ID, 251 | hostName, 252 | System.getenv("HOST")); 253 | 254 | resourceAttributes.put(DISTRIBUTION_NAME, "grafana-opentelemetry-starter"); 255 | resourceAttributes.put(DISTRIBUTION_VERSION, DistributionVersion.VERSION); 256 | 257 | return resourceAttributes.entrySet().stream() 258 | .map(e -> String.format("%s=%s", e.getKey(), e.getValue())) 259 | .collect(Collectors.joining(",")); 260 | } 261 | 262 | static void updateResourceAttribute( 263 | Map resourceAttributes, AttributeKey key, String... overrides) { 264 | 265 | if (!resourceAttributes.containsKey(key.getKey())) { 266 | for (String value : overrides) { 267 | if (Strings.isNotBlank(value)) { 268 | resourceAttributes.put(key.getKey(), value); 269 | return; 270 | } 271 | } 272 | } 273 | } 274 | } 275 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports: -------------------------------------------------------------------------------- 1 | com.grafana.opentelemetry.OpenTelemetryConfig 2 | com.grafana.opentelemetry.LogbackConfig 3 | com.grafana.opentelemetry.Log4jConfig 4 | 5 | -------------------------------------------------------------------------------- /src/main/resources/grafana-otel-starter.properties: -------------------------------------------------------------------------------- 1 | management.metrics.distribution.percentiles-histogram.http.server.requests=true 2 | -------------------------------------------------------------------------------- /src/test/java/com/grafana/opentelemetry/OpenTelemetryConfigTest.java: -------------------------------------------------------------------------------- 1 | package com.grafana.opentelemetry; 2 | 3 | import io.opentelemetry.semconv.ResourceAttributes; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.Optional; 7 | import java.util.stream.Stream; 8 | import org.assertj.core.api.Assertions; 9 | import org.junit.jupiter.api.extension.ExtendWith; 10 | import org.junit.jupiter.params.ParameterizedTest; 11 | import org.junit.jupiter.params.provider.Arguments; 12 | import org.junit.jupiter.params.provider.MethodSource; 13 | import org.springframework.boot.test.system.CapturedOutput; 14 | import org.springframework.boot.test.system.OutputCaptureExtension; 15 | 16 | @ExtendWith(OutputCaptureExtension.class) 17 | class OpenTelemetryConfigTest { 18 | 19 | @ParameterizedTest(name = "{0}") 20 | @MethodSource("overrideCases") 21 | void updateResourceAttribute(String name, String expected, String explicit, String[] override) { 22 | HashMap resourceAttributes = new HashMap<>(); 23 | if (explicit != null) { 24 | resourceAttributes.put(ResourceAttributes.SERVICE_NAME.getKey(), explicit); 25 | } 26 | OpenTelemetryConfig.updateResourceAttribute( 27 | resourceAttributes, ResourceAttributes.SERVICE_NAME, override); 28 | 29 | if (expected == null) { 30 | Assertions.assertThat(resourceAttributes).isEmpty(); 31 | } else { 32 | Assertions.assertThat(resourceAttributes) 33 | .containsExactlyEntriesOf(Map.of(ResourceAttributes.SERVICE_NAME.getKey(), expected)); 34 | } 35 | } 36 | 37 | private static Stream overrideCases() { 38 | return Stream.of( 39 | Arguments.of("explicit name is kept", "explicit", "explicit", new String[] {"ignored"}), 40 | Arguments.of("only override is used", "override", null, new String[] {"override"}), 41 | Arguments.of( 42 | "first non-blank override is used", "override", null, new String[] {" ", "override"}), 43 | Arguments.of( 44 | "first non-empty override is used", "override", null, new String[] {"", "override"}), 45 | Arguments.of( 46 | "first non-null override is used", "override", null, new String[] {null, "override"}), 47 | Arguments.of("no value found", null, null, new String[] {" ", null})); 48 | } 49 | 50 | record BasicAuthTestCase( 51 | Optional expected, String expectedOutput, String apiKey, int instanceId) {} 52 | 53 | @ParameterizedTest(name = "{0}") 54 | @MethodSource("basicAuthCases") 55 | void getBasicAuthHeader(String name, BasicAuthTestCase testCase, CapturedOutput output) { 56 | Optional basicAuthHeader = 57 | OpenTelemetryConfig.getBasicAuthHeader(testCase.instanceId, testCase.apiKey); 58 | Assertions.assertThat(basicAuthHeader).isEqualTo(testCase.expected); 59 | Assertions.assertThat(output).contains(testCase.expectedOutput); 60 | } 61 | 62 | private static Stream basicAuthCases() { 63 | return Stream.of( 64 | Arguments.of( 65 | "valid basic auth", 66 | new BasicAuthTestCase( 67 | Optional.of("Authorization=Basic MTIyMzQ1OmFwaUtleQ=="), "", "apiKey", 122345)), 68 | Arguments.of( 69 | "API key and instanceId missing", 70 | new BasicAuthTestCase(Optional.empty(), "", " ", 12345)), 71 | Arguments.of( 72 | "API key blank", 73 | new BasicAuthTestCase( 74 | Optional.empty(), 75 | "found grafana.otlp.cloud.instanceId but no grafana.otlp.cloud.apiKey", 76 | " ", 77 | 12345)), 78 | Arguments.of( 79 | "instanceId 0", 80 | new BasicAuthTestCase( 81 | Optional.empty(), 82 | "found grafana.otlp.cloud.apiKey but no grafana.otlp.cloud.instanceId", 83 | "apiKey", 84 | 0))); 85 | } 86 | 87 | record EndpointTestCase( 88 | Optional expected, 89 | String expectedOutput, 90 | String zone, 91 | String endpoint, 92 | Optional authHeader) {} 93 | 94 | @ParameterizedTest(name = "{0}") 95 | @MethodSource("endpointCases") 96 | void getEndpoint(String name, EndpointTestCase testCase, CapturedOutput output) { 97 | Assertions.assertThat( 98 | OpenTelemetryConfig.getEndpoint(testCase.endpoint, testCase.zone, testCase.authHeader)) 99 | .isEqualTo(testCase.expected); 100 | Assertions.assertThat(output).contains(testCase.expectedOutput); 101 | } 102 | 103 | private static Stream endpointCases() { 104 | return Stream.of( 105 | Arguments.of( 106 | "only zone", 107 | new EndpointTestCase( 108 | Optional.of("https://otlp-gateway-zone.grafana.net/otlp"), 109 | "", 110 | "zone", 111 | "", 112 | Optional.of("apiKey"))), 113 | Arguments.of( 114 | "only onprem endpoint", 115 | new EndpointTestCase(Optional.of("endpoint"), "", "", "endpoint", Optional.empty())), 116 | Arguments.of( 117 | "both with cloud", 118 | new EndpointTestCase( 119 | Optional.of("https://otlp-gateway-zone.grafana.net/otlp"), 120 | "ignoring grafana.otlp.onprem.endpoint, because grafana.otlp.cloud.instanceId was found", 121 | "zone", 122 | "endpoint", 123 | Optional.of("key"))), 124 | Arguments.of( 125 | "zone without instanceId", 126 | new EndpointTestCase( 127 | Optional.of("endpoint"), 128 | "ignoring grafana.otlp.cloud.zone, because grafana.otlp.cloud.instanceId was not found", 129 | "zone", 130 | "endpoint", 131 | Optional.empty())), 132 | Arguments.of( 133 | "missing zone", 134 | new EndpointTestCase( 135 | Optional.empty(), 136 | "please specify grafana.otlp.cloud.zone", 137 | " ", 138 | " ", 139 | Optional.of("key"))), 140 | Arguments.of( 141 | "onprem endpoint not set", 142 | new EndpointTestCase( 143 | Optional.empty(), 144 | "grafana.otlp.onprem.endpoint not found, using default endpoint for otel.exporter.otlp.protocol", 145 | " ", 146 | " ", 147 | Optional.empty()))); 148 | } 149 | 150 | record ProtocolTestCase( 151 | String expected, String expectedOutput, String protocol, Optional authHeader) {} 152 | 153 | @ParameterizedTest(name = "{0}") 154 | @MethodSource("protocolCases") 155 | void getProtocol(String name, ProtocolTestCase testCase, CapturedOutput output) { 156 | Assertions.assertThat(OpenTelemetryConfig.getProtocol(testCase.protocol, testCase.authHeader)) 157 | .isEqualTo(testCase.expected); 158 | Assertions.assertThat(output).contains(testCase.expectedOutput); 159 | } 160 | 161 | private static Stream protocolCases() { 162 | return Stream.of( 163 | Arguments.of("cloud", new ProtocolTestCase("http/protobuf", "", "", Optional.of("apiKey"))), 164 | Arguments.of( 165 | "cloud and proto", 166 | new ProtocolTestCase( 167 | "http/protobuf", 168 | "ignoring grafana.otlp.onprem.protocol, because grafana.otlp.cloud.instanceId was found", 169 | "grpc", 170 | Optional.of("apiKey"))), 171 | Arguments.of("onprem", new ProtocolTestCase("grpc", "", "", Optional.empty())), 172 | Arguments.of( 173 | "onprem and proto", 174 | new ProtocolTestCase("http/protobuf", "", "http/protobuf", Optional.empty()))); 175 | } 176 | 177 | @ParameterizedTest(name = "{0}") 178 | @MethodSource("maskCases") 179 | void maskAuthHeader(String name, Map expected, Map given) { 180 | Map map = OpenTelemetryConfig.maskAuthHeader(given); 181 | Assertions.assertThat(map).containsExactlyInAnyOrderEntriesOf(expected); 182 | } 183 | 184 | private static Stream maskCases() { 185 | return Stream.of( 186 | Arguments.of( 187 | "masked", 188 | Map.of("foo", "bar", OpenTelemetryConfig.OTLP_HEADERS, "Authorization=Basic NTUz..."), 189 | Map.of( 190 | "foo", 191 | "bar", 192 | OpenTelemetryConfig.OTLP_HEADERS, 193 | "Authorization=Basic NTUzMzg2OmV5SnJJam9pW")), 194 | Arguments.of( 195 | "short auth header", 196 | Map.of("foo", "bar", OpenTelemetryConfig.OTLP_HEADERS, ""), 197 | Map.of("foo", "bar", OpenTelemetryConfig.OTLP_HEADERS, "")), 198 | Arguments.of("no auth header", Map.of("foo", "bar"), Map.of("foo", "bar"))); 199 | } 200 | } 201 | --------------------------------------------------------------------------------