├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build-publish.gradle ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle ├── span-reporter-examples ├── build.gradle └── src │ └── main │ ├── java │ ├── examples │ │ ├── Sample01.java │ │ └── Sample01.scala.off │ └── io │ │ └── opentracing │ │ └── contrib │ │ └── di │ │ ├── BraveTracerModule.java │ │ ├── HawkularTracerModule.java │ │ ├── LoggerTracerModule.java │ │ └── NoopTracerModule.java │ └── resources │ └── logback.xml ├── span-reporter-slf4j ├── build.gradle └── src │ └── main │ ├── java │ └── io │ │ └── opentracing │ │ └── contrib │ │ └── reporter │ │ └── slf4j │ │ ├── DefaultLoggerTracer.java │ │ └── Slf4jReporter.java │ └── resources │ └── META-INF │ └── services │ └── io.opentracing.Tracer ├── span-reporter ├── build.gradle └── src │ ├── main │ └── java │ │ └── io │ │ └── opentracing │ │ └── contrib │ │ ├── reporter │ │ ├── CompositeReporter.java │ │ ├── LogLevel.java │ │ ├── Reporter.java │ │ ├── SpanBuilderR.java │ │ ├── SpanData.java │ │ ├── SpanR.java │ │ └── TracerR.java │ │ └── util │ │ └── MapMaker.java │ └── test │ └── java │ └── io │ └── opentracing │ └── contrib │ └── reporter │ └── SpanBuilderRTest.java └── src └── etc └── header.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Build / maven artifacts 2 | *.class 3 | target/ 4 | dependency-reduced-pom.xml 5 | pom.xml.versionsBackup 6 | 7 | # Gradle 8 | build/ 9 | .gradle 10 | 11 | # Mobile Tools for Java (J2ME) 12 | .mtj.tmp/ 13 | 14 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 15 | hs_err_pid* 16 | 17 | # IntelliJ project files 18 | .idea/ 19 | *.iml 20 | 21 | # vscode 22 | .vscode 23 | 24 | # Eclipse 25 | .project 26 | .classpath 27 | .settings 28 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | dist: trusty 3 | env: 4 | global: 5 | - GRADLE_USER_HOME=gradle-cache 6 | # travis encrypt -r org/repo BINTRAY_USER=... 7 | - secure: "BX8IzFIg+3iPz3arjcfEU5iDPp9euFptpSBhrLor7J0etHtQ2QyqVQLsJ8B3w8udy8UhCZxnAe0NObzCI7NFf/2jgSN6y+T0E/dYDT3LSQk9sB9SpP853VgIsihuiYFNS9pBs1DgjSh4o3wkUt8KZA+XFowZ6AJrFnYE25J3o9O80CCO0eQP6xPjjhyuVQlsjzTht7q1ApiQOza5ux3cnMUCZOAEaB81MxK4yQ/98h4IBlIKe2gvLGBaN+YYsOnd1Mte8kGyuBnUdz7Nb1339xMBkUcEi4a6Tz9Z4NDS99K1dfLWLR3ef1bYDP8N4CVKS4ZJgavdc6BykOGEMEWae8tFqnMUCHJjUuXWMN4EFpi1HUY2eK43TI3wPVM8h+YsTvzb/KMfiLtBttkTjPksHohoeYK9IGpxuggkR/A1FPf8MNv8vb8h2hl0Q1mbCHdPCa1jtoIO94yaZZXzN3gb3MBNENwXh8q8TVwsvRr9UvEO8+/4ta8V7IEqlCj6+vNQryqQAO0KiwxNnWfo3XFzfSCnBQ5/l66uwW3SMmJ4gI9oh1B0tzhunoeMSegdutcbWPOYxdBEOX3AKwfpDCqyd9eBrTTmFmdrwuxvuQR842jK9fzEhzrPhTA/pbNcZRpHuzb0ny3iIP3r4UGg/TS7f8btCJG713XbcOLbozxC0KQ=" 8 | # travis encrypt -r org/repo BINTRAY_KEY=... 9 | - secure: "Zq32wGOUirE07jQlB3n5Yr+x3rBfFNnD5oAFUXDpuxhHyER8qS5cIiNQFOVPI9yeWQyQN3iRvmUICu3/Lz7k+LPlMl2xI98yrLQSNeG1pTgRHt9yblWx7pYNomrEsHV7AZ7j/5/Ry7LU9mVQvKm+9nZAZz7sTcDjzItH7U73pkHaZpFaN9zsvOE8i85ts82OwhmyEll7xLCf1trYjTAqxyj7HvdSE5d2imbGlm+6rkbd6nb0qHbdfpJbpMuhUNdscNeNvtHr2x1hLt3s95swaSOGMczfNfFIjpTjisiXv4iEjvVBhN7x7tQJS4FBiKvAkvUJFdPs0AMsr61Zplaytt3CefABrM9s1gMYONxjltv2jfF99N/s7tg92kX3FTZDjjvQApqsQFGL1AxNf9vFjbiCuyBexm8Nj0m/KdxN7nKF5ePTtPX2FIbm+0QX3Xi2Nz7mr7GwV12TIMADo65SZKvSmBcSbt09ryEkVgHqDBRyq1JyD/ubaKr7MgMIaWk3/sIpIaSaqdE6dN2ZDs+70OZ+Klda24b4bQhBCSBgcY7FnqI/uFwJ9zaETc+QbkSeV7xdgUPdX+vxzNATCa1INsCXVMxKI7QWYGQxN9nTMRK1we2sFNwIh+1a5jotLbtRC+SsbQ5oyyWGuEoVShtWisVRP4K07dRoMIJKVZFfg2w=" 10 | language: java 11 | jdk: 12 | - oraclejdk8 13 | 14 | cache: 15 | directories: 16 | - gradle-cache 17 | - $HOME/.gradle/caches/ 18 | - $HOME/.gradle/wrapper/ 19 | 20 | install: 21 | - ./gradlew assemble 22 | 23 | script: 24 | - ./gradlew check 25 | 26 | after_success: 27 | - 'echo "TRAVIS_TAG: $TRAVIS_TAG" - "TRAVIS_PULL_REQUEST: $TRAVIS_PULL_REQUEST"' 28 | - '[ -n "$TRAVIS_TAG" ] && [ "$TRAVIS_PULL_REQUEST" == "false" ] && ./gradlew bintrayUpload' 29 | 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status][ci-img]][ci] [![Coverage Status][cov-img]][cov] [![Released Version][maven-img]][maven] 2 | 3 | # SpanReporter for Java 4 | SpanReporter forward to backend Tracer and reports trace into Reporter. 5 | 6 | ```java 7 | public interface Reporter { 8 | void start(long timestampMicroseconds, SpanR span); 9 | void finish(long timestampMicroseconds, SpanR span); 10 | void log(long timestampMicroseconds, SpanR span, Map event); 11 | } 12 | ``` 13 | ## Use Case 14 | 15 | * As zero server tracer. 16 | * To use OpenTracing API, before selection and deployment of your Server Tracer. 17 | * To log with spanId, context, without using MDC. 18 | * To add log support to some server tracer that doesn't support `.log(...)` 19 | * To report some metrics (eg. histogram of span) 20 | 21 | ## Slf4jReporter 22 | 23 | * Message is reported as structured message (json) 24 | * Message at start and at finish is logged with level TRACE 25 | ``` 26 | 19:48:36.828 [main] TRACE tracer - {"ts":1490982516828,"elapsed":0,"spanId":"d4f6df3d-8dc0-4287-b1a0-1b2bc52978c6","action":"start","operation":"span-0","tags":{"description":"top level initial span in the original process"},"baggage":{},"references":{}} 27 | 19:48:36.828 [main] TRACE tracer - {"ts":1490982516828,"elapsed":0,"spanId":"da7d843a-4564-4480-a6cb-19550c24a344","action":"start","operation":"span-1","tags":{"description":"the first inner span in the original process"},"baggage":{},"references":{"child_of":"d4f6df3d-8dc0-4287-b1a0-1b2bc52978c6"}} 28 | 19:48:36.828 [main] TRACE tracer - {"ts":1490982516828,"elapsed":0,"spanId":"c4bf987f-2d0c-49f1-87bd-a23930570b96","action":"start","operation":"span-2","tags":{"description":"the second inner span in the original process"},"baggage":{},"references":{"child_of":"da7d843a-4564-4480-a6cb-19550c24a344"}} 29 | 19:48:36.841 [main] TRACE tracer - {"ts":1490982516841,"elapsed":13,"spanId":"c4bf987f-2d0c-49f1-87bd-a23930570b96","action":"finish","operation":"span-2","tags":{"description":"the second inner span in the original process"},"baggage":{},"references":{"child_of":"da7d843a-4564-4480-a6cb-19550c24a344"}} 30 | 19:48:36.841 [main] TRACE tracer - {"ts":1490982516841,"elapsed":13,"spanId":"da7d843a-4564-4480-a6cb-19550c24a344","action":"finish","operation":"span-1","tags":{"description":"the first inner span in the original process"},"baggage":{},"references":{"child_of":"d4f6df3d-8dc0-4287-b1a0-1b2bc52978c6"}} 31 | 19:48:36.841 [main] TRACE tracer - {"ts":1490982516841,"elapsed":13,"spanId":"d4f6df3d-8dc0-4287-b1a0-1b2bc52978c6","action":"finish","operation":"span-0","tags":{"description":"top level initial span in the original process","http.url":"/orders"},"baggage":{},"references":{}} 32 | ``` 33 | * Message for Span.log report with level INFO by default, the level could be set explicitly by setting the key "loglevel" 34 | ```java 35 | span.log("blablabala"); 36 | span.log(MapMaker.fields(LogLevel.FIELD_NAME, LogLevel.DEBUG, "k0", "v0", "k1", 42)); 37 | span.log(MapMaker.fields(LogLevel.FIELD_NAME, LogLevel.WARN, "k0", "v0", "ex", new Exception("boom !"))); 38 | ``` 39 | ``` 40 | 22:16:23.911 [main] INFO tracer - {"ts":1490991383911,"elapsed":1,"spanId":"dbebbda2-501e-4461-b9c6-32020df8008f","action":"log","operation":"span-2","tags":{"description":"the second inner span in the original process"},"fields":{"event":"blablabala"}} 41 | 22:16:23.911 [main] DEBUG tracer - {"ts":1490991383911,"elapsed":1,"spanId":"dbebbda2-501e-4461-b9c6-32020df8008f","action":"log","operation":"span-2","tags":{"description":"the second inner span in the original process"},"fields":{"k0":"v0","k1":42.0}} 42 | 22:16:23.911 [main] WARN tracer - {"ts":1490991383911,"elapsed":1,"spanId":"dbebbda2-501e-4461-b9c6-32020df8008f","action":"log","operation":"span-2","tags":{"description":"the second inner span in the original process"},"fields":{"ex":"java.lang.Exception: boom !\n\tat examples.Sample01.run0(Sample01.java:92)\n\tat examples.Sample01.main(Sample01.java:45)\n","k0":"v0"}} 43 | ``` 44 | 45 | # Usage 46 | 47 | ## Application intialization 48 | 49 | * Add dependency (format depends of your build tool) 50 | ``` 51 | "io.opentracing.contrib" % "java-span-reporter" % "${span-reporter.version}" 52 | ``` 53 | * Instantiate the TracerR (For using DI, you can take inspiration from [Guice samples](./span-reporter-examples/src/main/java/io/opentracing/contrib/di) 54 | ): 55 | ```java 56 | tracer = ... // if not backend tracer use NoopTracerFactory.create() 57 | tracer = new TracerR(tracer, new Slf4jReporter(LoggerFactory.getLogger("tracer"))); 58 | ``` 59 | * Setup your logger (example below use logback, but any slf4j compatible logger should work) 60 | * add dependencies 61 | ``` 62 | "ch.qos.logback" % "logback-classic" % "1.1.3" 63 | ``` 64 | * configure le logger (simplest) 65 | ```xml 66 | 67 | ``` 68 | 69 | ## Custom Reporter(s) 70 | 71 | Developer can provide its own [Reporter](./src/main/java/opentracing/contrib/reporter/Reporter.java): 72 | * to report log in an other log system 73 | * to report log in an other format 74 | * to report metrics about span/operation (histogram, nb calls, duration, ...) 75 | 76 | To report to several Reporters at once, you can use the CompositeReporter: 77 | ```java 78 | Tracer tracer = ... 79 | tracer = new TracerR(tracer, new CompositeReporter( 80 | new Slf4jReporter(LoggerFactory.getLogger("tracer")), 81 | new DropwizardMetricsReporter(...) 82 | )); 83 | ``` 84 | 85 | # Build 86 | 87 | * build localy 88 | ``` 89 | ./gradlew assemble 90 | ```` 91 | * publish to local maven repository 92 | ``` 93 | ./gradlew publishToMavenLocal 94 | ```` 95 | * release 96 | ``` 97 | git tag -a "${version}" -m "release" 98 | git push --tags 99 | ``` 100 | 101 | [ci-img]: https://travis-ci.org/opentracing-contrib/java-span-reporter.svg?branch=master 102 | [ci]: https://travis-ci.org/opentracing-contrib/java-span-reporter 103 | [cov-img]: https://coveralls.io/repos/github/opentracing-contrib/java-span-reporter/badge.svg?branch=master 104 | [cov]: https://coveralls.io/github/opentracing-contrib/java-span-reporter?branch=master 105 | [maven-img]: https://img.shields.io/maven-central/v/io.opentracing.contrib/java-span-reporter.svg?maxAge=2592000 106 | [maven]: http://search.maven.org/#search%7Cga%7C1%7Cjava-span-reporter 107 | -------------------------------------------------------------------------------- /build-publish.gradle: -------------------------------------------------------------------------------- 1 | // 2 | // This file is to be applied to some subproject. 3 | // 4 | apply plugin: 'com.jfrog.bintray' 5 | apply plugin: 'maven-publish' 6 | 7 | // documentation and samples: https://github.com/bintray/gradle-bintray-plugin 8 | project.ext.bintray_user = project.hasProperty('bintray_user') ? project.property('bintray_user') : System.getenv('BINTRAY_USER') 9 | project.ext.bintray_key = project.hasProperty('bintray_key') ? project.property('bintray_key') : System.getenv('BINTRAY_KEY') 10 | 11 | def pomConfig = { 12 | developers { 13 | developer { 14 | id "davidB" 15 | name "David Bernard" 16 | url "https://github.com/davidB" 17 | } 18 | } 19 | scm { 20 | url project.scm_url 21 | connection "scm:git:${project.scm_url}.git" 22 | developerConnection "scm:git:${project.scm_url}.git" 23 | } 24 | issueManagement { 25 | system "github" 26 | url project.issue_url 27 | } 28 | } 29 | 30 | // Create the publication with the pom configuration: 31 | publishing { 32 | publications { 33 | MyPublication(MavenPublication) { 34 | from components.java 35 | artifact sourcesJar 36 | artifact javadocJar 37 | groupId project.group 38 | artifactId project.name 39 | version project.version 40 | pom.withXml { 41 | def root = asNode() 42 | root.appendNode('description', project.description) 43 | root.appendNode('name', project.name) 44 | root.appendNode('url', project.website_url) 45 | root.appendNode('inceptionYear', project.license_year) 46 | root.children().last() + pomConfig 47 | // could not use the pomConfig to set license, 48 | // maybe because the Node license {...} is associated to the license plugin 49 | def lic = root.appendNode('licenses').appendNode('license') 50 | lic.appendNode('name', project.license_name) 51 | lic.appendNode('url', project.license_url) 52 | lic.appendNode('distribution', "repo") 53 | } 54 | } 55 | } 56 | } 57 | 58 | bintray { 59 | user = project.bintray_user 60 | key = project.bintray_key 61 | publications = ['MyPublication'] 62 | dryRun = false 63 | pkg { 64 | repo = 'maven' 65 | userOrg = 'opentracing' 66 | name = project.name 67 | desc = project.description 68 | websiteUrl = project.website_url 69 | issueTrackerUrl = project.issue_url 70 | vcsUrl = project.scm_url 71 | licenses = [project.license_name] 72 | labels = ['open-tracing'] 73 | publicDownloadNumbers = true 74 | githubRepo = project.scm_github_repo 75 | githubReleaseNotesFile = 'README.md' 76 | } 77 | } 78 | 79 | bintrayUpload.onlyIf { 80 | (project.bintray_key != null) && 81 | (version ==~ /\d+\.\d+\.\d+(-[a-zA-Z0-9]+)?/) && 82 | !(version ==~ /.*-dirty/) 83 | } 84 | 85 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id "com.github.hierynomus.license" version "0.14.0" 3 | id "com.jfrog.bintray" version "1.7.3" 4 | } 5 | 6 | allprojects { 7 | // apply plugin: 'license' 8 | 9 | project.version = "git describe --always --dirty".execute().text.trim() 10 | println("version : '${project.version}'") 11 | group = "io.opentracing.contrib" 12 | project.ext.description="OpenTracing Tracer that report traces (on logs, metrics,...)" 13 | project.ext.website_url="https://github.com/opentracing-contrib/${rootProject.name}" 14 | project.ext.issue_url="${project.website_url}/issues" 15 | project.ext.scm_github_repo="opentracing-contrib/${rootProject.name}" 16 | project.ext.scm_url="https://github.com/${project.scm_github_repo}" 17 | project.ext.license_name="Apache-2.0" // use value of bintray license enum 18 | project.ext.license_url="https://www.apache.org/licenses/LICENSE-2.0.txt" 19 | project.ext.license_year=Calendar.getInstance().get(Calendar.YEAR) 20 | project.ext.license_owner="The OpenTracing Authors" 21 | } 22 | 23 | subprojects { 24 | apply plugin: 'java' 25 | 26 | if(!project.name.contains('examples')){ 27 | apply from: rootProject.file('build-publish.gradle') 28 | } 29 | 30 | repositories { 31 | jcenter() 32 | //maven { url "https://jitpack.io" } 33 | } 34 | 35 | sourceCompatibility = JavaVersion.VERSION_1_8 36 | targetCompatibility = JavaVersion.VERSION_1_8 37 | [compileJava, compileTestJava]*.options*.encoding = 'UTF-8' 38 | 39 | javadoc { 40 | failOnError = false 41 | options.memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PROTECTED 42 | options.docTitle = "${project.name} ${project.version} Javadoc" 43 | options.windowTitle = "${project.name} ${project.version} Javadoc" 44 | options.header = "${project.name} ${project.version}" 45 | options.author = "true" 46 | options.use = "true" 47 | //disable doclint for JDK8, more quiet output 48 | if (JavaVersion.current().isJava8Compatible()){ 49 | options.addStringOption('Xdoclint:none', '-quiet') 50 | } 51 | } 52 | 53 | task sourcesJar(type: Jar, dependsOn: classes, description: 'Creates a jar from the source files.') { 54 | classifier = 'sources' 55 | from sourceSets*.allSource 56 | } 57 | 58 | task javadocJar(type: Jar, dependsOn: javadoc, description: 'Creates a jar from the javadoc files.') { 59 | classifier = 'javadoc' 60 | from javadoc.destinationDir 61 | } 62 | 63 | license { 64 | header = rootProject.file("src/etc/header.txt") 65 | strictCheck = true 66 | ext.license_year = project.license_year 67 | ext.license_owner = license_owner 68 | excludes(['src/test/resources/**', 'src/main/resources/**']) 69 | } 70 | } 71 | 72 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | v_opentracing=0.33.0 2 | 3 | 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/opentracing-contrib/java-span-reporter/df0fd335cb7b0fafcccac7ef04ad9dc4680a8c5f/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.2-bin.zip 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include 'span-reporter', 'span-reporter-examples', 'span-reporter-slf4j' 2 | 3 | -------------------------------------------------------------------------------- /span-reporter-examples/build.gradle: -------------------------------------------------------------------------------- 1 | project.ext.description = "SpanReporter (Examples)" 2 | 3 | def v_logback="1.1.3" 4 | def v_brave="4.15.0" 5 | def v_hawkular="0.14.4.Final" 6 | 7 | dependencies { 8 | compile "io.opentracing:opentracing-api:${v_opentracing}" 9 | compile "io.opentracing:opentracing-mock:${v_opentracing}" 10 | compile "io.opentracing:opentracing-util:${v_opentracing}" 11 | compile project(":span-reporter") 12 | compile project(":span-reporter-slf4j") 13 | compile "javax.inject:javax.inject:1" 14 | compile "com.google.inject:guice:4.0" 15 | 16 | // Logback 17 | compile "ch.qos.logback:logback-core:${v_logback}" 18 | compile "ch.qos.logback:logback-classic:${v_logback}" 19 | 20 | // Hawkular 21 | compile "org.hawkular.apm:hawkular-apm-client-opentracing:${v_hawkular}" 22 | compile "org.hawkular.apm:hawkular-apm-trace-publisher-rest-client:${v_hawkular}" 23 | 24 | // Brave / Zipkin 25 | // compile "io.zipkin.brave:brave-mysql:${v_brave}" 26 | // compile "io.zipkin.brave:brave-okhttp:${v_brave}" 27 | // compile "io.zipkin.brave:brave-p6spy:${v_brave}" 28 | compile "io.zipkin.reporter:zipkin-sender-okhttp3:0.6.12" 29 | compile "io.zipkin.brave:brave:${v_brave}" 30 | compile "io.opentracing.brave:brave-opentracing:0.18.1" 31 | } 32 | 33 | task run(type:JavaExec) { 34 | main = System.getProperty("exec.mainClass") ?: "examples.Sample01" 35 | classpath = sourceSets.test.runtimeClasspath 36 | } 37 | -------------------------------------------------------------------------------- /span-reporter-examples/src/main/java/examples/Sample01.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package examples; 15 | 16 | import com.google.inject.Guice; 17 | import com.google.inject.Injector; 18 | import io.opentracing.Scope; 19 | import io.opentracing.ScopeManager; 20 | import io.opentracing.Span; 21 | import io.opentracing.Tracer; 22 | import io.opentracing.contrib.di.LoggerTracerModule; 23 | import io.opentracing.contrib.di.NoopTracerModule; 24 | import io.opentracing.contrib.reporter.LogLevel; 25 | import io.opentracing.contrib.reporter.Reporter; 26 | import io.opentracing.contrib.reporter.TracerR; 27 | import io.opentracing.contrib.reporter.slf4j.Slf4jReporter; 28 | import io.opentracing.contrib.util.MapMaker; 29 | import io.opentracing.mock.MockTracer; 30 | import io.opentracing.tag.Tags; 31 | import io.opentracing.util.ThreadLocalScopeManager; 32 | import org.slf4j.LoggerFactory; 33 | 34 | public class Sample01 { 35 | public static void main(String[] args) throws Exception { 36 | System.out.print("\n>> only OpenTracing api\n"); 37 | // create the logger is longest operation 38 | //Tracer tracer = provideTracerByGuice(); 39 | Tracer tracer = provideTracerByConstructor(); 40 | for (int i = 0; i < 5; i++){ 41 | System.out.format("\n>> run %d\n", i); 42 | run0(tracer); 43 | } 44 | //delay to send data to backend-tracer 45 | //Thread.sleep(2000); 46 | System.out.print("\n>> end\n"); 47 | } 48 | 49 | private static Tracer provideTracerByGuice() throws Exception { 50 | //Injector injector = Guice.createInjector(new BraveModule(), new CtxBasicModule()); 51 | //Injector injector = Guice.createInjector(new HawkularModule(), new LoggerTracerModule()); 52 | Injector injector = Guice.createInjector(new NoopTracerModule(), new LoggerTracerModule()); 53 | return injector.getInstance(Tracer.class); 54 | } 55 | 56 | private static Tracer provideTracerByConstructor() throws Exception { 57 | Tracer backend = new MockTracer(); 58 | Reporter reporter = new Slf4jReporter(LoggerFactory.getLogger("tracer"), true); 59 | //ScopeManager scopeManager = new ThreadLocalScopeManager(); 60 | ScopeManager scopeManager = new ThreadLocalScopeManager(); 61 | return new TracerR(backend, reporter, scopeManager); 62 | } 63 | 64 | private static void run0(Tracer tracer) throws Exception { 65 | // start a span 66 | try(Scope scope0 = tracer.activateSpan(tracer.buildSpan("span-0") 67 | .withTag("description", "top level initial span in the original process").start())) { 68 | Span span0 = tracer.activeSpan(); 69 | Tags.HTTP_URL.set(span0, "/orders"); //span0.setTag(Tags.HTTP_URL.getKey(), "/orders"); 70 | //Tags.HTTP_METHOD.set(span0, "POST"); 71 | //Tags.PEER_SERVICE.set(span0, "OrderManager"); 72 | //Tags.SPAN_KIND.set(span0, Tags.SPAN_KIND_SERVER); 73 | try(Scope scope1 = tracer.activateSpan(tracer.buildSpan("span-1") 74 | .withTag("description", "the first inner span in the original process") 75 | .start())) { 76 | Span span1 = tracer.activeSpan(); 77 | 78 | // do something 79 | 80 | // start another span 81 | 82 | try(Scope scope2 = tracer.activateSpan(tracer.buildSpan("span-2") 83 | .asChildOf(span1) 84 | .withTag("description", "the second inner span in the original process") 85 | .start())) { 86 | Span span2 = tracer.activeSpan(); 87 | 88 | // do something 89 | span2.log("blablabala"); 90 | span2.log(MapMaker.fields(LogLevel.FIELD_NAME, LogLevel.DEBUG, "k0", "v0", "k1", 42)); 91 | span2.log(MapMaker.fields(LogLevel.FIELD_NAME, LogLevel.WARN, "k0", "v0", "ex", new Exception("boom !"))); 92 | 93 | // cross process boundary 94 | //Map map = new java.util.HashMap<>(); 95 | //tracer.inject(span2.context(), Format.Builtin.HTTP_HEADERS, new TextMapInjectAdapter(map)) 96 | Thread.currentThread().sleep(10); 97 | // request.addHeaders(map); 98 | // request.doGet(); 99 | } 100 | } 101 | } 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /span-reporter-examples/src/main/java/examples/Sample01.scala.off: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package sandbox 15 | 16 | import java.util 17 | 18 | import com.google.inject.Guice 19 | import context.CtxTools 20 | import context.di.CtxBasicModule 21 | import di.{BraveModule, HawkularModule, LoggerTracerModule, NoopTracerModule} 22 | import io.opentracing.Tracer 23 | import io.opentracing.propagation.{Format, TextMapInjectAdapter} 24 | import io.opentracing.tag.Tags 25 | 26 | /** 27 | * Created by davidb on 15/02/17. 28 | */ 29 | object Sample01 { 30 | def main(args: Array[String]): Unit = { 31 | //val injector = Guice.createInjector(new BraveModule(), new CtxBasicModule()) 32 | //val injector = Guice.createInjector(new HawkularModule(), new CtxBasicModule(), new LoggerTracerModule) 33 | val injector = Guice.createInjector(new NoopTracerModule(), new CtxBasicModule(), new LoggerTracerModule) 34 | System.out.print("\n only OpenTracing api\n") 35 | val tracer = injector.getInstance(classOf[Tracer]) 36 | (0 until 5).foreach { _ => 37 | run0(tracer) 38 | } 39 | System.out.print("\n use CtxTools api\n") 40 | val ctxTools = injector.getInstance(classOf[CtxTools]) 41 | (0 until 5).foreach { _ => 42 | run1(ctxTools) 43 | } 44 | System.out.print("\n waiting 2s to give time to reporter\n") 45 | Thread.sleep(2000) 46 | System.out.print("\n end\n") 47 | } 48 | 49 | def run0(tracer: Tracer): Unit = { 50 | // start a span 51 | val span0 = tracer.buildSpan("span-0") 52 | .withTag("description", "top level initial span in the original process") 53 | .start() 54 | Tags.HTTP_URL.set(span0, "/orders") //span.setTag(Tags.HTTP_URL.getKey(), "/orders") 55 | //Tags.HTTP_METHOD.set(span0, "POST") 56 | //Tags.PEER_SERVICE.set(span0, "OrderManager") 57 | //Tags.SPAN_KIND.set(span0, Tags.SPAN_KIND_SERVER) 58 | try { 59 | 60 | val span1 = tracer.buildSpan("span-1") 61 | .asChildOf(span0) 62 | .withTag("description", "the first inner span in the original process") 63 | .start() 64 | try { 65 | 66 | // do something 67 | 68 | // start another span 69 | 70 | val span2 = tracer.buildSpan("span-2") 71 | .asChildOf(span1) 72 | .withTag("description", "the second inner span in the original process") 73 | .start() 74 | try { 75 | 76 | // do something 77 | 78 | // cross process boundary 79 | val map = new util.HashMap[String, String]() 80 | //tracer.inject(span2.context(), Format.Builtin.HTTP_HEADERS, new TextMapInjectAdapter(map)) 81 | System.out.print(".") 82 | // request.addHeaders(map); 83 | // request.doGet(); 84 | } finally { 85 | span2.finish() 86 | } 87 | } finally { 88 | span1.finish() 89 | } 90 | } finally { 91 | span0.finish() 92 | } 93 | } 94 | 95 | def run1(ctxTools: CtxTools): Unit = { 96 | // start a span 97 | ctxTools.withCtx(ctxTools.newCtx("span-0")) { implicit ctx => 98 | ctx.foreach { x => 99 | x.span.setTag("description", "top level initial span in the original process") 100 | Tags.HTTP_URL.set(x.span, "/orders") 101 | //Tags.HTTP_METHOD.set(x.span, "POST") 102 | //Tags.PEER_SERVICE.set(x.span, "OrderManager") 103 | //Tags.SPAN_KIND.set(x.span, Tags.SPAN_KIND_SERVER) 104 | } 105 | ctxTools.withCtx(ctxTools.newCtx("span-1")) { implicit ctx => 106 | ctx.foreach(_.span.setTag("description", "the first inner span in the original process")) 107 | // do something 108 | // start another span 109 | ctxTools.withCtx(ctxTools.newCtx("span-2")) { implicit ctx => 110 | ctx.foreach(_.span.setTag("description", "the second inner span in the original process")) 111 | // do something 112 | // cross process boundary 113 | val map = new util.HashMap[String, String]() 114 | //TODO tracer.inject(span2.context(), Format.Builtin.HTTP_HEADERS, new TextMapInjectAdapter(map)) 115 | // request.addHeaders(map); 116 | // request.doGet(); 117 | System.out.print(".") 118 | } 119 | } 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /span-reporter-examples/src/main/java/io/opentracing/contrib/di/BraveTracerModule.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package io.opentracing.contrib.di; 15 | 16 | import brave.opentracing.BraveTracer; 17 | import com.google.inject.AbstractModule; 18 | import com.google.inject.Provides; 19 | import io.opentracing.Tracer; 20 | import zipkin.reporter.AsyncReporter; 21 | import zipkin.reporter.okhttp3.OkHttpSender; 22 | 23 | import javax.inject.Named; 24 | import javax.inject.Singleton; 25 | 26 | public class BraveTracerModule extends AbstractModule { 27 | @Override 28 | protected void configure() { 29 | 30 | } 31 | @Provides 32 | @Singleton 33 | @Named("backend") 34 | protected Tracer tracer() { 35 | // Configure a reporter, which controls how often spans are sent 36 | // (the dependency is io.zipkin.reporter:zipkin-sender-okhttp3) 37 | OkHttpSender sender = OkHttpSender.create("http://127.0.0.1:9411/api/v1/spans"); 38 | AsyncReporter reporter = AsyncReporter.builder(sender).build(); 39 | 40 | // Now, create a Brave tracer with the service name you want to see in Zipkin. 41 | // (the dependency is io.zipkin.brave:brave) 42 | brave.Tracer braveTracer = brave.Tracer.newBuilder() 43 | .localServiceName("my-service") 44 | .reporter(reporter) 45 | .build(); 46 | 47 | // Finally, wrap this with the OpenTracing Api 48 | BraveTracer tracer = BraveTracer.wrap(braveTracer); 49 | //GlobalTracer.register(tracer) 50 | 51 | // You can later unwrap the underlying Brave Api as needed 52 | //val braveTracer = tracer.unwrap(); 53 | return tracer; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /span-reporter-examples/src/main/java/io/opentracing/contrib/di/HawkularTracerModule.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package io.opentracing.contrib.di; 15 | 16 | import com.google.inject.AbstractModule; 17 | import com.google.inject.Provides; 18 | import io.opentracing.Tracer; 19 | import org.hawkular.apm.api.utils.PropertyUtil; 20 | import org.hawkular.apm.client.api.recorder.BatchTraceRecorder; 21 | import org.hawkular.apm.client.api.recorder.TraceRecorder; 22 | import org.hawkular.apm.client.opentracing.APMTracer; 23 | import org.hawkular.apm.trace.publisher.rest.client.TracePublisherRESTClient; 24 | 25 | import javax.inject.Named; 26 | import javax.inject.Singleton; 27 | 28 | public class HawkularTracerModule extends AbstractModule { 29 | @Override 30 | protected void configure() { 31 | } 32 | 33 | @Provides 34 | @Singleton 35 | @Named("backend") 36 | protected Tracer tracer(TraceRecorder traceRecorder) { 37 | APMTracer tracer0 = new APMTracer(traceRecorder); 38 | //GlobalTracer.register(tracer0) 39 | //GlobalTracer.get() 40 | return tracer0; 41 | } 42 | 43 | //Hawkular seems to failed to load TracePublisher via ServiceLoader, so Made a explicit 44 | @Provides 45 | @Singleton 46 | protected TraceRecorder traceRecorder() { 47 | TracePublisherRESTClient publisher = new TracePublisherRESTClient( 48 | PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_USERNAME, "jdoe"), 49 | PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_PASSWORD, "password"), 50 | PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_URI, "http://localhost:8080") 51 | ); 52 | BatchTraceRecorder.BatchTraceRecorderBuilder builder = new BatchTraceRecorder.BatchTraceRecorderBuilder(); 53 | builder.withTracePublisher(publisher); 54 | 55 | String batchSize = PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_COLLECTOR_BATCHSIZE); 56 | if (batchSize != null) { 57 | builder.withBatchSize(Integer.parseInt(batchSize)); 58 | } 59 | String batchTime = PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_COLLECTOR_BATCHTIME); 60 | if (batchTime != null) { 61 | builder.withBatchTime(Integer.parseInt(batchTime)); 62 | } 63 | String threadPoolSize = PropertyUtil.getProperty(PropertyUtil.HAWKULAR_APM_COLLECTOR_BATCHTHREADS); 64 | if (threadPoolSize != null) { 65 | builder.withBatchPoolSize(Integer.parseInt(threadPoolSize)); 66 | } 67 | builder.withTenantId(PropertyUtil.getProperty("HAWKULAR_APM_TENANTID")); 68 | return new BatchTraceRecorder(builder); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /span-reporter-examples/src/main/java/io/opentracing/contrib/di/LoggerTracerModule.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package io.opentracing.contrib.di; 15 | 16 | import com.google.inject.AbstractModule; 17 | import com.google.inject.Provides; 18 | import io.opentracing.ScopeManager; 19 | import io.opentracing.Tracer; 20 | import io.opentracing.contrib.reporter.TracerR; 21 | import io.opentracing.contrib.reporter.slf4j.Slf4jReporter; 22 | import io.opentracing.util.ThreadLocalScopeManager; 23 | import org.slf4j.LoggerFactory; 24 | 25 | import javax.inject.Named; 26 | import javax.inject.Singleton; 27 | 28 | public class LoggerTracerModule extends AbstractModule { 29 | @Override 30 | protected void configure() { 31 | 32 | } 33 | 34 | @Provides 35 | @Singleton 36 | protected ScopeManager scopeManager(@Named("backend") Tracer tracer) { 37 | return (tracer.scopeManager() == null) ? tracer.scopeManager() : new ThreadLocalScopeManager(); 38 | } 39 | 40 | @Provides 41 | @Singleton 42 | protected Tracer tracer(@Named("backend") Tracer tracer, ScopeManager scopeManager) { 43 | return new TracerR(tracer, new Slf4jReporter(LoggerFactory.getLogger("tracer"), true), scopeManager); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /span-reporter-examples/src/main/java/io/opentracing/contrib/di/NoopTracerModule.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package io.opentracing.contrib.di; 15 | 16 | import com.google.inject.AbstractModule; 17 | import com.google.inject.Provides; 18 | import io.opentracing.Tracer; 19 | import io.opentracing.noop.NoopTracerFactory; 20 | 21 | import javax.inject.Named; 22 | import javax.inject.Singleton; 23 | 24 | public class NoopTracerModule extends AbstractModule { 25 | @Override 26 | protected void configure() { 27 | 28 | } 29 | @Provides 30 | @Singleton 31 | @Named("backend") 32 | protected Tracer tracer() { 33 | return NoopTracerFactory.create(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /span-reporter-examples/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | -------------------------------------------------------------------------------- /span-reporter-slf4j/build.gradle: -------------------------------------------------------------------------------- 1 | project.ext.description = "SpanReporter For Slf4j" 2 | 3 | dependencies { 4 | //compile "io.opentracing:opentracing-api:${v_opentracing}" 5 | compile project(":span-reporter") 6 | compile "io.opentracing:opentracing-mock:${v_opentracing}" 7 | compile "io.opentracing:opentracing-util:${v_opentracing}" 8 | compile "org.slf4j:slf4j-api:1.7.25" 9 | compile "com.fasterxml.jackson.core:jackson-core:2.6.0" 10 | } 11 | -------------------------------------------------------------------------------- /span-reporter-slf4j/src/main/java/io/opentracing/contrib/reporter/slf4j/DefaultLoggerTracer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package io.opentracing.contrib.reporter.slf4j; 15 | 16 | import io.opentracing.contrib.reporter.TracerR; 17 | import io.opentracing.mock.MockTracer; 18 | import io.opentracing.util.ThreadLocalScopeManager; 19 | import org.slf4j.LoggerFactory; 20 | 21 | /** 22 | * A TracerR with a zero args Constructor and default configuration. 23 | * It's the implementation use by ServiceLoader (META-INF/services/io.opentracing.Tracer) 24 | * 25 | * new TracerR(new MockTracer(), new Slf4jReporter(LoggerFactory.getLogger("tracer"), true), new AutoFinishScopeManager()); 26 | * 27 | */ 28 | public final class DefaultLoggerTracer extends TracerR { 29 | 30 | /** 31 | * No args constructor used by Service Loader 32 | */ 33 | public DefaultLoggerTracer() { 34 | super(new MockTracer(), new Slf4jReporter(LoggerFactory.getLogger("tracer"), true), new ThreadLocalScopeManager()); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /span-reporter-slf4j/src/main/java/io/opentracing/contrib/reporter/slf4j/Slf4jReporter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package io.opentracing.contrib.reporter.slf4j; 15 | 16 | import com.fasterxml.jackson.core.JsonFactory; 17 | import com.fasterxml.jackson.core.JsonGenerator; 18 | import io.opentracing.contrib.reporter.LogLevel; 19 | import io.opentracing.contrib.reporter.SpanData; 20 | import io.opentracing.contrib.reporter.Reporter; 21 | import org.slf4j.Logger; 22 | import org.slf4j.LoggerFactory; 23 | 24 | import java.io.PrintWriter; 25 | import java.io.StringWriter; 26 | import java.time.Duration; 27 | import java.time.Instant; 28 | import java.util.Map; 29 | 30 | /** 31 | * A Reporter to a slf4j Logger. 32 | *
    33 | *
  • report start, finish with level TRACE
  • 34 | *
  • report log with level define by key "loglevel" (value is a LogLevel), by default INFO
  • 35 | *
  • message are formatted as json (structured message)
  • 36 | *
37 | */ 38 | public class Slf4jReporter implements Reporter { 39 | private final Logger logger; 40 | private final JsonFactory f = new JsonFactory(); 41 | private final boolean includeStackTraceInStructuredLog; 42 | 43 | public Slf4jReporter(Logger logger, boolean includeStackTraceInStructuredLog) { 44 | LoggerFactory.getLogger(this.getClass()).info("{reporter: 'init'}"); 45 | this.logger = logger; 46 | this.includeStackTraceInStructuredLog = includeStackTraceInStructuredLog; 47 | } 48 | 49 | @Override 50 | public void start(Instant ts, SpanData span) { 51 | if (logger.isTraceEnabled()) { 52 | logger.trace(toStructuredMessage(ts, "start", span,null)); 53 | } 54 | } 55 | 56 | @Override 57 | public void finish(Instant ts, SpanData span) { 58 | if (logger.isTraceEnabled()) { 59 | logger.trace(toStructuredMessage(ts, "finish", span, null)); 60 | } 61 | } 62 | 63 | @Override 64 | public void log(Instant ts, SpanData span, Map fields) { 65 | LogLevel level = LogLevel.INFO; 66 | try { 67 | LogLevel level0 = (LogLevel) fields.get(LogLevel.FIELD_NAME); 68 | if (level0 != null) { 69 | level = level0; 70 | fields.remove(LogLevel.FIELD_NAME); 71 | } 72 | } catch (Exception exc) { 73 | logger.warn("fail to read value of field {}", LogLevel.FIELD_NAME, exc); 74 | } 75 | switch (level) { 76 | case TRACE: 77 | if (logger.isTraceEnabled()) { 78 | logger.trace(toStructuredMessage(ts, "log", span, fields)); 79 | } 80 | break; 81 | case DEBUG: 82 | if (logger.isDebugEnabled()) { 83 | logger.debug(toStructuredMessage(ts, "log", span, fields)); 84 | } 85 | break; 86 | case WARN: 87 | if (logger.isWarnEnabled()) { 88 | logger.warn(toStructuredMessage(ts, "log", span, fields)); 89 | } 90 | break; 91 | case ERROR: 92 | if (logger.isErrorEnabled()) { 93 | logger.error(toStructuredMessage(ts, "log", span, fields)); 94 | } 95 | break; 96 | default: 97 | if (logger.isInfoEnabled()) { 98 | logger.info(toStructuredMessage(ts, "log", span, fields)); 99 | } 100 | } 101 | } 102 | 103 | protected String toStructuredMessage(Instant ts, String action, SpanData span, Map fields){ 104 | //return "" + (timestampMicroseconds - startAt); 105 | 106 | try { 107 | StringWriter w = new StringWriter(); 108 | JsonGenerator g = f.createGenerator(w); 109 | 110 | g.writeStartObject(); 111 | g.writeNumberField("ts", ts.toEpochMilli()); 112 | g.writeNumberField("elapsed", Duration.between(span.startAt, ts).toMillis()); 113 | g.writeStringField("spanId", span.spanId); 114 | g.writeStringField("action", action); 115 | g.writeStringField("operation", span.operationName); 116 | g.writeObjectFieldStart("tags"); 117 | for(Map.Entry kv : span.tags.entrySet()){ 118 | Object v = kv.getValue(); 119 | if (v instanceof String) { 120 | g.writeStringField(kv.getKey(), (String)v); 121 | } else if (v instanceof Number) { 122 | g.writeNumberField(kv.getKey(), ((Number) v).doubleValue()); 123 | } else if (v instanceof Boolean) { 124 | g.writeBooleanField(kv.getKey(), (Boolean) v); 125 | } 126 | } 127 | g.writeEndObject(); 128 | if (fields != null && !fields.isEmpty()){ 129 | g.writeObjectFieldStart("fields"); 130 | for(Map.Entry kv : fields.entrySet()){ 131 | Object v = kv.getValue(); 132 | if (v instanceof String) { 133 | g.writeStringField(kv.getKey(), (String)v); 134 | } else if (v instanceof Number) { 135 | g.writeNumberField(kv.getKey(), ((Number) v).doubleValue()); 136 | } else if (v instanceof Boolean) { 137 | g.writeBooleanField(kv.getKey(), (Boolean) v); 138 | } else if (v instanceof Throwable){ 139 | if (includeStackTraceInStructuredLog) { 140 | try (StringWriter w2 = new StringWriter()) { 141 | ((Throwable) v).printStackTrace(new PrintWriter(w2)); 142 | g.writeStringField(kv.getKey(), w2.toString()); 143 | }catch (Exception ignore){ 144 | g.writeStringField(kv.getKey(), String.valueOf(v)); 145 | } 146 | } else { 147 | g.writeStringField(kv.getKey(), String.valueOf(v)); 148 | } 149 | } else { 150 | g.writeStringField(kv.getKey(), String.valueOf(v)); 151 | } 152 | } 153 | g.writeEndObject(); 154 | } else { 155 | g.writeObjectFieldStart("baggage"); 156 | for(Map.Entry kv : span.context().baggageItems()){ 157 | g.writeStringField(kv.getKey(), kv.getValue()); 158 | } 159 | g.writeEndObject(); 160 | g.writeObjectFieldStart("references"); 161 | for(Map.Entry kv : span.references.entrySet()){ 162 | g.writeStringField(kv.getKey(), kv.getValue()); 163 | } 164 | g.writeEndObject(); 165 | } 166 | 167 | g.writeEndObject(); 168 | g.close(); 169 | w.close(); 170 | return w.toString(); 171 | } catch(Exception exc) { 172 | exc.printStackTrace(); 173 | } 174 | return ""; 175 | } 176 | } 177 | -------------------------------------------------------------------------------- /span-reporter-slf4j/src/main/resources/META-INF/services/io.opentracing.Tracer: -------------------------------------------------------------------------------- 1 | io.opentracing.contrib.reporter.slf4j.DefaultLoggerTracer 2 | -------------------------------------------------------------------------------- /span-reporter/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | dependencies { 3 | compile "io.opentracing:opentracing-api:${v_opentracing}" 4 | compile "io.opentracing:opentracing-util:${v_opentracing}" 5 | 6 | testCompile gradleTestKit() 7 | testCompile 'junit:junit:4.12' 8 | testCompile "org.mockito:mockito-core:3.1.+" 9 | testCompile "io.opentracing:opentracing-mock:${v_opentracing}" 10 | 11 | } 12 | -------------------------------------------------------------------------------- /span-reporter/src/main/java/io/opentracing/contrib/reporter/CompositeReporter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package io.opentracing.contrib.reporter; 15 | 16 | import java.time.Instant; 17 | import java.util.Map; 18 | 19 | /** 20 | * Composite Reporter broadcast reporter's calls to several Reporter. 21 | * Could used to call a reporter to log system AND a reporter to metrics. 22 | * 23 | * Tracer tracer = ... 24 | * tracer = new TracerR(tracer, new CompositeReporter( 25 | * loggerReporter, 26 | * metricsReporter 27 | * )); 28 | * 29 | */ 30 | public class CompositeReporter implements Reporter { 31 | private final Reporter[] reporters; 32 | 33 | public CompositeReporter(Reporter... reporters) { 34 | this.reporters = reporters; 35 | } 36 | 37 | @Override 38 | public void start(Instant ts, SpanData span) { 39 | for(Reporter r: reporters) { 40 | try { 41 | r.start(ts, span); 42 | } catch (Exception exc) { 43 | exc.printStackTrace(); 44 | } 45 | } 46 | } 47 | 48 | @Override 49 | public void finish(Instant ts, SpanData span) { 50 | for(Reporter r: reporters) { 51 | try { 52 | r.finish(ts, span); 53 | } catch (Exception exc) { 54 | exc.printStackTrace(); 55 | } 56 | } 57 | } 58 | 59 | @Override 60 | public void log(Instant ts, SpanData span, Map fields) { 61 | for(Reporter r: reporters) { 62 | try { 63 | r.log(ts, span, fields); 64 | } catch (Exception exc) { 65 | exc.printStackTrace(); 66 | } 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /span-reporter/src/main/java/io/opentracing/contrib/reporter/LogLevel.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package io.opentracing.contrib.reporter; 15 | 16 | public enum LogLevel { 17 | TRACE, DEBUG, INFO, WARN, ERROR; 18 | public static String FIELD_NAME = "log.level"; 19 | } 20 | -------------------------------------------------------------------------------- /span-reporter/src/main/java/io/opentracing/contrib/reporter/Reporter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package io.opentracing.contrib.reporter; 15 | 16 | import java.time.Instant; 17 | import java.util.Map; 18 | 19 | public interface Reporter { 20 | void start(Instant timestamp, SpanData span); 21 | void finish(Instant timestamp, SpanData span); 22 | void log(Instant timestamp, SpanData span, Map fields); 23 | } 24 | -------------------------------------------------------------------------------- /span-reporter/src/main/java/io/opentracing/contrib/reporter/SpanBuilderR.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package io.opentracing.contrib.reporter; 15 | 16 | import io.opentracing.*; 17 | import io.opentracing.tag.Tag; 18 | 19 | import java.util.LinkedHashMap; 20 | import java.util.Map; 21 | import java.util.UUID; 22 | 23 | public class SpanBuilderR implements Tracer.SpanBuilder { 24 | static final String BAGGAGE_SPANID_KEY = "reporter.spanId"; 25 | private Tracer.SpanBuilder wrapped; 26 | private Reporter reporter; 27 | private ScopeManager scopeManager; 28 | private final Map tags = new LinkedHashMap<>(); 29 | private final Map references = new LinkedHashMap<>(); 30 | private String operationName; 31 | private boolean ignoreActiveSpan; 32 | 33 | 34 | SpanBuilderR(Tracer.SpanBuilder wrapped, Reporter reporter, String operationName, ScopeManager scopeManager){ 35 | this.wrapped = wrapped; 36 | this.reporter = reporter; 37 | this.operationName = operationName; 38 | this.scopeManager = scopeManager; 39 | } 40 | 41 | String findSpanId(SpanContext context) { 42 | if (context != null && context.baggageItems() != null) { 43 | for (Map.Entry kv: context.baggageItems()) { 44 | if (BAGGAGE_SPANID_KEY.equals(kv.getKey())) { 45 | return kv.getValue(); 46 | } 47 | } 48 | } 49 | return ""; 50 | } 51 | 52 | @Override 53 | public Tracer.SpanBuilder asChildOf(SpanContext spanContext) { 54 | if(spanContext != null) { 55 | return addReference(References.CHILD_OF, spanContext); 56 | } 57 | return this; 58 | } 59 | 60 | @Override 61 | public Tracer.SpanBuilder asChildOf(Span parent) { 62 | if(parent != null) { 63 | return addReference(References.CHILD_OF, parent.context()); 64 | } 65 | return this; 66 | } 67 | 68 | //FIXME manage reference to parent 69 | @Override 70 | public Tracer.SpanBuilder addReference(String s, SpanContext spanContext) { 71 | wrapped.addReference(s, spanContext); 72 | references.put(s, findSpanId(spanContext)); 73 | return this; 74 | } 75 | 76 | //FIXME manage reference to parent 77 | @Override 78 | public Tracer.SpanBuilder ignoreActiveSpan() { 79 | wrapped.ignoreActiveSpan(); 80 | this.ignoreActiveSpan = true; 81 | return this; 82 | } 83 | 84 | @Override 85 | public Tracer.SpanBuilder withTag(String s, String s1) { 86 | wrapped = wrapped.withTag(s, s1); 87 | tags.put(s, s1); 88 | return this; 89 | } 90 | 91 | @Override 92 | public Tracer.SpanBuilder withTag(String s, boolean b) { 93 | wrapped = wrapped.withTag(s, b); 94 | tags.put(s, b); 95 | return this; 96 | } 97 | 98 | @Override 99 | public Tracer.SpanBuilder withTag(String s, Number number) { 100 | wrapped = wrapped.withTag(s, number); 101 | tags.put(s, number); 102 | return this; 103 | } 104 | 105 | @Override 106 | public Tracer.SpanBuilder withTag(final Tag tag, final T value) { 107 | wrapped = wrapped.withTag(tag, value); 108 | tags.put(tag.getKey(), value); 109 | return this; 110 | } 111 | 112 | @Override 113 | public Tracer.SpanBuilder withStartTimestamp(long l) { 114 | wrapped = wrapped.withStartTimestamp(l); 115 | return this; 116 | } 117 | 118 | @Override 119 | public Span start() { 120 | Span wspan = wrapped.start(); 121 | String spanId = UUID.randomUUID().toString(); 122 | wspan.setBaggageItem(BAGGAGE_SPANID_KEY, spanId); 123 | 124 | // shamelessly copied from io.jaegertracing.internal.JaegerTracer.SpanBuilder#start 125 | // of io.jaegertracing:jaeger-core:0.35.5 126 | if (references.isEmpty() && !ignoreActiveSpan && null != scopeManager.activeSpan()) { 127 | asChildOf(scopeManager.activeSpan()); 128 | } 129 | 130 | return new SpanR(wspan, reporter, spanId, operationName, tags, references); 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /span-reporter/src/main/java/io/opentracing/contrib/reporter/SpanData.java: -------------------------------------------------------------------------------- 1 | package io.opentracing.contrib.reporter; 2 | 3 | import io.opentracing.SpanContext; 4 | 5 | import java.time.Instant; 6 | import java.util.Map; 7 | 8 | abstract public class SpanData { 9 | public String spanId; 10 | public String operationName; 11 | public Instant startAt; 12 | public Map tags; 13 | public Map references; 14 | abstract public SpanContext context(); 15 | } 16 | -------------------------------------------------------------------------------- /span-reporter/src/main/java/io/opentracing/contrib/reporter/SpanR.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package io.opentracing.contrib.reporter; 15 | 16 | import io.opentracing.Span; 17 | import io.opentracing.SpanContext; 18 | import io.opentracing.tag.Tag; 19 | 20 | import java.time.Instant; 21 | import java.util.Collections; 22 | import java.util.Map; 23 | import java.util.concurrent.ConcurrentHashMap; 24 | 25 | class SpanR extends SpanData implements Span { 26 | private Span wrapped; 27 | private final Reporter reporter; 28 | 29 | public SpanR(Span wrapped, Reporter reporter, String spanId, String operationName, Map tags, Map references) { 30 | this.reporter = reporter; 31 | this.wrapped = wrapped; 32 | this.spanId = spanId; 33 | this.operationName = operationName; 34 | this.tags = new ConcurrentHashMap<>(tags); 35 | this.references = Collections.unmodifiableMap(references); 36 | this.startAt = now(); 37 | reporter.start(this.startAt, this); 38 | } 39 | 40 | protected Instant now(){ 41 | return Instant.now(); 42 | } 43 | 44 | protected Instant ts(long timestampMicroSeconds){ 45 | // lost of precision 46 | return Instant.ofEpochMilli(timestampMicroSeconds / 1000); 47 | } 48 | 49 | //------------------------------------------------------------------------------------------------------------------ 50 | // Span 51 | 52 | @Override 53 | public SpanContext context() { 54 | return wrapped.context(); 55 | } 56 | 57 | @Override 58 | public void finish() { 59 | wrapped.finish(); 60 | reporter.finish(now(), this); 61 | } 62 | 63 | @Override 64 | public void finish(long l) { 65 | wrapped.finish(l); 66 | reporter.finish(ts(l), this); 67 | } 68 | 69 | @Override 70 | public Span setTag(String s, boolean b) { 71 | wrapped = wrapped.setTag(s, b); 72 | this.tags.put(s, b); 73 | return this; 74 | } 75 | 76 | @Override 77 | public Span setTag(String s, String s1) { 78 | wrapped = wrapped.setTag(s, s1); 79 | this.tags.put(s, s1); 80 | return this; 81 | } 82 | 83 | @Override 84 | public Span setTag(String s, Number number) { 85 | wrapped = wrapped.setTag(s, number); 86 | this.tags.put(s, number); 87 | return this; 88 | } 89 | 90 | @Override 91 | public Span setTag(final Tag tag, final T value) { 92 | wrapped = wrapped.setTag(tag, value); 93 | this.tags.put(tag.getKey(), value); 94 | return this; 95 | } 96 | 97 | @Override 98 | public Span log(Map map) { 99 | wrapped = wrapped.log(map); 100 | toLogger(now(), map); 101 | return this; 102 | } 103 | 104 | @Override 105 | public Span log(long l, Map map) { 106 | wrapped = wrapped.log(l, map); 107 | toLogger(ts(l), map); 108 | return this; 109 | } 110 | 111 | @Override 112 | public Span log(String event) { 113 | wrapped = wrapped.log(event); 114 | toLogger(now(), Collections.singletonMap("event", event)); 115 | return this; 116 | } 117 | 118 | @Override 119 | public Span log(long l, String event) { 120 | wrapped.log(l, event); 121 | toLogger(ts(l), Collections.singletonMap("event", event)); 122 | return this; 123 | } 124 | 125 | @Override 126 | public Span setBaggageItem(String s, String s1) { 127 | wrapped = wrapped.setBaggageItem(s, s1); 128 | return this; 129 | } 130 | 131 | @Override 132 | public String getBaggageItem(String s) { 133 | return wrapped.getBaggageItem(s); 134 | } 135 | 136 | @Override 137 | public SpanR setOperationName(String s) { 138 | wrapped = wrapped.setOperationName(s); 139 | this.operationName = s; 140 | return this; 141 | } 142 | 143 | protected void toLogger(Instant ts, Map map) { 144 | reporter.log(ts, this, map); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /span-reporter/src/main/java/io/opentracing/contrib/reporter/TracerR.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package io.opentracing.contrib.reporter; 15 | 16 | import io.opentracing.*; 17 | import io.opentracing.propagation.Format; 18 | 19 | public class TracerR implements Tracer { 20 | final Tracer wrapped; 21 | final Reporter reporter; 22 | final ScopeManager scopeManager; 23 | 24 | /** 25 | * @param wrapped the backend tracer, if you don't want a wrapped tracer use NoopTracerFactory.create() 26 | * @param reporter the reporter to use (eg )) ) 27 | */ 28 | public TracerR(Tracer wrapped, Reporter reporter, ScopeManager scopeManager) { 29 | this.wrapped = wrapped; 30 | this.reporter = reporter; 31 | this.scopeManager = scopeManager; 32 | } 33 | 34 | @Override 35 | public ScopeManager scopeManager() { 36 | return scopeManager; 37 | } 38 | 39 | @Override 40 | public Span activeSpan() { 41 | return this.scopeManager.activeSpan(); 42 | } 43 | 44 | @Override 45 | public Scope activateSpan(final Span span) { 46 | return this.scopeManager.activate(span); 47 | } 48 | 49 | @Override 50 | public SpanBuilder buildSpan(String s) { 51 | return new SpanBuilderR(wrapped.buildSpan(s), reporter, s, scopeManager()); 52 | } 53 | 54 | @Override 55 | public void inject(SpanContext spanContext, Format format, C c) { 56 | wrapped.inject(spanContext, format, c); 57 | } 58 | 59 | @Override 60 | public SpanContext extract(Format format, C c) { 61 | return wrapped.extract(format, c); 62 | } 63 | 64 | @Override 65 | public void close() { 66 | this.wrapped.close(); 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /span-reporter/src/main/java/io/opentracing/contrib/util/MapMaker.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 The OpenTracing Authors 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 | * in compliance with the License. You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software distributed under the License 10 | * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 | * or implied. See the License for the specific language governing permissions and limitations under 12 | * the License. 13 | */ 14 | package io.opentracing.contrib.util; 15 | 16 | import java.util.HashMap; 17 | import java.util.Map; 18 | 19 | /** 20 | * Helpers to create Map in a single line of code. 21 | */ 22 | public class MapMaker { 23 | /** 24 | * 25 | * @param keyAndValue 26 | */ 27 | public static Map fields(Object... keyAndValue){ 28 | int lg = keyAndValue.length / 2; 29 | HashMap m = new HashMap<>(); 30 | for(int i = 0; i < lg; i++) { 31 | m.put(String.valueOf(keyAndValue[i*2]), keyAndValue[i*2+1]); 32 | } 33 | return m; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /span-reporter/src/test/java/io/opentracing/contrib/reporter/SpanBuilderRTest.java: -------------------------------------------------------------------------------- 1 | package io.opentracing.contrib.reporter; 2 | 3 | import io.opentracing.ScopeManager; 4 | import io.opentracing.Span; 5 | import io.opentracing.SpanContext; 6 | import io.opentracing.Tracer; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | 13 | import static io.opentracing.References.CHILD_OF; 14 | import static org.junit.Assert.*; 15 | import static org.mockito.Mockito.*; 16 | 17 | public class SpanBuilderRTest { 18 | @Before 19 | public void setup() { 20 | this.reporterMock = mock(Reporter.class); 21 | this.spanBuilderMock = mock(Tracer.SpanBuilder.class); 22 | this.scopeManagerMock = mock(ScopeManager.class); 23 | this.newSpanMock = mock(Span.class); 24 | this.parentSpanMock = mock(Span.class); 25 | this.parentSpanContextMock = mock(SpanContext.class); 26 | 27 | // default mock behaviors 28 | when(spanBuilderMock.start()).thenReturn(newSpanMock); 29 | when(parentSpanMock.context()).thenReturn(parentSpanContextMock); 30 | } 31 | 32 | @Test 33 | public void subspan_ignoreActiveSpan() { 34 | final SpanR spanR = (SpanR) new SpanBuilderR(spanBuilderMock, reporterMock, "some-operation", scopeManagerMock) 35 | .ignoreActiveSpan().start(); 36 | 37 | // verify 38 | assertTrue(spanR.references.isEmpty()); 39 | verify(spanBuilderMock).start(); 40 | verify(scopeManagerMock, never()).activeSpan(); 41 | } 42 | 43 | @Test 44 | public void subspan_explicitAsChildOf() { 45 | final String spanId = "some-span-id-" + System.currentTimeMillis(); 46 | final Map parentBaggage = new HashMap<>(); 47 | parentBaggage.put(SpanBuilderR.BAGGAGE_SPANID_KEY, spanId); 48 | 49 | // setup mocks 50 | when(parentSpanContextMock.baggageItems()).thenReturn(parentBaggage.entrySet()); 51 | 52 | final SpanR spanR = (SpanR) new SpanBuilderR(spanBuilderMock, reporterMock, "some-operation", scopeManagerMock).asChildOf(parentSpanMock).start(); 53 | 54 | // verify 55 | assertFalse(spanR.references.isEmpty()); 56 | verify(scopeManagerMock, never()).activeSpan(); 57 | verify(spanBuilderMock).start(); 58 | verify(parentSpanMock).context(); 59 | verify(parentSpanContextMock, atLeastOnce()).baggageItems(); 60 | assertEquals(spanId, spanR.references.get(CHILD_OF)); 61 | } 62 | 63 | @Test 64 | public void subspan_implicitAsChildOf() { 65 | final String spanId = "some-span-id-" + System.currentTimeMillis(); 66 | final Map parentBaggage = new HashMap<>(); 67 | parentBaggage.put(SpanBuilderR.BAGGAGE_SPANID_KEY, spanId); 68 | 69 | // setup mocks 70 | when(scopeManagerMock.activeSpan()).thenReturn(parentSpanMock); 71 | when(parentSpanContextMock.baggageItems()).thenReturn(parentBaggage.entrySet()); 72 | 73 | final SpanR spanR = (SpanR) new SpanBuilderR(spanBuilderMock, reporterMock, "some-operation", scopeManagerMock).start(); 74 | 75 | // verify 76 | assertFalse(spanR.references.isEmpty()); 77 | verify(scopeManagerMock, atLeastOnce()).activeSpan(); 78 | verify(spanBuilderMock).start(); 79 | verify(parentSpanMock).context(); 80 | verify(parentSpanContextMock, atLeastOnce()).baggageItems(); 81 | assertEquals(spanId, spanR.references.get(CHILD_OF)); 82 | } 83 | 84 | private Reporter reporterMock; 85 | private Tracer.SpanBuilder spanBuilderMock; 86 | private ScopeManager scopeManagerMock; 87 | private Span newSpanMock; 88 | private Span parentSpanMock; 89 | private SpanContext parentSpanContextMock; 90 | } -------------------------------------------------------------------------------- /src/etc/header.txt: -------------------------------------------------------------------------------- 1 | Copyright ${license_year} ${license_owner} 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 4 | in compliance with the License. You may obtain a copy of the License at 5 | 6 | http://www.apache.org/licenses/LICENSE-2.0 7 | 8 | Unless required by applicable law or agreed to in writing, software distributed under the License 9 | is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 10 | or implied. See the License for the specific language governing permissions and limitations under 11 | the License. 12 | --------------------------------------------------------------------------------