Search in sources :

Example 1 with Arg

use of com.palantir.logsafe.Arg in project atlasdb by palantir.

the class CheckAndSetQueriesTest method valuesCreatedAtCorrectLogSafetyLevelsForUpdates.

@Test
public void valuesCreatedAtCorrectLogSafetyLevelsForUpdates() {
    CqlQuery query = CheckAndSetQueries.getQueryForRequest(UPDATE_REQUEST);
    AtomicReference<Object[]> objects = new AtomicReference<>();
    query.logSlowResult((format, args) -> objects.set(args), Stopwatch.createStarted());
    Object[] loggedObjects = objects.get();
    Map<String, Boolean> argumentSafety = new HashMap<>();
    Arrays.stream(loggedObjects).forEach(object -> {
        Arg<?> arg = (Arg<?>) object;
        argumentSafety.put(arg.getName(), arg.isSafeForLogging());
    });
    assertThat(argumentSafety).containsEntry("row", false).containsEntry("column", false).containsEntry("cassandraTimestamp", true).containsEntry("oldValue", false).containsEntry("newValue", false).containsEntry("unsafeTableRef", false).doesNotContainKey(// the table wasn't marked as safe
    "tableRef");
    assertThat(query.toString()).isEqualTo("UPDATE \"ns__table\" SET value=0x626262" + " WHERE key=0x616263 AND column1=0x313233 AND column2=-1 IF value=0x616161;");
}
Also used : HashMap(java.util.HashMap) Arg(com.palantir.logsafe.Arg) AtomicReference(java.util.concurrent.atomic.AtomicReference) CqlQuery(com.palantir.atlasdb.keyvalue.cassandra.CqlQuery) Test(org.junit.Test)

Example 2 with Arg

use of com.palantir.logsafe.Arg in project atlasdb by palantir.

the class CheckAndSetQueriesTest method valuesCreatedAtCorrectLogSafetyLevelsForNewCells.

@Test
public void valuesCreatedAtCorrectLogSafetyLevelsForNewCells() {
    CqlQuery query = CheckAndSetQueries.getQueryForRequest(NEW_CELL_REQUEST);
    AtomicReference<Object[]> objects = new AtomicReference<>();
    query.logSlowResult((format, args) -> objects.set(args), Stopwatch.createStarted());
    Object[] loggedObjects = objects.get();
    Map<String, Boolean> argumentSafety = new HashMap<>();
    Arrays.stream(loggedObjects).forEach(object -> {
        Arg<?> arg = (Arg<?>) object;
        argumentSafety.put(arg.getName(), arg.isSafeForLogging());
    });
    assertThat(argumentSafety).containsEntry("row", false).containsEntry("column", false).containsEntry("cassandraTimestamp", true).containsEntry("newValue", false).containsEntry("unsafeTableRef", false).doesNotContainKey(// the table wasn't marked as safe
    "tableRef");
    assertThat(query.toString()).isEqualTo("INSERT INTO \"ns__table\" (key, column1, column2, value)" + " VALUES (0x616263, 0x313233, -1, 0x70747074) IF NOT EXISTS;");
}
Also used : HashMap(java.util.HashMap) Arg(com.palantir.logsafe.Arg) AtomicReference(java.util.concurrent.atomic.AtomicReference) CqlQuery(com.palantir.atlasdb.keyvalue.cassandra.CqlQuery) Test(org.junit.Test)

Example 3 with Arg

use of com.palantir.logsafe.Arg in project dialogue by palantir.

the class ApacheHttpClientChannelsTest method close_doesnt_fail_inflight_requests.

@Test
public void close_doesnt_fail_inflight_requests() throws Exception {
    ClientConfiguration conf = TestConfigurations.create("http://foo");
    Channel channel;
    try (ApacheHttpClientChannels.CloseableClient client = ApacheHttpClientChannels.createCloseableHttpClient(conf, "client")) {
        channel = ApacheHttpClientChannels.createSingleUri("http://foo", client);
        ListenableFuture<Response> response = channel.execute(TestEndpoint.POST, Request.builder().build());
        assertThatThrownBy(() -> Futures.getUnchecked(response)).getCause().isInstanceOfSatisfying(UnknownHostException.class, throwable -> assertThat(throwable.getSuppressed()[0]).satisfies(diagnosticThrowable -> assertThat(diagnosticThrowable.getStackTrace()).as("Diagnostic exception should have an empty stack trace").isEmpty()).isInstanceOfSatisfying(SafeLoggable.class, safeLoggable -> {
            assertThat(Lists.transform(safeLoggable.getArgs(), Arg::getName)).as("Expected a diagnostic exception").containsExactlyInAnyOrder("durationMillis", "connectTimeout", "socketTimeout", "clientName", "serviceName", "endpointName", "requestTraceId", "requestSpanId", "hostIndex");
        }));
    }
    ListenableFuture<Response> again = channel.execute(TestEndpoint.POST, Request.builder().build());
    assertThatThrownBy(() -> Futures.getUnchecked(again)).hasCauseInstanceOf(UnknownHostException.class);
}
Also used : Response(com.palantir.dialogue.Response) AbstractChannelTest(com.palantir.dialogue.AbstractChannelTest) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ClientConfiguration(com.palantir.conjure.java.client.config.ClientConfiguration) TestEndpoint(com.palantir.dialogue.TestEndpoint) Meter(com.codahale.metrics.Meter) OptionalLong(java.util.OptionalLong) Lists(com.google.common.collect.Lists) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) HttpHeaders(com.google.common.net.HttpHeaders) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) Duration(java.time.Duration) Map(java.util.Map) Arg(com.palantir.logsafe.Arg) Request(com.palantir.dialogue.Request) OutputStream(java.io.OutputStream) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) RequestBody(com.palantir.dialogue.RequestBody) MoreCollectors(com.google.common.collect.MoreCollectors) Metric(com.codahale.metrics.Metric) IOException(java.io.IOException) SafeLoggable(com.palantir.logsafe.SafeLoggable) Channel(com.palantir.dialogue.Channel) HttpMethod(com.palantir.dialogue.HttpMethod) TaggedMetricRegistry(com.palantir.tritium.metrics.registry.TaggedMetricRegistry) UnknownHostException(java.net.UnknownHostException) TestConfigurations(com.palantir.dialogue.TestConfigurations) Test(org.junit.jupiter.api.Test) Futures(com.google.common.util.concurrent.Futures) Assertions.fail(org.assertj.core.api.Assertions.fail) Optional(java.util.Optional) Gauge(com.codahale.metrics.Gauge) Response(com.palantir.dialogue.Response) SafeLoggable(com.palantir.logsafe.SafeLoggable) Channel(com.palantir.dialogue.Channel) Arg(com.palantir.logsafe.Arg) ClientConfiguration(com.palantir.conjure.java.client.config.ClientConfiguration) AbstractChannelTest(com.palantir.dialogue.AbstractChannelTest) Test(org.junit.jupiter.api.Test)

Example 4 with Arg

use of com.palantir.logsafe.Arg in project safe-logging by palantir.

the class LoggerGenerator method generateLoggerImplementation.

private static JavaFile generateLoggerImplementation() {
    TypeSpec.Builder loggerBuilder = TypeSpec.classBuilder(LOGGER_NAME).addModifiers(Modifier.PUBLIC, Modifier.FINAL).addJavadoc("Safe-logging logger API used to produce log events with safe-classified {@link Arg} values.").addAnnotation(AnnotationSpec.builder(Generated.class).addMember("value", "$S", LoggerGenerator.class.getName()).build()).addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "TooManyArguments").build()).addField(FieldSpec.builder(BRIDGE_NAME, DELEGATE).addModifiers(Modifier.PRIVATE, Modifier.FINAL).build()).addMethod(MethodSpec.constructorBuilder().addJavadoc("Internal package-private constructor for {@link SafeLoggerFactory}.").addParameter(ParameterSpec.builder(BRIDGE_NAME, DELEGATE).build()).addStatement("this.$1N = $2T.requireNonNull($1N, $3S)", DELEGATE, Objects.class, "SafeLoggerBridge is required").build());
    for (MethodSpec spec : createLoggerBridge().methodSpecs) {
        MethodSpec.Builder methodBuilder = spec.toBuilder();
        methodBuilder.modifiers.clear();
        boolean isVoidMethod = ClassName.VOID.equals(spec.returnType);
        CodeBlock args = spec.parameters.stream().map(param -> CodeBlock.of("$N", param.name)).collect(CodeBlock.joining(", "));
        methodBuilder.addModifiers(Modifier.PUBLIC).addStatement("$L$N.$N($L)", isVoidMethod ? "" : "return ", DELEGATE, spec.name, args);
        loggerBuilder.addMethod(methodBuilder.build());
    }
    return JavaFile.builder(LOGGER_NAME.packageName(), loggerBuilder.build()).skipJavaLangImports(true).addFileComment(copyright(2021)).build();
}
Also used : ParameterSpec(com.squareup.javapoet.ParameterSpec) Modifier(javax.lang.model.element.Modifier) MethodSpec(com.squareup.javapoet.MethodSpec) CompileTimeConstant(com.google.errorprone.annotations.CompileTimeConstant) FieldSpec(com.squareup.javapoet.FieldSpec) ClassName(com.squareup.javapoet.ClassName) WildcardTypeName(com.squareup.javapoet.WildcardTypeName) ParameterizedTypeName(com.squareup.javapoet.ParameterizedTypeName) TypeSpec(com.squareup.javapoet.TypeSpec) JavaFile(com.squareup.javapoet.JavaFile) Objects(java.util.Objects) List(java.util.List) Safe(com.palantir.logsafe.Safe) Stream(java.util.stream.Stream) Paths(java.nio.file.Paths) Locale(java.util.Locale) Generated(javax.annotation.processing.Generated) AnnotationSpec(com.squareup.javapoet.AnnotationSpec) TypeName(com.squareup.javapoet.TypeName) Arg(com.palantir.logsafe.Arg) ArrayTypeName(com.squareup.javapoet.ArrayTypeName) CodeBlock(com.squareup.javapoet.CodeBlock) Nullable(javax.annotation.Nullable) Goethe(com.palantir.goethe.Goethe) MethodSpec(com.squareup.javapoet.MethodSpec) CodeBlock(com.squareup.javapoet.CodeBlock) TypeSpec(com.squareup.javapoet.TypeSpec)

Aggregations

Arg (com.palantir.logsafe.Arg)4 CqlQuery (com.palantir.atlasdb.keyvalue.cassandra.CqlQuery)2 HashMap (java.util.HashMap)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Test (org.junit.Test)2 Gauge (com.codahale.metrics.Gauge)1 Meter (com.codahale.metrics.Meter)1 Metric (com.codahale.metrics.Metric)1 Lists (com.google.common.collect.Lists)1 MoreCollectors (com.google.common.collect.MoreCollectors)1 HttpHeaders (com.google.common.net.HttpHeaders)1 Futures (com.google.common.util.concurrent.Futures)1 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)1 UncheckedExecutionException (com.google.common.util.concurrent.UncheckedExecutionException)1 CompileTimeConstant (com.google.errorprone.annotations.CompileTimeConstant)1 ClientConfiguration (com.palantir.conjure.java.client.config.ClientConfiguration)1 AbstractChannelTest (com.palantir.dialogue.AbstractChannelTest)1 Channel (com.palantir.dialogue.Channel)1 HttpMethod (com.palantir.dialogue.HttpMethod)1 Request (com.palantir.dialogue.Request)1