5

Кто-нибудь знает, как интегрировать метрики Spring boot с datadog?Пункты весенней загрузки + datadog

Datadog - это служба мониторинга облачности для ИТ.

Это позволяет пользователям легко визуализировать свои данные, используя множество диаграмм и графиков.

У меня есть приложение для загрузки весны, которое использует dropwizard метрики для заполнения большого количества информации обо всех методах, которые я аннотировал с помощью @Timed.

С другой стороны, я развертываю свое приложение в heroku, поэтому я не могу установить агент Datadog.

Я хочу знать, есть ли способ автоматически интегрировать отчетность о метрической системе весны с помощью datadog.

ответ

8

Я наконец-то нашел dropwizzard модуль, который интегрирует эту библиотеку с datadog: metrics-datadog

Я создал класс конфигурации Spring, который создает и инициализирует этот репортер используя свойства моего YAML.

Просто вставьте эту зависимость в вашем ПОМ:

<!-- Send metrics to Datadog --> 
    <dependency> 
     <groupId>org.coursera</groupId> 
     <artifactId>dropwizard-metrics-datadog</artifactId> 
     <version>1.1.3</version> 
    </dependency> 

Добавить эту конфигурацию в вашей YAML:

yourapp: 
    metrics: 
    apiKey: <your API key> 
    host: <your host> 
    period: 10 
    enabled: true 

и добавить этот класс конфигурации вашего проекта:

/** 
* This bean will create and configure a DatadogReporter that will be in charge of sending 
* all the metrics collected by Spring Boot actuator system to Datadog. 
*  
* @see https://www.datadoghq.com/ 
* @author jfcorugedo 
* 
*/ 
@Configuration 
@ConfigurationProperties("yourapp.metrics") 
public class DatadogReporterConfig { 

    private static final Logger LOGGER = LoggerFactory.getLogger(DatadogReporterConfig.class); 

    /** Datadog API key used to authenticate every request to Datadog API */ 
    private String apiKey; 

    /** Logical name associated to all the events send by this application */ 
    private String host; 

    /** Time, in seconds, between every call to Datadog API. The lower this value the more information will be send to Datadog */ 
    private long period; 

    /** This flag enables or disables the datadog reporter */ 
    private boolean enabled = false; 

    @Bean 
    @Autowired 
    public DatadogReporter datadogReporter(MetricRegistry registry) { 

     DatadogReporter reporter = null; 
     if(enabled) { 
      reporter = enableDatadogMetrics(registry); 
     } else { 
      if(LOGGER.isWarnEnabled()) { 
       LOGGER.info("Datadog reporter is disabled. To turn on this feature just set 'rJavaServer.metrics.enabled:true' in your config file (property or YAML)"); 
      } 
     } 

     return reporter; 
    } 

    private DatadogReporter enableDatadogMetrics(MetricRegistry registry) { 

     if(LOGGER.isInfoEnabled()) { 
      LOGGER.info("Initializing Datadog reporter using [ host: {}, period(seconds):{}, api-key:{} ]", getHost(), getPeriod(), getApiKey()); 
     } 

     EnumSet<Expansion> expansions = DatadogReporter.Expansion.ALL; 
     HttpTransport httpTransport = new HttpTransport 
           .Builder() 
           .withApiKey(getApiKey()) 
           .build(); 

     DatadogReporter reporter = DatadogReporter.forRegistry(registry) 
     .withHost(getHost()) 
     .withTransport(httpTransport) 
     .withExpansions(expansions) 
     .build(); 

     reporter.start(getPeriod(), TimeUnit.SECONDS); 

     if(LOGGER.isInfoEnabled()) { 
      LOGGER.info("Datadog reporter successfully initialized"); 
     } 

     return reporter; 
    } 

    /** 
    * @return Datadog API key used to authenticate every request to Datadog API 
    */ 
    public String getApiKey() { 
     return apiKey; 
    } 

    /** 
    * @param apiKey Datadog API key used to authenticate every request to Datadog API 
    */ 
    public void setApiKey(String apiKey) { 
     this.apiKey = apiKey; 
    } 

    /** 
    * @return Logical name associated to all the events send by this application 
    */ 
    public String getHost() { 
     return host; 
    } 

    /** 
    * @param host Logical name associated to all the events send by this application 
    */ 
    public void setHost(String host) { 
     this.host = host; 
    } 

    /** 
    * @return Time, in seconds, between every call to Datadog API. The lower this value the more information will be send to Datadog 
    */ 
    public long getPeriod() { 
     return period; 
    } 

    /** 
    * @param period Time, in seconds, between every call to Datadog API. The lower this value the more information will be send to Datadog 
    */ 
    public void setPeriod(long period) { 
     this.period = period; 
    } 

    /** 
    * @return true if DatadogReporter is enabled in this application 
    */ 
    public boolean isEnabled() { 
     return enabled; 
    } 

    /** 
    * This flag enables or disables the datadog reporter. 
    * This flag is only read during initialization, subsequent changes on this value will no take effect 
    * @param enabled 
    */ 
    public void setEnabled(boolean enabled) { 
     this.enabled = enabled; 
    } 
} 
+1

Также можно использовать одну и ту же библиотеку для отчетов StatsD, а не HTTP, если кто-нибудь заинтересован в этой опции. –

+0

Вам нужно написать планировщик, потому что добавление заданных ресурсов для меня не работает. – Shek

2

If JMX - это вариант для вас, вы можете использовать JMX dropwizrd reporter в сочетании с java datalog integration

+0

Это хороший момент. Однако я развертываю свое приложение в heroku, поэтому я не могу установить агент datadog в ОС – jfcorugedo

+1

@jfcorugedo. Я не думаю, что в вопросе упоминалось что-нибудь о героику? Если требуется решение heroku, вам нужно добавить его в вопрос. – eis

+0

Да, извините, что вы правы – jfcorugedo

Смежные вопросы