001package io.prometheus.client.examples.guice;
002
003import com.google.inject.AbstractModule;
004import com.google.inject.Provider;
005import com.google.inject.Provides;
006import com.google.inject.Singleton;
007import com.google.inject.multibindings.Multibinder;
008import com.google.inject.name.Named;
009import com.google.inject.name.Names;
010import io.prometheus.client.Prometheus;
011import io.prometheus.client.metrics.Counter;
012import io.prometheus.client.metrics.Summary;
013import org.eclipse.jetty.server.Server;
014
015public class Module extends AbstractModule {
016  private static final Counter.Builder COUNTER_PROTOTYPE = Counter.newBuilder()
017      .namespace("guice_example");
018  private static final Summary.Builder SUMMARY_PROTOTYPE = Summary.newBuilder()
019      .namespace("guice_example");
020
021  @Override
022  protected void configure() {
023    bind(Integer.class)
024        .annotatedWith(Names.named("port"))
025        .toInstance(8080);
026    bind(Counter.class)
027        .annotatedWith(Names.named("handler"))
028        .toProvider(HandlerCounterProvider.class)
029        .in(Singleton.class);
030    bind(Summary.class)
031        .annotatedWith(Names.named("handler"))
032        .toProvider(HandlerLatencyProvider.class)
033        .in(Singleton.class);
034
035    final Multibinder<Prometheus.ExpositionHook> hooks = Multibinder.newSetBinder(binder(),
036        Prometheus.ExpositionHook.class);
037  }
038
039  @Provides
040  @Singleton
041  public Server getServer(final @Named("port") Integer port) {
042    return new Server(port);
043  }
044
045  public static class HandlerCounterProvider implements Provider<Counter> {
046    @Override
047    public Counter get() {
048      // N.B.: Static registration!
049      return COUNTER_PROTOTYPE
050          .subsystem("http")
051          .name("requests_total")
052          .labelNames("handler")
053          .labelNames("result")
054          .documentation("The total number of requests served.")
055          .build();
056    }
057  }
058
059  public static class HandlerLatencyProvider implements Provider<Summary> {
060    @Override
061    public Summary get() {
062      // N.B.: Static registration!
063      return SUMMARY_PROTOTYPE
064          .subsystem("http")
065          .name("latency_ms")
066          .labelNames("handler")
067          .labelNames("result")
068          .documentation("The latencies of the requests served.")
069          .build();
070    }
071  }
072}