Added property for overriding the service name in Zipkin

without this only either service discovery service id / spring.application.name can be chosen as a service name for zipkin
    with this change you can pass spring.zipkin.service.name property to change override that both for HTTP and Stream collectors

    fixes #324
This commit is contained in:
Marcin Grzejszczak
2017-01-02 10:18:20 +01:00
parent 2a06734106
commit e117531d75
15 changed files with 255 additions and 33 deletions

View File

@@ -195,13 +195,13 @@ Below you can find an example of a Logback configuration (file named https://git
<property name="LOG_FILE" value="${BUILD_FOLDER:-build}/${springAppName}"/>
<property name="CONSOLE_LOG_PATTERN"
value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr([${springAppName:-},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-Span-Export:-}]){yellow} %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
value="%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr([${springAppName:-},%X{X-B3-TraceId:-},%X{X-B3-SpanId:-},%X{X-B3-ParentSpanId:-},%X{X-Span-Export:-}]){yellow} %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}"/>
<!-- Appender to log to console -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<!-- Minimum logging level to be presented in the console logs-->
<level>INFO</level>
<level>DEBUG</level>
</filter>
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
@@ -241,6 +241,7 @@ Below you can find an example of a Logback configuration (file named https://git
"service": "${springAppName:-}",
"trace": "%X{X-B3-TraceId:-}",
"span": "%X{X-B3-SpanId:-}",
"parent": "%X{X-B3-ParentSpanId:-}",
"exportable": "%X{X-Span-Export:-}",
"pid": "${PID:-}",
"thread": "%thread",
@@ -254,7 +255,7 @@ Below you can find an example of a Logback configuration (file named https://git
</appender>
<root level="INFO">
<!--<appender-ref ref="console"/>-->
<appender-ref ref="console"/>
<appender-ref ref="logstash"/>
<!--<appender-ref ref="flatfile"/>-->
</root>

View File

@@ -292,6 +292,19 @@ include::../../../..//spring-cloud-sleuth-zipkin/src/test/java/org/springframewo
IMPORTANT: Remember not to add both `peer.service` tag and the `SA` tag! You have to add only `peer.service`.
=== Custom service name
By default Sleuth assumes that when you send a span to Zipkin, you want the span's service name
to be equal to `spring.application.name` value. That's not always the case though. There
are situations in which you want to explicitly provide a different service name for all spans coming
from your application. To achieve that it's enough to just pass the following property
to your application to override that value (example for `foo` service name):
[source,yaml]
----
spring.zipkin.service.name: foo
----
== Span Data as Messages
You can accumulate and send span data over

View File

@@ -22,27 +22,39 @@ import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.sleuth.Span;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* An {@link HostLocator} that tries to find local service information from a
* {@link DiscoveryClient}.
*
* You can override the value of service id by {@link ZipkinProperties#setName(String)}
*
* @author Dave Syer
* @since 1.0.0
*/
public class DiscoveryClientHostLocator implements HostLocator {
private DiscoveryClient client;
private final DiscoveryClient client;
private final ZipkinProperties zipkinProperties;
@Deprecated
public DiscoveryClientHostLocator(DiscoveryClient client) {
this(client, new ZipkinProperties());
}
public DiscoveryClientHostLocator(DiscoveryClient client, ZipkinProperties zipkinProperties) {
this.client = client;
Assert.notNull(this.client, "client");
this.zipkinProperties = zipkinProperties;
}
@Override
public Host locate(Span span) {
ServiceInstance instance = this.client.getLocalServiceInstance();
return new Host(instance.getServiceId(), getIpAddress(instance),
String serviceId = StringUtils.hasText(this.zipkinProperties.getName()) ?
this.zipkinProperties.getName() : instance.getServiceId();
return new Host(serviceId, getIpAddress(instance),
instance.getPort());
}

View File

@@ -21,6 +21,7 @@ import org.springframework.boot.context.embedded.EmbeddedServletContainerInitial
import org.springframework.cloud.sleuth.Span;
import org.springframework.context.event.EventListener;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* A {@link HostLocator} that retrieves:
@@ -31,6 +32,8 @@ import org.springframework.util.Assert;
* <li><b>port</b> - from lazily assigned port or {@link ServerProperties}</li>
* </ul>
*
* You can override the value of service id by {@link ZipkinProperties#setName(String)}
*
* @author Dave Syer
* @since 1.0.0
*/
@@ -38,13 +41,21 @@ public class ServerPropertiesHostLocator implements HostLocator {
private final ServerProperties serverProperties; // Nullable
private final String appName;
private final ZipkinProperties zipkinProperties;
private Integer port; // Lazy assigned
@Deprecated
public ServerPropertiesHostLocator(ServerProperties serverProperties,
String appName) {
this(serverProperties, appName, new ZipkinProperties());
}
public ServerPropertiesHostLocator(ServerProperties serverProperties,
String appName, ZipkinProperties zipkinProperties) {
this.serverProperties = serverProperties;
this.appName = appName;
Assert.notNull(this.appName, "appName");
this.zipkinProperties = zipkinProperties;
}
@Override
@@ -87,7 +98,9 @@ public class ServerPropertiesHostLocator implements HostLocator {
private String getServiceName(Span span) {
String serviceName;
if (span.getProcessId() != null) {
if (StringUtils.hasText(this.zipkinProperties.getName())) {
serviceName = this.zipkinProperties.getName();
} else if (span.getProcessId() != null) {
serviceName = span.getProcessId();
}
else {

View File

@@ -54,7 +54,7 @@ import org.springframework.scheduling.support.PeriodicTrigger;
* @since 1.0.0
*/
@Configuration
@EnableConfigurationProperties({ SleuthStreamProperties.class, SamplerProperties.class })
@EnableConfigurationProperties({ SleuthStreamProperties.class, SamplerProperties.class, ZipkinProperties.class })
@AutoConfigureAfter(TraceMetricsAutoConfiguration.class)
@AutoConfigureBefore(ChannelBindingAutoConfiguration.class)
@EnableBinding(SleuthSource.class)
@@ -96,12 +96,15 @@ public class SleuthStreamAutoConfiguration {
@Autowired(required = false)
private ServerProperties serverProperties;
@Autowired
private ZipkinProperties zipkinProperties;
@Value("${spring.application.name:unknown}")
private String appName;
@Bean
public HostLocator zipkinEndpointLocator() {
return new ServerPropertiesHostLocator(this.serverProperties, this.appName);
return new ServerPropertiesHostLocator(this.serverProperties, this.appName, this.zipkinProperties);
}
}
@@ -113,6 +116,9 @@ public class SleuthStreamAutoConfiguration {
@Autowired(required = false)
private ServerProperties serverProperties;
@Autowired
private ZipkinProperties zipkinProperties;
@Value("${spring.application.name:unknown}")
private String appName;
@@ -122,9 +128,9 @@ public class SleuthStreamAutoConfiguration {
@Bean
public HostLocator zipkinEndpointLocator() {
if (this.client != null) {
return new DiscoveryClientHostLocator(this.client);
return new DiscoveryClientHostLocator(this.client, this.zipkinProperties);
}
return new ServerPropertiesHostLocator(this.serverProperties, this.appName);
return new ServerPropertiesHostLocator(this.serverProperties, this.appName, this.zipkinProperties);
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright 2013-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.sleuth.stream;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Zipkin settings for Zipkin Stream client
*
* @author Marcin Grzejszczak
* @since 1.0.12
*/
@ConfigurationProperties("spring.zipkin.service")
public class ZipkinProperties {
/** The name of the service, from which the Span was sent via Stream, that should appear in Zipkin */
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@@ -34,11 +34,11 @@ import static org.mockito.BDDMockito.given;
public class DiscoveryClientHostLocatorTest {
DiscoveryClient discoveryClient = Mockito.mock(DiscoveryClient.class);
DiscoveryClientHostLocator discoveryClientHostLocator =
new DiscoveryClientHostLocator(this.discoveryClient);
new DiscoveryClientHostLocator(this.discoveryClient, new ZipkinProperties());
@Test(expected = IllegalArgumentException.class)
public void should_throw_exception_when_no_discovery_client_is_present() throws Exception {
new DiscoveryClientHostLocator(null);
new DiscoveryClientHostLocator(null, new ZipkinProperties());
}
@Test
@@ -63,6 +63,20 @@ public class DiscoveryClientHostLocatorTest {
then(host.getIpv4()).isEqualTo(InetUtils.getIpAddressAsInt("localhost"));
}
@Test
public void should_override_the_service_name_from_properties() throws Exception {
given(this.discoveryClient.getLocalServiceInstance()).willReturn(serviceInstanceWithValidHost());
ZipkinProperties zipkinProperties = new ZipkinProperties();
zipkinProperties.setName("foo");
this.discoveryClientHostLocator = new DiscoveryClientHostLocator(this.discoveryClient, zipkinProperties);
Host host = this.discoveryClientHostLocator.locate(null);
then(host.getServiceName()).isEqualTo("foo");
then(host.getPort()).isEqualTo((short)8_000);
then(host.getIpv4()).isEqualTo(InetUtils.getIpAddressAsInt("localhost"));
}
private ServiceInstance serviceInstanceWithInvalidHost() {
return new ServiceInstance() {
@Override public String getServiceId() {

View File

@@ -33,7 +33,7 @@ public class ServerPropertiesHostLocatorTests {
@Test
public void portDefaultsTo8080() {
ServerPropertiesHostLocator locator = new ServerPropertiesHostLocator(
new ServerProperties(), "unknown");
new ServerProperties(), "unknown", new ZipkinProperties());
assertThat(locator.locate(this.span).getPort()).isEqualTo((short) 8080);
}
@@ -44,7 +44,7 @@ public class ServerPropertiesHostLocatorTests {
properties.setPort(1234);
ServerPropertiesHostLocator locator = new ServerPropertiesHostLocator(properties,
"unknown");
"unknown", new ZipkinProperties());
assertThat(locator.locate(this.span).getPort()).isEqualTo((short) 1234);
}
@@ -52,7 +52,7 @@ public class ServerPropertiesHostLocatorTests {
@Test
public void portDefaultsToLocalhost() {
ServerPropertiesHostLocator locator = new ServerPropertiesHostLocator(
new ServerProperties(), "unknown");
new ServerProperties(), "unknown", new ZipkinProperties());
assertThat(locator.locate(this.span).getAddress()).isEqualTo("127.0.0.1");
}
@@ -63,8 +63,21 @@ public class ServerPropertiesHostLocatorTests {
properties.setAddress(InetAddress.getByAddress(new byte[] { 1, 2, 3, 4 }));
ServerPropertiesHostLocator locator = new ServerPropertiesHostLocator(properties,
"unknown");
"unknown", new ZipkinProperties());
assertThat(locator.locate(this.span).getAddress()).isEqualTo("1.2.3.4");
}
@Test
public void nameTakenFromProperties() throws UnknownHostException {
ServerProperties properties = new ServerProperties();
properties.setAddress(InetAddress.getByAddress(new byte[] { 1, 2, 3, 4 }));
ZipkinProperties zipkinProperties = new ZipkinProperties();
zipkinProperties.setName("foo");
ServerPropertiesHostLocator locator = new ServerPropertiesHostLocator(properties,
"unknown", zipkinProperties);
assertThat(locator.locate(this.span).getServiceName()).isEqualTo("foo");
}
}

View File

@@ -16,24 +16,42 @@
package org.springframework.cloud.sleuth.zipkin;
import java.lang.invoke.MethodHandles;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.util.StringUtils;
import zipkin.Endpoint;
/**
* An {@link EndpointLocator} that tries to find local service information from a
* {@link DiscoveryClient}.
*
* You can override the name using {@link ZipkinProperties.Service#setName(String)}
*
* @author Dave Syer
* @since 1.0.0
*/
public class DiscoveryClientEndpointLocator implements EndpointLocator {
private DiscoveryClient client;
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
private final DiscoveryClient client;
private final ZipkinProperties zipkinProperties;
@Deprecated
public DiscoveryClientEndpointLocator(DiscoveryClient client) {
this(client, new ZipkinProperties());
}
public DiscoveryClientEndpointLocator(DiscoveryClient client,
ZipkinProperties zipkinProperties) {
this.client = client;
this.zipkinProperties = zipkinProperties;
}
@Override
@@ -42,8 +60,13 @@ public class DiscoveryClientEndpointLocator implements EndpointLocator {
if (instance == null) {
throw new NoServiceInstanceAvailableException();
}
String serviceName = StringUtils.hasText(this.zipkinProperties.getService().getName()) ?
this.zipkinProperties.getService().getName() : instance.getServiceId();
if (log.isDebugEnabled()) {
log.debug("Span will contain serviceName [" + serviceName + "]");
}
return Endpoint.builder()
.serviceName(instance.getServiceId())
.serviceName(serviceName)
.ipv4(getIpAddress(instance))
.port(instance.getPort()).build();
}

View File

@@ -16,10 +16,15 @@
package org.springframework.cloud.sleuth.zipkin;
import java.lang.invoke.MethodHandles;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.event.EventListener;
import org.springframework.util.StringUtils;
import zipkin.Endpoint;
@@ -31,25 +36,42 @@ import zipkin.Endpoint;
* <li><b>port</b> - from lazily assigned port or {@link ServerProperties}</li>
* </ul>
*
* You can override the name using {@link ZipkinProperties.Service#setName(String)}
*
* @author Dave Syer
* @since 1.0.0
*/
public class ServerPropertiesEndpointLocator implements EndpointLocator {
private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass());
private final ServerProperties serverProperties;
private final String appName;
private final ZipkinProperties zipkinProperties;
private Integer port;
@Deprecated
public ServerPropertiesEndpointLocator(ServerProperties serverProperties,
String appName) {
String appName) {
this(serverProperties, appName, new ZipkinProperties());
}
public ServerPropertiesEndpointLocator(ServerProperties serverProperties,
String appName, ZipkinProperties zipkinProperties) {
this.serverProperties = serverProperties;
this.appName = appName;
this.zipkinProperties = zipkinProperties;
}
@Override
public Endpoint local() {
String serviceName = StringUtils.hasText(this.zipkinProperties.getService().getName()) ?
this.zipkinProperties.getService().getName() : this.appName;
if (log.isDebugEnabled()) {
log.debug("Span will contain serviceName [" + serviceName + "]");
}
return Endpoint.builder()
.serviceName(this.appName)
.serviceName(serviceName)
.ipv4(getAddress())
.port(getPort())
.build();

View File

@@ -75,12 +75,16 @@ public class ZipkinAutoConfiguration {
@Autowired(required=false)
private ServerProperties serverProperties;
@Autowired
private ZipkinProperties zipkinProperties;
@Value("${spring.application.name:unknown}")
private String appName;
@Bean
public EndpointLocator zipkinEndpointLocator() {
return new ServerPropertiesEndpointLocator(this.serverProperties, this.appName);
return new ServerPropertiesEndpointLocator(this.serverProperties, this.appName,
this.zipkinProperties);
}
}
@@ -92,6 +96,9 @@ public class ZipkinAutoConfiguration {
@Autowired(required=false)
private ServerProperties serverProperties;
@Autowired
private ZipkinProperties zipkinProperties;
@Value("${spring.application.name:unknown}")
private String appName;
@@ -101,12 +108,13 @@ public class ZipkinAutoConfiguration {
@Bean
public EndpointLocator zipkinEndpointLocator() {
return new FallbackHavingEndpointLocator(discoveryClientEndpointLocator(),
new ServerPropertiesEndpointLocator(this.serverProperties, this.appName));
new ServerPropertiesEndpointLocator(this.serverProperties, this.appName,
this.zipkinProperties));
}
private DiscoveryClientEndpointLocator discoveryClientEndpointLocator() {
if (this.client!=null) {
return new DiscoveryClientEndpointLocator(this.client);
return new DiscoveryClientEndpointLocator(this.client, this.zipkinProperties);
}
return null;
}

View File

@@ -32,6 +32,8 @@ public class ZipkinProperties {
private int flushInterval = 1;
private Compression compression = new Compression();
private Service service = new Service();
public String getBaseUrl() {
return this.baseUrl;
}
@@ -48,6 +50,10 @@ public class ZipkinProperties {
return this.compression;
}
public Service getService() {
return this.service;
}
public void setBaseUrl(String baseUrl) {
this.baseUrl = baseUrl;
}
@@ -64,6 +70,10 @@ public class ZipkinProperties {
this.compression = compression;
}
public void setService(Service service) {
this.service = service;
}
/** When enabled, spans are gzipped before sent to the zipkin server */
public static class Compression {
@@ -77,4 +87,19 @@ public class ZipkinProperties {
this.enabled = enabled;
}
}
/** When set will override the default {@code spring.application.name} value of the service id */
public static class Service {
/** The name of the service, from which the Span was sent via HTTP, that should appear in Zipkin */
private String name;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
}

View File

@@ -19,9 +19,9 @@ package org.springframework.cloud.sleuth.zipkin;
import java.net.URI;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.cloud.client.ServiceInstance;
@@ -41,7 +41,12 @@ import static org.mockito.BDDMockito.given;
public class DiscoveryClientEndpointLocatorTest {
@Mock DiscoveryClient discoveryClient;
@InjectMocks DiscoveryClientEndpointLocator discoveryClientEndpointLocator;
DiscoveryClientEndpointLocator discoveryClientEndpointLocator;
@Before
public void setup() {
this.discoveryClientEndpointLocator = new DiscoveryClientEndpointLocator(this.discoveryClient, new ZipkinProperties());
}
@Test(expected = NoServiceInstanceAvailableException.class)
public void should_throw_exception_when_no_instances_are_available() throws Exception {
@@ -70,6 +75,20 @@ public class DiscoveryClientEndpointLocatorTest {
then(local.ipv4).isEqualTo(InetUtils.getIpAddressAsInt("localhost"));
}
@Test
public void should_create_endpoint_with_overridden_name() throws Exception {
ZipkinProperties zipkinProperties = new ZipkinProperties();
zipkinProperties.getService().setName("foo");
DiscoveryClientEndpointLocator locator = new DiscoveryClientEndpointLocator(this.discoveryClient, zipkinProperties);
given(this.discoveryClient.getLocalServiceInstance()).willReturn(serviceInstanceWithValidHost());
Endpoint local = locator.local();
then(local.serviceName).isEqualTo("foo");
then(local.port).isEqualTo((short)8_000);
then(local.ipv4).isEqualTo(InetUtils.getIpAddressAsInt("localhost"));
}
private ServiceInstance serviceInstanceWithInvalidHost() {
return new ServiceInstance() {
@Override public String getServiceId() {

View File

@@ -129,7 +129,8 @@ public class HttpZipkinSpanReporterTest {
AtomicReference<Span> receivedSpan = new AtomicReference<>();
Tracer tracer = new DefaultTracer(new AlwaysSampler(), new Random(), new DefaultSpanNamer(),
new NoOpSpanLogger(), new ZipkinSpanListener(receivedSpan::set,
new ServerPropertiesEndpointLocator(new ServerProperties(), "foo")));
new ServerPropertiesEndpointLocator(new ServerProperties(), "foo",
new ZipkinProperties())));
// tag::service_name[]
org.springframework.cloud.sleuth.Span newSpan = tracer.createSpan("redis");
try {

View File

@@ -16,12 +16,12 @@
package org.springframework.cloud.sleuth.zipkin;
import org.junit.Test;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.junit.Test;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import static org.assertj.core.api.Assertions.assertThat;
public class ServerPropertiesEndpointLocatorTests {
@@ -29,7 +29,7 @@ public class ServerPropertiesEndpointLocatorTests {
@Test
public void portDefaultsTo8080() {
ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator(
new ServerProperties(), "unknown");
new ServerProperties(), "unknown", new ZipkinProperties());
assertThat(locator.local().port).isEqualTo((short) 8080);
}
@@ -40,7 +40,7 @@ public class ServerPropertiesEndpointLocatorTests {
properties.setPort(1234);
ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator(
properties, "unknown");
properties, "unknown", new ZipkinProperties());
assertThat(locator.local().port).isEqualTo((short) 1234);
}
@@ -48,7 +48,7 @@ public class ServerPropertiesEndpointLocatorTests {
@Test
public void portDefaultsToLocalhost() {
ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator(
new ServerProperties(), "unknown");
new ServerProperties(), "unknown", new ZipkinProperties());
assertThat(locator.local().ipv4).isEqualTo(127 << 24 | 1);
}
@@ -59,8 +59,20 @@ public class ServerPropertiesEndpointLocatorTests {
properties.setAddress(InetAddress.getByAddress(new byte[] { 1, 2, 3, 4 }));
ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator(
properties, "unknown");
properties, "unknown", new ZipkinProperties());
assertThat(locator.local().ipv4).isEqualTo(1 << 24 | 2 << 16 | 3 << 8 | 4);
}
@Test
public void appNameFromProperties() throws UnknownHostException {
ServerProperties properties = new ServerProperties();
ZipkinProperties zipkinProperties = new ZipkinProperties();
zipkinProperties.getService().setName("foo");
ServerPropertiesEndpointLocator locator = new ServerPropertiesEndpointLocator(
properties, "unknown", zipkinProperties);
assertThat(locator.local().serviceName).isEqualTo("foo");
}
}