O OpenTelemetry Collector fica no centro da arquitetura OpenTelemetry, mas não está relacionado ao contexto de rastreamento do W3C. Na minha , uso Jaeger em vez do Collector. No entanto, é onipresente, como em todas as postagens relacionadas ao OpenTelemetry. Eu queria explorá-lo ainda mais. demonstração de rastreamento Neste post, exploro os diferentes aspectos do Colecionador: O tipo de dados: logs, métricas e rastreamentos Modelos push e pull Operações: leituras, transformações e gravações Primeiros passos Há muito tempo, como a conhecemos não existia; o que tínhamos era . Naquela época, o monitoramento era um monte de gente olhando para telas que exibiam painéis. Os próprios painéis consistiam em métricas e apenas métricas do sistema: principalmente CPU, memória e uso de disco. Por esse motivo, começaremos com métricas. a observabilidade monitoramento é uma das principais soluções de monitoramento. Ele funciona em um modelo baseado em pull: o Prometheus coleta endpoints compatíveis de seus aplicativos e os armazena internamente. Prometheus Usaremos o OTEL Collector para extrair um endpoint compatível com Prometheus e imprimir o resultado no console. Grafana Labs oferece um que gera métricas aleatórias para brincar. Para simplificar, usarei o Docker Compose; a configuração é semelhante a esta: projeto version: "3" services: fake-metrics: build: ./fake-metrics-generator #1 collector: image: otel/opentelemetry-collector:0.87.0 #2 environment: #3 - METRICS_HOST=fake-metrics - METRICS_PORT=5000 volumes: - ./config/collector/config.yml:/etc/otelcol/config.yaml:ro #4 Nenhuma imagem Docker está disponível para o projeto de métricas falsas; portanto, precisamos construí-lo Versão mais recente do OTEL Collector no momento da redação deste artigo Parametrize o seguinte arquivo de configuração Tudo acontece aqui Como mencionei acima, o OTEL Collector pode fazer muito. Portanto, configuração é tudo. receivers: #1 prometheus: #2 config: scrape_configs: #3 - job_name: fake-metrics #4 scrape_interval: 3s static_configs: - targets: [ "${env:METRICS_HOST}:${env:METRICS_PORT}" ] exporters: #5 logging: #6 loglevel: debug service: pipelines: #7 metrics: #8 receivers: [ "prometheus" ] #9 exporters: [ "logging" ] #9 Lista de receptores. Um receptor lê dados; pode ser baseado em push ou pull. Usamos o receptor predefinido prometheus Definir trabalhos pull Configuração do trabalho Lista de exportadores. Ao contrário dos receptores, um exportador grava dados. O exportador mais simples é gravar dados na saída padrão Dutos montam receptores e exportadores Definir um pipeline relacionado a métricas O pipeline obtém dados do receptor definido anteriormente e os envia para o exportador , , os imprime prometheus logging ou seja Aqui está uma amostra do resultado: 2023-11-11 08:28:54 otel-collector-collector-1 | StartTimestamp: 1970-01-01 00:00:00 +0000 UTC 2023-11-11 08:28:54 otel-collector-collector-1 | Timestamp: 2023-11-11 07:28:54.14 +0000 UTC 2023-11-11 08:28:54 otel-collector-collector-1 | Value: 83.090000 2023-11-11 08:28:54 otel-collector-collector-1 | NumberDataPoints #1 2023-11-11 08:28:54 otel-collector-collector-1 | Data point attributes: 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__embrace_world_class_systems: Str(concept) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__exploit_magnetic_applications: Str(concept) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__facilitate_wireless_architectures: Str(extranet) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__grow_magnetic_communities: Str(challenge) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__reinvent_revolutionary_applications: Str(support) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__strategize_strategic_initiatives: Str(internet_solution) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__target_customized_eyeballs: Str(concept) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__transform_turn_key_technologies: Str(framework) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__whiteboard_innovative_partnerships: Str(matrices) 2023-11-11 08:28:54 otel-collector-collector-1 | StartTimestamp: 1970-01-01 00:00:00 +0000 UTC 2023-11-11 08:28:54 otel-collector-collector-1 | Timestamp: 2023-11-11 07:28:54.14 +0000 UTC 2023-11-11 08:28:54 otel-collector-collector-1 | Value: 53.090000 2023-11-11 08:28:54 otel-collector-collector-1 | NumberDataPoints #2 2023-11-11 08:28:54 otel-collector-collector-1 | Data point attributes: 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__expedite_distributed_partnerships: Str(approach) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__facilitate_wireless_architectures: Str(graphical_user_interface) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__grow_magnetic_communities: Str(policy) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__reinvent_revolutionary_applications: Str(algorithm) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__transform_turn_key_technologies: Str(framework) 2023-11-11 08:28:54 otel-collector-collector-1 | StartTimestamp: 1970-01-01 00:00:00 +0000 UTC 2023-11-11 08:28:54 otel-collector-collector-1 | Timestamp: 2023-11-11 07:28:54.14 +0000 UTC 2023-11-11 08:28:54 otel-collector-collector-1 | Value: 16.440000 2023-11-11 08:28:54 otel-collector-collector-1 | NumberDataPoints #3 2023-11-11 08:28:54 otel-collector-collector-1 | Data point attributes: 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__exploit_magnetic_applications: Str(concept) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__grow_magnetic_communities: Str(graphical_user_interface) 2023-11-11 08:28:54 otel-collector-collector-1 | -> fake__target_customized_eyeballs: Str(extranet) Além da impressão O texto acima é um excelente primeiro passo, mas há mais do que imprimir no console. Exporemos as métricas a serem extraídas por uma instância regular do Prometheus; podemos adicionar um para visualizá-los. Embora possa parecer inútil, tenha paciência, pois é apenas um degrau. painel Grafana Para conseguir o que foi dito acima, alteramos apenas a configuração do Coletor OTEL: exporters: prometheus: #1 endpoint: ":${env:PROMETHEUS_PORT}" #2 service: pipelines: metrics: receivers: [ "prometheus" ] exporters: [ "prometheus" ] #3 Adicionar um exportador prometheus Expor um endpoint compatível com Prometheus Substitua a impressão pela exposição É isso. O OTEL Collector é muito flexível. Observe que o Coletor é multientrada e multisaída. Para imprimir dados e expô-los por meio do endpoint, nós os adicionamos ao pipeline: exporters: prometheus: #1 endpoint: ":${env:PROMETHEUS_PORT}" logging: #2 loglevel: debug service: pipelines: metrics: receivers: [ "prometheus" ] exporters: [ "prometheus", "logging" ] #3 Expor dados Imprimir dados O pipeline imprimirá dados e os exporá Com o exportador Prometheus configurado, podemos visualizar métricas no Grafana. Observe que os receptores e exportadores especificam seu tipo cada um deles deve ser único. Para cumprir o último requisito, podemos acrescentar um qualificador para distinguir entre eles, , e e ou seja prometheus/foo prometheus/bar. Processamento de dados intermediários Uma questão válida seria por que o OTEL Collector está colocado entre a fonte e o Prometheus, pois torna o design geral mais frágil. Nesta fase, podemos aproveitar o verdadeiro poder do OTEL Collector: processamento de dados. Até agora, ingerimos métricas brutas, mas o formato de origem pode não ser adaptado à forma como queremos visualizar os dados. Por exemplo, em nossa configuração, as métricas vêm de nosso gerador falso, “negócios”, e da plataforma NodeJS subjacente, “técnica”. Isso se reflete no nome das métricas. Poderíamos adicionar um rótulo de origem dedicado e remover o prefixo desnecessário para filtrar com mais eficiência. Você declara os processadores de dados na seção do arquivo de configuração. O coletor os executa na ordem em que são declarados. Vamos implementar a transformação acima. processors O primeiro passo em direção ao nosso objetivo é entender que o colecionador tem dois sabores: um “nu” e um contributivo que se baseia nele. Os processadores incluídos no primeiro são limitados, tanto em número como em capacidades; portanto, precisamos mudar a versão do contrib. collector: image: otel/opentelemetry-collector-contrib:0.87.0 #1 environment: - METRICS_HOST=fake-metrics - METRICS_PORT=5000 - PROMETHEUS_PORT=8889 volumes: - ./config/collector/config.yml:/etc/otelcol-contrib/config.yaml:ro #2 Use o sabor contrib Para maior diversão, o arquivo de configuração está em outro caminho Neste ponto, podemos adicionar o próprio processador: processors: metricstransform: #1 transforms: #2 - include: ^fake_(.*)$ #3 match_type: regexp #3 action: update operations: #4 - action: add_label #5 new_label: origin new_value: fake - include: ^fake_(.*)$ match_type: regexp action: update #6 new_name: $${1} #6-7 # Do the same with metrics generated by NodeJS Invocar o processador de transformação de métricas Lista de transformações aplicadas em ordem Corresponde todas as métricas com o regexp definido Lista de operações aplicadas em ordem Adicione o rótulo Renomeie a métrica removendo o prefixo do grupo regexp Coisas divertidas: a sintaxe é $${x} Finalmente, adicionamos o processador definido ao pipeline: service: pipelines: metrics: receivers: [ "prometheus" ] processors: [ "metricstransform" ] exporters: [ "prometheus" ] Aqui estão os resultados: Conectando receptores e exportadores Um conector é receptor exportador e conecta dois pipelines. O exemplo da documentação recebe o número de spans (rastreamento) e exporta a contagem, que possui uma métrica. Tentei fazer o mesmo com 500 erros - spoiler: não funciona como esperado. e Vamos primeiro adicionar um receptor de log: receivers: filelog: include: [ "/var/logs/generated.log" ] Em seguida, adicionamos um conector: connectors: count: requests.errors: description: Number of 500 errors condition: [ "status == 500 " ] Por último, conectamos o receptor de log e o exportador de métricas: service: pipelines: logs: receivers: [ "filelog" ] exporters: [ "count" ] metrics: receivers: [ "prometheus", "count" ] A métrica é denominada , mas seu valor permanece em 1. log_record_count_total Manipulação de registros Os processadores permitem a manipulação de dados; operadores são processadores especializados que trabalham em logs. Se você estiver familiarizado com a pilha Elasticsearch Logstash Kibana, eles são equivalentes ao Logstash. A partir de agora, o carimbo de data/hora do log é o carimbo de data/hora de ingestão. Vamos alterá-lo para o carimbo de data/hora de sua criação. receivers: filelog: include: [ "/var/logs/generated.log" ] operators: - type: json_parser #1 timestamp: #2 parse_from: attributes.datetime #3 layout: "%d/%b/%Y:%H:%M:%S %z" #4 severity: #2 parse_from: attributes.status #3 mapping: #5 error: 5xx #6 warn: 4xx info: 3xx debug: 2xx - id: remove_body #7 type: remove field: body - id: remove_datetime #7 type: remove field: attributes.datetime - id: remove_status #7 type: remove field: attributes.status O log está no formato JSON; podemos usar o analisador JSON fornecido Atributos de metadados a serem definidos Campos para leitura Padrão de análise Tabela de mapeamento Aceite um intervalo, , . O operador possui um valor interpretado especial (e semelhante) para status HTTP. por exemplo 501-599 5xx Remover dados duplicados Histórico Neste ponto, podemos enviar os logs para qualquer componente de agregação de logs. Ficaremos na esfera do Grafana Labs e usaremos Loki. exporters: loki: endpoint: "http://loki:3100/loki/api/v1/push" Também podemos usar logs do próprio coletor: service: telemetry: logs: Finalmente, vamos adicionar outro pipeline: service: pipelines: logs: receivers: [ "filelog" ] exporters: [ "loki" ] Grafana também pode visualizar os logs. Escolha Loki como fonte de dados. Conclusão Neste post, nos aprofundamos no coletor OpenTelemetry. Embora não seja uma parte obrigatória da arquitetura OTEL, é um canivete suíço útil para todas as suas necessidades de processamento de dados. Caso você não esteja preso a uma pilha específica ou não queira, é uma ajuda tremenda. O código-fonte completo desta postagem pode ser encontrado no . GitHub Ir adiante: Coletor OpenTelemetry Operadores OpenTelemetry originalmente em em 12 de novembro de 2023 Publicado A Java Geek