|
| 1 | +--- |
| 2 | +title: Primeiros passos com exemplo |
| 3 | +description: Obtenha telemetria para sua aplicação em menos de 5 minutos! |
| 4 | +weight: 10 |
| 5 | +default_lang_commit: 0930994d5be6f01b05d0caca0550c468d2f3e829 |
| 6 | +--- |
| 7 | + |
| 8 | +<!-- markdownlint-disable blanks-around-fences --> |
| 9 | +<?code-excerpt path-base="examples/java/getting-started"?> |
| 10 | + |
| 11 | +Esta página mostrará como começar a utilizar o OpenTelemetry em Java. |
| 12 | + |
| 13 | +Você aprenderá como instrumentalizar automaticamente uma aplicação Java simples, |
| 14 | +de modo que [rastros][traces], [métricas][metrics], e [logs][] sejam emitidos |
| 15 | +para o console. |
| 16 | + |
| 17 | +## Pré-requisitos {#prerequisites} |
| 18 | + |
| 19 | +Certifique-se de ter instalado localmente: |
| 20 | + |
| 21 | +- Java JDK 17+ devido ao uso do Spring Boot 3; [Java 8+ para outros |
| 22 | + casos][java-vers] |
| 23 | +- [Gradle](https://gradle.org/) |
| 24 | + |
| 25 | +## Exemplo de Aplicação {#example-application} |
| 26 | + |
| 27 | +O exemplo a seguir utiliza uma aplicação básica [Spring Boot][]. Você pode usar |
| 28 | +outros frameworks web, como Apache Wicket ou Play. Para uma lista completa das |
| 29 | +bibliotecas e frameworks suportados, consulte o |
| 30 | +[registro](/ecosystem/registry/?component=instrumentation&language=java). |
| 31 | + |
| 32 | +Para exemplos mais elaborados, veja [exemplos](../examples/). |
| 33 | + |
| 34 | +### Dependências {#dependencies} |
| 35 | + |
| 36 | +Para começar, configure um ambiente em um novo diretório chamado `java-simple`. |
| 37 | +Dentro dele, crie um arquivo chamado `build.gradle.kts` e adicione o seguinte |
| 38 | +conteúdo ao arquivo: |
| 39 | + |
| 40 | +```kotlin |
| 41 | +plugins { |
| 42 | + id("java") |
| 43 | + id("org.springframework.boot") version "3.0.6" |
| 44 | + id("io.spring.dependency-management") version "1.1.0" |
| 45 | +} |
| 46 | + |
| 47 | +sourceSets { |
| 48 | + main { |
| 49 | + java.setSrcDirs(setOf(".")) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +repositories { |
| 54 | + mavenCentral() |
| 55 | +} |
| 56 | + |
| 57 | +dependencies { |
| 58 | + implementation("org.springframework.boot:spring-boot-starter-web") |
| 59 | +} |
| 60 | +``` |
| 61 | + |
| 62 | +### Criando e iniciando um servidor HTTP {#create-and-launch-an-http-server} |
| 63 | + |
| 64 | +No mesmo diretório, crie um arquivo chamado `DiceApplication.java` e adicione o |
| 65 | +seguinte código ao arquivo: |
| 66 | + |
| 67 | +<!-- prettier-ignore-start --> |
| 68 | +<?code-excerpt "src/main/java/otel/DiceApplication.java"?> |
| 69 | +```java |
| 70 | +package otel; |
| 71 | + |
| 72 | +import org.springframework.boot.Banner; |
| 73 | +import org.springframework.boot.SpringApplication; |
| 74 | +import org.springframework.boot.autoconfigure.SpringBootApplication; |
| 75 | + |
| 76 | +@SpringBootApplication |
| 77 | +public class DiceApplication { |
| 78 | + public static void main(String[] args) { |
| 79 | + SpringApplication app = new SpringApplication(DiceApplication.class); |
| 80 | + app.setBannerMode(Banner.Mode.OFF); |
| 81 | + app.run(args); |
| 82 | + } |
| 83 | +} |
| 84 | +``` |
| 85 | +<!-- prettier-ignore-end --> |
| 86 | + |
| 87 | +Crie outro arquivo chamado `RollController.java` e adicione o seguinte código ao |
| 88 | +arquivo: |
| 89 | + |
| 90 | +<!-- prettier-ignore-start --> |
| 91 | +<?code-excerpt "src/main/java/otel/RollController.java"?> |
| 92 | +```java |
| 93 | +package otel; |
| 94 | + |
| 95 | +import java.util.Optional; |
| 96 | +import java.util.concurrent.ThreadLocalRandom; |
| 97 | +import org.slf4j.Logger; |
| 98 | +import org.slf4j.LoggerFactory; |
| 99 | +import org.springframework.web.bind.annotation.GetMapping; |
| 100 | +import org.springframework.web.bind.annotation.RequestParam; |
| 101 | +import org.springframework.web.bind.annotation.RestController; |
| 102 | + |
| 103 | +@RestController |
| 104 | +public class RollController { |
| 105 | + private static final Logger logger = LoggerFactory.getLogger(RollController.class); |
| 106 | + |
| 107 | + @GetMapping("/rolldice") |
| 108 | + public String index(@RequestParam("player") Optional<String> player) { |
| 109 | + int result = this.getRandomNumber(1, 6); |
| 110 | + if (player.isPresent()) { |
| 111 | + logger.info("{} is rolling the dice: {}", player.get(), result); |
| 112 | + } else { |
| 113 | + logger.info("Anonymous player is rolling the dice: {}", result); |
| 114 | + } |
| 115 | + return Integer.toString(result); |
| 116 | + } |
| 117 | + |
| 118 | + public int getRandomNumber(int min, int max) { |
| 119 | + return ThreadLocalRandom.current().nextInt(min, max + 1); |
| 120 | + } |
| 121 | +} |
| 122 | +``` |
| 123 | +<!-- prettier-ignore-end --> |
| 124 | + |
| 125 | +Compile e execute a aplicação com o seguinte comando, e então abra |
| 126 | +<http://localhost:8080/rolldice> no seu navegador para ter certeza que está |
| 127 | +funcionando. |
| 128 | + |
| 129 | +```sh |
| 130 | +gradle assemble |
| 131 | +java -jar ./build/libs/java-simple.jar |
| 132 | +``` |
| 133 | + |
| 134 | +## Instrumentação {#instrumentation} |
| 135 | + |
| 136 | +Em seguida, você usará um [agente Java](/docs/zero-code/java/agent/) para |
| 137 | +instrumentalizar automaticamente a aplicação durante sua inicialização. Embora |
| 138 | +seja possível [configurar o agente Java][configure the java agent] de várias |
| 139 | +maneiras, os passos abaixo utilizam variáveis de ambiente. |
| 140 | + |
| 141 | +1. Faça o download do [opentelemetry-javaagent.jar][] na página de [releases][] |
| 142 | + do repositório `opentelemetry-java-instrumentation`. O arquivo JAR contém o |
| 143 | + agente e todos os pacotes de instrumentação automática: |
| 144 | + |
| 145 | + ```console |
| 146 | + curl -L -O https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/latest/download/opentelemetry-javaagent.jar |
| 147 | + ``` |
| 148 | + |
| 149 | + {{% alert color="info" %}}<i class="fas fa-edit"></i> Take note of the path |
| 150 | + to the JAR file.{{% /alert %}} |
| 151 | + |
| 152 | +2. Configure e exporte as variáveis que especificam o JAR do agente Java e um |
| 153 | + [exportador de console][console exporter], utilizando a notação adequada para |
| 154 | + seu ambiente — aqui demonstramos a notação para shells do tipo bash: |
| 155 | + |
| 156 | + ```sh |
| 157 | + export JAVA_TOOL_OPTIONS="-javaagent:PATH/TO/opentelemetry-javaagent.jar" \ |
| 158 | + OTEL_TRACES_EXPORTER=logging \ |
| 159 | + OTEL_METRICS_EXPORTER=logging \ |
| 160 | + OTEL_LOGS_EXPORTER=logging \ |
| 161 | + OTEL_METRIC_EXPORT_INTERVAL=15000 |
| 162 | + ``` |
| 163 | + |
| 164 | + {{% alert title="Important" color="warning" %}} |
| 165 | + - Replace `PATH/TO` above, with your path to the JAR. |
| 166 | + - Set `OTEL_METRIC_EXPORT_INTERVAL` to a value well below the default, as we |
| 167 | + illustrate above, **only during testing** to help you more quickly ensure |
| 168 | + that metrics are properly generated. |
| 169 | + |
| 170 | + {{% /alert %}} |
| 171 | + |
| 172 | +3. Execute a **aplicação** mais uma vez: |
| 173 | + |
| 174 | + ```console |
| 175 | + $ java -jar ./build/libs/java-simple.jar |
| 176 | + ... |
| 177 | + ``` |
| 178 | + |
| 179 | + Observe a saída do `otel.javaagent`. |
| 180 | + |
| 181 | +4. De _outro_ terminal, envie uma requisição utilizando `curl`: |
| 182 | + |
| 183 | + ```sh |
| 184 | + curl localhost:8080/rolldice |
| 185 | + ``` |
| 186 | + |
| 187 | +5. Pare o processo do servidor. |
| 188 | + |
| 189 | +No passo 4, você deve ter visto o rastro e log na saída do console do servidor e |
| 190 | +cliente que se parece com algo assim (a saída do rastro está quebrada em linhas |
| 191 | +para melhor visualização): |
| 192 | + |
| 193 | +```sh |
| 194 | +[otel.javaagent 2023-04-24 17:33:54:567 +0200] [http-nio-8080-exec-1] INFO |
| 195 | +io.opentelemetry.exporter.logging.LoggingSpanExporter - 'RollController.index' : |
| 196 | + 70c2f04ec863a956e9af975ba0d983ee 7fd145f5cda13625 INTERNAL [tracer: |
| 197 | + io.opentelemetry.spring-webmvc-6.0:1.25.0-alpha] AttributesMap{data= |
| 198 | + {thread.id=39, thread.name=http-nio-8080-exec-1}, capacity=128, |
| 199 | + totalAddedValues=2} |
| 200 | +[otel.javaagent 2023-04-24 17:33:54:568 +0200] [http-nio-8080-exec-1] INFO |
| 201 | +io.opentelemetry.exporter.logging.LoggingSpanExporter - 'GET /rolldice' : |
| 202 | +70c2f04ec863a956e9af975ba0d983ee 647ad186ad53eccf SERVER [tracer: |
| 203 | +io.opentelemetry.tomcat-10.0:1.25.0-alpha] AttributesMap{ |
| 204 | + data={user_agent.original=curl/7.87.0, net.host.name=localhost, |
| 205 | + net.transport=ip_tcp, http.target=/rolldice, net.sock.peer.addr=127.0.0.1, |
| 206 | + thread.name=http-nio-8080-exec-1, net.sock.peer.port=53422, |
| 207 | + http.route=/rolldice, net.sock.host.addr=127.0.0.1, thread.id=39, |
| 208 | + net.protocol.name=http, http.status_code=200, http.scheme=http, |
| 209 | + net.protocol.version=1.1, http.response_content_length=1, |
| 210 | + net.host.port=8080, http.method=GET}, capacity=128, totalAddedValues=17} |
| 211 | +``` |
| 212 | + |
| 213 | +No passo 5, ao parar o servidor, você verá uma saída com todas as métricas |
| 214 | +coletadas (a saída das métricas está quebrada em linhas e resumida para melhor |
| 215 | +visualização): |
| 216 | + |
| 217 | +```sh |
| 218 | +[otel.javaagent 2023-04-24 17:34:25:347 +0200] [PeriodicMetricReader-1] INFO |
| 219 | +io.opentelemetry.exporter.logging.LoggingMetricExporter - Received a collection |
| 220 | + of 19 metrics for export. |
| 221 | +[otel.javaagent 2023-04-24 17:34:25:347 +0200] [PeriodicMetricReader-1] INFO |
| 222 | +io.opentelemetry.exporter.logging.LoggingMetricExporter - metric: |
| 223 | +ImmutableMetricData{resource=Resource{schemaUrl= |
| 224 | +https://opentelemetry.io/schemas/1.19.0, attributes={host.arch="aarch64", |
| 225 | +host.name="OPENTELEMETRY", os.description="Mac OS X 13.3.1", os.type="darwin", |
| 226 | +process.command_args=[/bin/java, -jar, java-simple.jar], |
| 227 | +process.executable.path="/bin/java", process.pid=64497, |
| 228 | +process.runtime.description="Homebrew OpenJDK 64-Bit Server VM 20", |
| 229 | +process.runtime.name="OpenJDK Runtime Environment", |
| 230 | +process.runtime.version="20", service.name="java-simple", |
| 231 | +telemetry.auto.version="1.25.0", telemetry.sdk.language="java", |
| 232 | +telemetry.sdk.name="opentelemetry", telemetry.sdk.version="1.25.0"}}, |
| 233 | +instrumentationScopeInfo=InstrumentationScopeInfo{name=io.opentelemetry.runtime-metrics, |
| 234 | +version=1.25.0, schemaUrl=null, attributes={}}, |
| 235 | +name=process.runtime.jvm.buffer.limit, description=Total capacity of the buffers |
| 236 | +in this pool, unit=By, type=LONG_SUM, data=ImmutableSumData{points= |
| 237 | +[ImmutableLongPointData{startEpochNanos=1682350405319221000, |
| 238 | +epochNanos=1682350465326752000, attributes= |
| 239 | +{pool="mapped - 'non-volatile memory'"}, value=0, exemplars=[]}, |
| 240 | +ImmutableLongPointData{startEpochNanos=1682350405319221000, |
| 241 | +epochNanos=1682350465326752000, attributes={pool="mapped"}, |
| 242 | +value=0, exemplars=[]}, |
| 243 | +ImmutableLongPointData{startEpochNanos=1682350405319221000, |
| 244 | +epochNanos=1682350465326752000, attributes={pool="direct"}, |
| 245 | +value=8192, exemplars=[]}], monotonic=false, aggregationTemporality=CUMULATIVE}} |
| 246 | +... |
| 247 | +``` |
| 248 | + |
| 249 | +## O que vem depois? {#what-next} |
| 250 | + |
| 251 | +Para mais: |
| 252 | + |
| 253 | +- Execute este exemplo com outro [exportador][exporter] para dados de |
| 254 | + telemetria. |
| 255 | +- Experimente a [instrumentação sem código](/docs/zero-code/java/agent/) em uma |
| 256 | + de suas próprias aplicações. |
| 257 | +- Para telemetria levemente personalizada, experimente [anotações][annotations]. |
| 258 | +- Aprenda sobre [instrumentação manual][manual instrumentation] e experimente |
| 259 | + mais [exemplos](../examples/). |
| 260 | +- Dê uma olhada no [OpenTelemetry Demo](/docs/demo/), que inclui o |
| 261 | + [Serviço de Anúncios](/docs/demo/services/ad/) baseado em Java e o |
| 262 | + [Serviço de Detecção de Fraude](/docs/demo/services/fraud-detection/) baseado |
| 263 | + em Kotlin |
| 264 | + |
| 265 | +[traces]: /docs/concepts/signals/traces/ |
| 266 | +[metrics]: /docs/concepts/signals/metrics/ |
| 267 | +[logs]: /docs/concepts/signals/logs/ |
| 268 | +[annotations]: /docs/zero-code/java/agent/annotations/ |
| 269 | +[configure the java agent]: /docs/zero-code/java/agent/configuration/ |
| 270 | +[console exporter]: /docs/languages/java/configuration/#properties-exporters |
| 271 | +[exporter]: /docs/languages/java/configuration/#properties-exporters |
| 272 | +[java-vers]: |
| 273 | + https://github.com/open-telemetry/opentelemetry-java/blob/main/VERSIONING.md#language-version-compatibility |
| 274 | +[manual instrumentation]: ../instrumentation |
| 275 | +[opentelemetry-javaagent.jar]: |
| 276 | + https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases/latest/download/opentelemetry-javaagent.jar |
| 277 | +[releases]: |
| 278 | + https://github.com/open-telemetry/opentelemetry-java-instrumentation/releases |
| 279 | +[Spring Boot]: https://spring.io/guides/gs/spring-boot/ |
0 commit comments