com.netflix.spectator.api.Spectator Java Examples

The following examples show how to use com.netflix.spectator.api.Spectator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpectatorAppenderTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void properties() {
  Spectator.globalRegistry().add(registry);

  Properties props = new Properties();
  props.setProperty("log4j.rootLogger", "ALL, A1");
  props.setProperty("log4j.appender.A1", "com.netflix.spectator.log4j.SpectatorAppender");
  PropertyConfigurator.configure(props);

  Counter c = registry.counter("log4j.numStackTraces",
      "loglevel", "5_DEBUG",
      "exception", "IllegalArgumentException",
      "file", "SpectatorAppenderTest.java");
  Assertions.assertEquals(0, c.count());
  Exception e = new IllegalArgumentException("foo");
  e.fillInStackTrace();
  Logger.getLogger(getClass()).debug("foo", e);

  Assertions.assertEquals(1, c.count());
}
 
Example #2
Source File: GuiceServletFilterTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Override
protected Injector getInjector() {
  return Guice.createInjector(
      new AbstractModule() {
        @Override
        protected void configure() {
          bind(Registry.class).toInstance(Spectator.globalRegistry());
        }
      },
      new ServletModule() {
        @Override
        protected void configureServlets() {
          serve("/test/foo/*").with(TestServlet.class);
          serve("/api/*").with(TestServlet.class);
          serve("/*").with(TestServlet.class);
          filter("/*").through(IpcServletFilter.class);
        }
      }
  );
}
 
Example #3
Source File: GcLogger.java    From spectator with Apache License 2.0 6 votes vote down vote up
private void processGcEvent(GarbageCollectionNotificationInfo info) {
  GcEvent event = new GcEvent(info, jvmStartTime + info.getGcInfo().getStartTime());
  gcLogs.get(info.getGcName()).add(event);
  if (LOGGER.isDebugEnabled()) {
    LOGGER.debug(event.toString());
  }

  // Update pause timer for the action and cause...
  Id eventId = (isConcurrentPhase(info) ? CONCURRENT_PHASE_TIME : PAUSE_TIME)
    .withTag("action", info.getGcAction())
    .withTag("cause", info.getGcCause());
  Timer timer = Spectator.globalRegistry().timer(eventId);
  timer.record(info.getGcInfo().getDuration(), TimeUnit.MILLISECONDS);

  // Update promotion and allocation counters
  updateMetrics(info.getGcName(), info.getGcInfo());

  // Notify an event listener if registered
  if (eventListener != null) {
    try {
      eventListener.onComplete(event);
    } catch (Exception e) {
      LOGGER.warn("exception thrown by event listener", e);
    }
  }
}
 
Example #4
Source File: PercentileTimerTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void expirationGlobalRegistry() {
  ManualClock clock = new ManualClock();
  ExpiringRegistry r = new ExpiringRegistry(clock);
  Spectator.globalRegistry().removeAll();
  Spectator.globalRegistry().add(r);
  PercentileTimer t = PercentileTimer.builder(Spectator.globalRegistry())
      .withName("test")
      .build();

  Assertions.assertFalse(t.hasExpired());
  t.record(5, TimeUnit.SECONDS);
  Assertions.assertEquals(1, r.timer("test").count());

  clock.setWallTime(1);
  Assertions.assertTrue(t.hasExpired());
  r.removeExpiredMeters();
  Assertions.assertNull(r.state().get(t.id()));

  t.record(5, TimeUnit.SECONDS);
  Assertions.assertFalse(t.hasExpired());
  Assertions.assertEquals(1, r.timer("test").count());
}
 
Example #5
Source File: SpectatorAppender.java    From spectator with Apache License 2.0 6 votes vote down vote up
/** Create a new instance of the appender using the global spectator registry. */
@PluginFactory
public static SpectatorAppender createAppender(
    @PluginAttribute("name") String name,
    @PluginAttribute("ignoreExceptions") boolean ignoreExceptions,
    @PluginElement("Layout") Layout<? extends Serializable> layout,
    @PluginElement("Filters") Filter filter) {

  if (name == null) {
    LOGGER.error("no name provided for SpectatorAppender");
    return null;
  }

  return new SpectatorAppender(
      Spectator.globalRegistry(),
      name, filter, layout, ignoreExceptions,
      Property.EMPTY_ARRAY);
}
 
Example #6
Source File: SparkSink.java    From spectator with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new instance. Spark looks for a constructor with all three parameters, so the
 * {@code SecurityManager} needs to be in the signature even though it isn't used.
 */
@SuppressWarnings("PMD.UnusedFormalParameter")
public SparkSink(
    Properties properties,
    MetricRegistry registry,
    org.apache.spark.SecurityManager manager) throws MalformedURLException {
  final Config config = loadConfig();
  statelessRegistry = new StatelessRegistry(
      Clock.SYSTEM, new SpectatorConfig(config.getConfig("spectator.spark.stateless")));
  reporter = SpectatorReporter.forRegistry(registry)
      .withSpectatorRegistry(statelessRegistry)
      .withNameFunction(SparkNameFunction.fromConfig(config, statelessRegistry))
      .withValueFunction(SparkValueFunction.fromConfig(config))
      .withGaugeCounters(Pattern.compile(config.getString("spectator.spark.gauge-counters")))
      .build();
  pollPeriod = getPeriod(properties);
  pollUnit = getUnit(properties);

  // If there is a need to collect application metrics from jobs running on Spark, then
  // this should be enabled. The apps can report to the global registry and it will get
  // picked up by the Spark integration.
  if (shouldAddToGlobal(properties)) {
    Spectator.globalRegistry().add(statelessRegistry);
  }
}
 
Example #7
Source File: SpectatorModule.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Override protected void configure() {
  // Servo is all based on static classes. The context for servo needs to be set as early
  // as possible to avoid missing metrics because the context has not yet been set.
  SpectatorContext.setRegistry(Spectator.globalRegistry());
  bind(Plugin.class).asEagerSingleton();
  bind(StaticManager.class).asEagerSingleton();
  bind(Config.class)
      .annotatedWith(Names.named("spectator"))
      .toProvider(ConfigProvider.class);
  bind(AtlasConfig.class).to(AtlasConfiguration.class);
  OptionalBinder.newOptionalBinder(binder(), ExtendedRegistry.class)
      .setDefault()
      .toInstance(Spectator.registry());
  OptionalBinder.newOptionalBinder(binder(), Clock.class)
      .setDefault()
      .toInstance(Clock.SYSTEM);
  OptionalBinder.newOptionalBinder(binder(), Registry.class)
      .setDefault()
      .to(AtlasRegistry.class)
      .in(Scopes.SINGLETON);
}
 
Example #8
Source File: SpectatorModuleTest.java    From spectator with Apache License 2.0 6 votes vote down vote up
@Test
public void injectedRegistryAddedToGlobal() {
  final ManualClock clock = new ManualClock();
  Injector injector = Guice.createInjector(
      new AbstractModule() {
        @Override protected void configure() {
          OptionalBinder.newOptionalBinder(binder(), Clock.class)
              .setBinding()
              .toInstance(clock);
        }
      },
      new SpectatorModule());
  Registry registry = injector.getInstance(Registry.class);
  Spectator.globalRegistry().counter("test").increment();
  clock.setWallTime(5000);
  Assertions.assertEquals(1, registry.counter("test").count());
}
 
Example #9
Source File: TestModuleTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@Test
public void usableIfSpectatorModuleIsInstalled() {
  Registry r = Guice
      .createInjector(new SpectatorModule(), new TestModule())
      .getInstance(Registry.class);
  Assertions.assertTrue(r instanceof DefaultRegistry); // SpectatorModule installs ServoRegistry

  // Sanity checking global behavior, SpectatorModule will add it to the global
  // registry which is not normally done for TestModule because it is all static.
  Assertions.assertSame(Spectator.globalRegistry().underlying(DefaultRegistry.class), r);
}
 
Example #10
Source File: EVCacheMetricsFactory.java    From EVCache with Apache License 2.0 5 votes vote down vote up
public DistributionSummary getDistributionSummary(String name, Collection<Tag> tags) {
    final String metricName = (tags != null ) ? name + tags.toString() : name;
    final DistributionSummary _ds = distributionSummaryMap.get(metricName);
    if(_ds != null) return _ds;
    final Registry registry = Spectator.globalRegistry(); 
    if (registry != null) {
        Id id = getId(name, tags);
        final DistributionSummary ds = registry.distributionSummary(id);
        distributionSummaryMap.put(metricName, ds);
        return ds;
    }
    return null;
}
 
Example #11
Source File: ServoRegistryTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
public void globalIterator(Function<Registry, Meter> createMeter) {
  Registry dflt = Servo.newRegistry();
  CompositeRegistry global = Spectator.globalRegistry();
  global.removeAll();
  global.add(dflt);

  boolean found = false;
  Id expected = createMeter.apply(dflt).id();
  for (Meter m : global) {
    found |= m.id().equals(expected);
  }
  Assertions.assertTrue(found, "id for sub-registry could not be found in global iterator");
}
 
Example #12
Source File: GuiceServletFilterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void before() {
  registry = new DefaultRegistry();
  client = HttpClient.create(new IpcLogger(registry));
  Spectator.globalRegistry().removeAll();
  Spectator.globalRegistry().add(registry);
}
 
Example #13
Source File: IpcServletFilterTest.java    From spectator with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void before() {
  registry = new DefaultRegistry();
  client = HttpClient.create(new IpcLogger(registry));
  Spectator.globalRegistry().removeAll();
  Spectator.globalRegistry().add(registry);
}
 
Example #14
Source File: SpectatorRegistryFactory.java    From mantis with Apache License 2.0 5 votes vote down vote up
public static Registry getRegistry() {
    if (registryRef.get() == null) {
        return Spectator.globalRegistry();
    } else {
        return registryRef.get();
    }
}
 
Example #15
Source File: SpectatorConfiguration.java    From kork with Apache License 2.0 5 votes vote down vote up
public RegistryInitializer(Registry registry, boolean enableJmxLogging) {
  this.registry = registry;
  Spectator.globalRegistry().add(registry);
  if (enableJmxLogging) {
    Jmx.registerStandardMXBeans(registry);
  }
  gcLogger = new GcLogger();
  gcLogger.start(null);
}
 
Example #16
Source File: SpectatorReporter.java    From spectator with Apache License 2.0 5 votes vote down vote up
/** Create a new instance of the reporter. */
public SpectatorReporter build() {
  if (spectatorRegistry == null) {
    spectatorRegistry = Spectator.globalRegistry();
  }
  return new SpectatorReporter(
      registry, spectatorRegistry, nameFunction, valueFunction, gaugeCounters);
}
 
Example #17
Source File: ErrorStatsData.java    From zuul with Apache License 2.0 5 votes vote down vote up
/**
 * create a counter by route and cause of error
 * @param route
 * @param cause
 */
public ErrorStatsData(String route, String cause) {
    if(null == route || "".equals(route)){
        route = "UNKNOWN";
    }
    id = route + "_" + cause;

    this.errorCause = cause;
    Registry registry = Spectator.globalRegistry();
    PolledMeter.using(registry)
            .withId(registry.createId("zuul.ErrorStatsData", "ID", id))
            .monitorValue(this, ErrorStatsData::getCount);
}
 
Example #18
Source File: BasicRequestMetricsPublisher.java    From zuul with Apache License 2.0 5 votes vote down vote up
private void recordRequestTiming(String name, long timeNs)
{
    long timeMs = timeNs / 1000000;
    if(timeMs > -1) {
        Spectator.globalRegistry().timer(name).record(timeMs, TimeUnit.MILLISECONDS);
    }
}
 
Example #19
Source File: NamedCountingMonitor.java    From zuul with Apache License 2.0 5 votes vote down vote up
public NamedCountingMonitor(String name) {
    this.name = name;
    Registry registry = Spectator.globalRegistry();
    PolledMeter.using(registry)
            .withId(registry.createId("zuul.ErrorStatsData", "ID", name))
            .monitorValue(this, NamedCountingMonitor::getCount);
}
 
Example #20
Source File: RouteStatusCodeMonitor.java    From zuul with Apache License 2.0 5 votes vote down vote up
public RouteStatusCodeMonitor(@Nullable String route, int statusCode) {
    if (route == null) {
        route = "";
    }
    this.route = route;
    this.statusCode = statusCode;
    this.routeCode = route + "_" + statusCode;
    Registry registry = Spectator.globalRegistry();
    PolledMeter.using(registry)
            .withId(registry.createId("zuul.RouteStatusCodeMonitor", "ID", routeCode))
            .monitorValue(this, RouteStatusCodeMonitor::getCount);
}
 
Example #21
Source File: SpectatorUtils.java    From zuul with Apache License 2.0 4 votes vote down vote up
public static Counter newCounter(String name, String id, String... tags) {
    String[] allTags = getTagsWithId(id, tags);
    return Spectator.globalRegistry().counter(name, allTags);
}
 
Example #22
Source File: CurrentPassport.java    From zuul with Apache License 2.0 4 votes vote down vote up
private static Counter createCounter(String name)
{
    return Spectator.globalRegistry().counter("zuul.passport." + name);
}
 
Example #23
Source File: SpectatorUtils.java    From zuul with Apache License 2.0 4 votes vote down vote up
public static Counter newCounter(String name, String id) {
    return Spectator.globalRegistry().counter(name, "id", id);
}
 
Example #24
Source File: Tracer.java    From zuul with Apache License 2.0 4 votes vote down vote up
@Override
public void stopAndLog() {
    Spectator.globalRegistry().timer(name, "hostname", getHostName(), "ip", getIp())
            .record(System.nanoTime() - start, TimeUnit.NANOSECONDS);
}
 
Example #25
Source File: SpectatorUtils.java    From zuul with Apache License 2.0 4 votes vote down vote up
public static <T extends Number> T newGauge(String name, String id, T number, String... tags) {
    final CompositeRegistry registry = Spectator.globalRegistry();
    Id gaugeId = registry.createId(name, getTagsWithId(id, tags));
    return registry.gauge(gaugeId, number);
}
 
Example #26
Source File: SpectatorUtils.java    From zuul with Apache License 2.0 4 votes vote down vote up
public static Timer newTimer(String name, String id) {
    return Spectator.registry().timer(name, "id", id);
}
 
Example #27
Source File: SpectatorUtils.java    From zuul with Apache License 2.0 4 votes vote down vote up
public static Timer newTimer(String name, String id, String... tags) {
    return Spectator.globalRegistry().timer(name, getTagsWithId(id, tags));
}
 
Example #28
Source File: BaseZuulChannelInitializer.java    From zuul with Apache License 2.0 4 votes vote down vote up
private BaseZuulChannelInitializer(
        int port,
        String metricId,
        ChannelConfig channelConfig,
        ChannelConfig channelDependencies,
        ChannelGroup channels) {
    this.port = port;
    checkNotNull(metricId, "metricId");
    this.channelConfig = channelConfig;
    this.channelDependencies = channelDependencies;
    this.channels = channels;

    this.accessLogPublisher = channelDependencies.get(ZuulDependencyKeys.accessLogPublisher);

    this.withProxyProtocol = channelConfig.get(CommonChannelConfigKeys.withProxyProtocol);

    this.idleTimeout = channelConfig.get(CommonChannelConfigKeys.idleTimeout);
    this.httpRequestReadTimeout = channelConfig.get(CommonChannelConfigKeys.httpRequestReadTimeout);
    this.channelMetrics = new ServerChannelMetrics("http-" + metricId, Spectator.globalRegistry());
    this.registry = channelDependencies.get(ZuulDependencyKeys.registry);
    this.httpMetricsHandler = new HttpMetricsChannelHandler(registry, "server", "http-" + metricId);

    EventLoopGroupMetrics eventLoopGroupMetrics = channelDependencies.get(ZuulDependencyKeys.eventLoopGroupMetrics);
    PerEventLoopMetricsChannelHandler perEventLoopMetricsHandler = new PerEventLoopMetricsChannelHandler(eventLoopGroupMetrics);
    this.perEventLoopConnectionMetricsHandler = perEventLoopMetricsHandler.new Connections();
    this.perEventLoopRequestsMetricsHandler = perEventLoopMetricsHandler.new HttpRequests();

    this.maxConnections = channelConfig.get(CommonChannelConfigKeys.maxConnections);
    this.maxConnectionsHandler = new MaxInboundConnectionsHandler(maxConnections);
    this.maxRequestsPerConnection = channelConfig.get(CommonChannelConfigKeys.maxRequestsPerConnection);
    this.maxRequestsPerConnectionInBrownout = channelConfig.get(CommonChannelConfigKeys.maxRequestsPerConnectionInBrownout);
    this.connectionExpiry = channelConfig.get(CommonChannelConfigKeys.connectionExpiry);
    this.connCloseDelay = channelConfig.get(CommonChannelConfigKeys.connCloseDelay);

    StripUntrustedProxyHeadersHandler.AllowWhen allowProxyHeadersWhen = channelConfig.get(CommonChannelConfigKeys.allowProxyHeadersWhen);
    this.stripInboundProxyHeadersHandler = new StripUntrustedProxyHeadersHandler(allowProxyHeadersWhen);

    this.rateLimitingChannelHandler = channelDependencies.get(ZuulDependencyKeys.rateLimitingChannelHandlerProvider).get();

    this.sslClientCertCheckChannelHandler = channelDependencies.get(ZuulDependencyKeys.sslClientCertCheckChannelHandlerProvider).get();

    this.passportLoggingHandler = new PassportLoggingHandler(registry);

    this.sessionContextDecorator = channelDependencies.get(ZuulDependencyKeys.sessionCtxDecorator);
    this.requestCompleteHandler = channelDependencies.get(ZuulDependencyKeys.requestCompleteHandler);
    this.httpRequestReadTimeoutCounter = channelDependencies.get(ZuulDependencyKeys.httpRequestReadTimeoutCounter);

    this.filterLoader = channelDependencies.get(ZuulDependencyKeys.filterLoader);
    this.filterUsageNotifier = channelDependencies.get(ZuulDependencyKeys.filterUsageNotifier);

    this.sourceAddressChannelHandler = new SourceAddressChannelHandler();
}
 
Example #29
Source File: ServerTest.java    From zuul with Apache License 2.0 4 votes vote down vote up
@Test
public void getListeningSockets() throws Exception {
    ServerStatusManager ssm = mock(ServerStatusManager.class);
    Map<SocketAddress, ChannelInitializer<?>> initializers = new HashMap<>();
    ChannelInitializer<Channel> init = new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) {}
    };
    initializers.put(new InetSocketAddress(0), init);
    // Pick an InetAddress likely different than the above.  The port to channel map has a unique Key; this
    // prevents the key being a duplicate.
    initializers.put(new InetSocketAddress(InetAddress.getLocalHost(), 0), init);
    ClientConnectionsShutdown ccs =
            new ClientConnectionsShutdown(
                    new DefaultChannelGroup(GlobalEventExecutor.INSTANCE),
                    GlobalEventExecutor.INSTANCE,
                    /* discoveryClient= */ null);
    EventLoopGroupMetrics elgm = new EventLoopGroupMetrics(Spectator.globalRegistry());
    EventLoopConfig elc = new EventLoopConfig() {
        @Override
        public int eventLoopCount() {
            return 1;
        }

        @Override
        public int acceptorCount() {
            return 1;
        }
    };
    Server s = new Server(ssm, initializers, ccs, elgm, elc);
    s.start(/* sync= */ false);

    List<SocketAddress> addrs = s.getListeningAddresses();
    assertEquals(2, addrs.size());
    assertTrue(addrs.get(0) instanceof InetSocketAddress);
    assertNotEquals(((InetSocketAddress) addrs.get(0)).getPort(), 0);
    assertTrue(addrs.get(1) instanceof InetSocketAddress);
    assertNotEquals(((InetSocketAddress) addrs.get(1)).getPort(), 0);

    s.stop();
}
 
Example #30
Source File: SpectatorUtils.java    From zuul with Apache License 2.0 4 votes vote down vote up
public static <T extends Number> T newGauge(String name, String id, T number) {
    final CompositeRegistry registry = Spectator.globalRegistry();
    Id gaugeId = registry.createId(name, "id", id);
    return registry.gauge(gaugeId, number);
}