use of io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk in project opentelemetry-java-instrumentation by open-telemetry.
the class AgentInstaller method installBytebuddyAgent.
/**
* Install the core bytebuddy agent along with all implementations of {@link
* InstrumentationModule}.
*
* @param inst Java Instrumentation used to install bytebuddy
* @return the agent's class transformer
*/
public static ResettableClassFileTransformer installBytebuddyAgent(Instrumentation inst, Iterable<AgentListener> agentListeners) {
WeakRefAsyncOperationEndStrategies.initialize();
Config config = Config.get();
setBootstrapPackages(config);
// If noop OpenTelemetry is enabled, autoConfiguredSdk will be null and AgentListeners are not
// called
AutoConfiguredOpenTelemetrySdk autoConfiguredSdk = null;
if (config.getBoolean(JAVAAGENT_NOOP_CONFIG, false)) {
logger.info("Tracing and metrics are disabled because noop is enabled.");
GlobalOpenTelemetry.set(NoopOpenTelemetry.getInstance());
} else {
autoConfiguredSdk = installOpenTelemetrySdk(config);
}
if (autoConfiguredSdk != null) {
runBeforeAgentListeners(agentListeners, config, autoConfiguredSdk);
}
AgentBuilder agentBuilder = new AgentBuilder.Default().disableClassFormatChanges().with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION).with(new RedefinitionDiscoveryStrategy()).with(AgentBuilder.DescriptionStrategy.Default.POOL_ONLY).with(AgentTooling.poolStrategy()).with(new ClassLoadListener()).with(AgentTooling.locationStrategy(Utils.getBootstrapProxy()));
if (JavaModule.isSupported()) {
agentBuilder = agentBuilder.with(new ExposeAgentBootstrapListener(inst));
}
agentBuilder = configureIgnoredTypes(config, agentBuilder);
if (logger.isDebugEnabled()) {
agentBuilder = agentBuilder.with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION).with(new RedefinitionDiscoveryStrategy()).with(new RedefinitionLoggingListener()).with(new TransformLoggingListener());
}
int numberOfLoadedExtensions = 0;
for (AgentExtension agentExtension : loadOrdered(AgentExtension.class)) {
logger.debug("Loading extension {} [class {}]", agentExtension.extensionName(), agentExtension.getClass().getName());
try {
agentBuilder = agentExtension.extend(agentBuilder);
numberOfLoadedExtensions++;
} catch (Exception | LinkageError e) {
logger.error("Unable to load extension {} [class {}]", agentExtension.extensionName(), agentExtension.getClass().getName(), e);
}
}
logger.debug("Installed {} extension(s)", numberOfLoadedExtensions);
ResettableClassFileTransformer resettableClassFileTransformer = agentBuilder.installOn(inst);
ClassFileTransformerHolder.setClassFileTransformer(resettableClassFileTransformer);
if (autoConfiguredSdk != null) {
runAfterAgentListeners(agentListeners, config, autoConfiguredSdk);
}
return resettableClassFileTransformer;
}
use of io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk in project opentelemetry-java-instrumentation by open-telemetry.
the class OpenTelemetryInstaller method installOpenTelemetrySdk.
/**
* Install the {@link OpenTelemetrySdk} using autoconfigure, and return the {@link
* AutoConfiguredOpenTelemetrySdk}.
*
* @return the {@link AutoConfiguredOpenTelemetrySdk}
*/
static AutoConfiguredOpenTelemetrySdk installOpenTelemetrySdk(Config config) {
System.setProperty("io.opentelemetry.context.contextStorageProvider", "default");
AutoConfiguredOpenTelemetrySdkBuilder builder = AutoConfiguredOpenTelemetrySdk.builder().setResultAsGlobal(true).addPropertiesSupplier(config::getAllProperties);
ClassLoader classLoader = AgentInitializer.getExtensionsClassLoader();
if (classLoader != null) {
// May be null in unit tests.
builder.setServiceClassLoader(classLoader);
}
AutoConfiguredOpenTelemetrySdk autoConfiguredSdk = builder.build();
OpenTelemetrySdk sdk = autoConfiguredSdk.getOpenTelemetrySdk();
OpenTelemetrySdkAccess.internalSetForceFlush((timeout, unit) -> {
CompletableResultCode traceResult = sdk.getSdkTracerProvider().forceFlush();
CompletableResultCode metricsResult = sdk.getSdkMeterProvider().forceFlush();
CompletableResultCode.ofAll(Arrays.asList(traceResult, metricsResult)).join(timeout, unit);
});
SdkLogEmitterProvider sdkLogEmitterProvider = autoConfiguredSdk.getOpenTelemetrySdk().getSdkLogEmitterProvider();
LogEmitterProvider logEmitterProvider = DelegatingLogEmitterProvider.from(sdkLogEmitterProvider);
AgentLogEmitterProvider.set(logEmitterProvider);
return autoConfiguredSdk;
}
use of io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk in project opentelemetry-plugin by jenkinsci.
the class OpenTelemetrySdkProvider method initialize.
public void initialize(@Nonnull OpenTelemetryConfiguration configuration) {
// shutdown existing SDK
preDestroy();
AutoConfiguredOpenTelemetrySdkBuilder sdkBuilder = AutoConfiguredOpenTelemetrySdk.builder();
// PROPERTIES
sdkBuilder.addPropertiesSupplier(() -> configuration.toOpenTelemetryProperties());
// RESOURCE
sdkBuilder.addResourceCustomizer((resource, configProperties) -> {
ResourceBuilder resourceBuilder = Resource.builder().putAll(resource).putAll(configuration.toOpenTelemetryResource());
return resourceBuilder.build();
});
sdkBuilder.registerShutdownHook(// SDK closed by io.jenkins.plugins.opentelemetry.OpenTelemetrySdkProvider.preDestroy()
false).setResultAsGlobal(// ensure GlobalOpenTelemetry.set() is invoked
true);
AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk = sdkBuilder.build();
this.openTelemetrySdk = autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk();
this.resource = autoConfiguredOpenTelemetrySdk.getResource();
this.config = autoConfiguredOpenTelemetrySdk.getConfig();
this.openTelemetry = this.openTelemetrySdk;
this.tracer.setDelegate(openTelemetry.getTracer(GlobalOpenTelemetrySdk.INSTRUMENTATION_NAME, OtelUtils.getOpentelemetryPluginVersion()));
this.logEmitter = openTelemetrySdk.getSdkLogEmitterProvider().get(GlobalOpenTelemetrySdk.INSTRUMENTATION_NAME);
this.meter = openTelemetry.getMeterProvider().get(GlobalOpenTelemetrySdk.INSTRUMENTATION_NAME);
LOGGER.log(Level.INFO, () -> "OpenTelemetry SDK initialized: " + OtelUtils.prettyPrintOtelSdkConfig(autoConfiguredOpenTelemetrySdk));
}
use of io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk in project splunk-otel-java by signalfx.
the class TestMicrometerInstaller method beforeAgent.
@Override
public void beforeAgent(Config config, AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk) {
Tags globalMetricsTags = config.getMap("splunk.testing.metrics.global-tags", emptyMap()).entrySet().stream().map(e -> Tag.of(e.getKey(), e.getValue())).reduce(Tags.empty(), Tags::and, Tags::concat);
SimpleMeterRegistry registry = new SimpleMeterRegistry();
registry.config().meterFilter(MeterFilter.commonTags(globalMetricsTags));
Metrics.addRegistry(registry);
}
use of io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk in project opentelemetry-plugin by jenkinsci.
the class OpenTelemetryLogToElasticsearchIT method test.
@Test
public void test() throws Exception {
InputStream envAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(".env");
Assert.assertNotNull(".env file not found in classpath", envAsStream);
Properties env = new Properties();
env.load(envAsStream);
Map<String, String> configuration = new HashMap<>();
env.forEach((k, v) -> configuration.put(k.toString(), v.toString()));
configuration.put("otel.traces.exporter", "otlp");
configuration.put("otel.metrics.exporter", "otlp");
configuration.put("otel.logs.exporter", "otlp");
final int LOG_MESSAGE_COUNT = 100;
String traceId;
// PRODUCE OPEN TELEMETRY LOG MESSAGES
{
AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk = AutoConfiguredOpenTelemetrySdk.builder().addPropertiesSupplier(() -> configuration).build();
try {
OpenTelemetrySdk sdk = autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk();
Tracer tracer = sdk.getTracer("test");
LogEmitter logEmitter = sdk.getSdkLogEmitterProvider().get("test");
Span span = tracer.spanBuilder("my-test-pipeline").startSpan();
try (Scope scope = span.makeCurrent()) {
for (int i = 0; i < LOG_MESSAGE_COUNT; i++) {
logEmitter.logBuilder().setContext(Context.current()).setBody("Log Message " + i).setAttributes(Attributes.of(AttributeKey.stringKey("myStringAttribute"), "Value " + i, AttributeKey.longKey("myNumericAttribute"), (long) i)).emit();
Thread.sleep(RANDOM.nextInt(100));
}
} finally {
span.end();
}
traceId = span.getSpanContext().getTraceId();
} finally {
autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk().getSdkLogEmitterProvider().close();
autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk().getSdkTracerProvider().close();
}
}
Thread.sleep(3_000);
// VERIFY LOG MESSAGES IN ELASTICSEARCH
{
String elasticsearchUrl = configuration.get("elasticsearch.url");
String elasticsearchUsername = configuration.get("elasticsearch.username");
String elasticsearchPassword = configuration.get("elasticsearch.password");
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(elasticsearchUsername, elasticsearchPassword));
RestClient restClient = RestClient.builder(HttpHost.create(elasticsearchUrl)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)).build();
RestClientTransport elasticsearchTransport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient elasticsearchClient = new ElasticsearchClient(elasticsearchTransport);
SearchRequest searchRequest = new SearchRequest.Builder().index("logs-apm.app-*").size(500).sort(s -> s.field(f -> f.field("@timestamp").order(SortOrder.Asc))).query(q -> q.match(m -> m.field("trace.id").query(FieldValue.of(traceId)))).build();
SearchResponse<ObjectNode> searchResponse = elasticsearchClient.search(searchRequest, ObjectNode.class);
List<Hit<ObjectNode>> hits = searchResponse.hits().hits();
if (hits.size() != LOG_MESSAGE_COUNT) {
System.err.println("Invalid number of log messages: actual: " + hits.size() + ", expected: " + LOG_MESSAGE_COUNT);
}
for (Hit<ObjectNode> hit : hits) {
ObjectNode source = hit.source();
ObjectNode labels = (ObjectNode) source.findValue("labels");
ObjectNode numericLabels = (ObjectNode) source.findValue("numeric_labels");
try {
String message = source.findValue("message").asText();
String myStringAttribute = labels.findValue("myStringAttribute").asText();
long myNumericAttribute = numericLabels.findValue("myNumericAttribute").longValue();
System.out.println(hit.id() + "\tmessage:'" + message + "', \tmyStringAttribute: '" + myStringAttribute + "', myNumericAttribute: " + myNumericAttribute);
} catch (Exception e) {
System.err.println("Error parsing " + source);
}
}
}
}
Aggregations