Java Code Examples for com.linecorp.armeria.server.ServiceRequestContext#push()

The following examples show how to use com.linecorp.armeria.server.ServiceRequestContext#push() . 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: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testMdcPropertyPreservation() throws Exception {
    final List<ILoggingEvent> events = prepare(a -> a.addBuiltIn(BuiltInProperty.REQ_DIRECTION));

    MDC.put("some-prop", "some-value");
    final ServiceRequestContext ctx = newServiceContext("/foo", null);
    try (SafeCloseable ignored = ctx.push()) {
        final ILoggingEvent e = log(events);
        final Map<String, String> mdc = e.getMDCPropertyMap();
        assertThat(mdc).containsEntry("req.direction", "INBOUND")
                       .containsEntry("some-prop", "some-value")
                       .hasSize(2);
    } finally {
        MDC.remove("some-prop");
    }
}
 
Example 2
Source File: DefaultClientRequestContextTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void canBringAttributeInServiceRequestContext() {
    final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
    final ServiceRequestContext serviceContext = ServiceRequestContext.of(req);
    final AttributeKey<String> fooKey = AttributeKey.valueOf(DefaultClientRequestContextTest.class, "foo");
    serviceContext.setAttr(fooKey, "foo");
    try (SafeCloseable ignored = serviceContext.push()) {
        final ClientRequestContext clientContext = ClientRequestContext.of(req);
        assertThat(clientContext.attr(fooKey)).isEqualTo("foo");
        assertThat(clientContext.attrs().hasNext()).isTrue();

        final ClientRequestContext derivedContext = clientContext.newDerivedContext(
                clientContext.id(), clientContext.request(),
                clientContext.rpcRequest());
        assertThat(derivedContext.attr(fooKey)).isNotNull();
        // Attributes in serviceContext is not copied to clientContext when derived.

        final AttributeKey<String> barKey = AttributeKey.valueOf(DefaultClientRequestContextTest.class,
                                                                 "bar");
        clientContext.setAttr(barKey, "bar");
        assertThat(serviceContext.attr(barKey)).isNull();
    }
}
 
Example 3
Source File: ClientRequestContextTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void pushWithOldClientCtxWhoseRootIsSameServiceCtx_derivedCtx() {
    final ServiceRequestContext sctx = serviceRequestContext();
    try (SafeCloseable ignored = sctx.push()) {
        assertCurrentCtx(sctx);
        final ClientRequestContext cctx1 = clientRequestContext();
        final ClientRequestContext derived = cctx1.newDerivedContext(cctx1.id(), cctx1.request(),
                                                                     cctx1.rpcRequest());
        try (SafeCloseable ignored1 = derived.push()) {
            assertCurrentCtx(derived);
            final ClientRequestContext cctx2 = clientRequestContext();
            assertThat(derived.root()).isSameAs(cctx2.root());

            try (SafeCloseable ignored2 = cctx2.push()) {
                assertCurrentCtx(cctx2);
            }
            assertCurrentCtx(derived);
        }
        assertCurrentCtx(sctx);
    }
    assertCurrentCtx(null);
}
 
Example 4
Source File: ClientRequestContextTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void pushWithOldClientCtxWhoseRootIsSameServiceCtx__ctx2IsCreatedUnderCtx1() {
    final ServiceRequestContext sctx = serviceRequestContext();
    try (SafeCloseable ignored = sctx.push()) {
        assertCurrentCtx(sctx);
        final ClientRequestContext cctx1 = clientRequestContext();
        try (SafeCloseable ignored1 = cctx1.push()) {
            assertCurrentCtx(cctx1);
            final ClientRequestContext cctx2 = clientRequestContext();
            assertThat(cctx1.root()).isSameAs(cctx2.root());

            try (SafeCloseable ignored2 = cctx2.push()) {
                assertCurrentCtx(cctx2);
            }
            assertCurrentCtx(cctx1);
        }
        assertCurrentCtx(sctx);
    }
    assertCurrentCtx(null);
}
 
Example 5
Source File: RequestContextAwareFutureTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ContextFutureCallbackArgumentsProvider.class)
void makeContextAwareCompletableFutureWithDifferentContext(
        BiConsumer<CompletableFuture<?>, AtomicBoolean> callback) {
    final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
    final ServiceRequestContext ctx1 = ServiceRequestContext.builder(req).build();
    final ServiceRequestContext ctx2 = ServiceRequestContext.builder(req).build();
    try (SafeCloseable ignored = ctx1.push()) {
        final CompletableFuture<Object> future = new CompletableFuture<>();
        final CompletableFuture<Object> contextAwareFuture = ctx2.makeContextAware(future);
        final AtomicBoolean callbackCalled = new AtomicBoolean();
        callback.accept(contextAwareFuture, callbackCalled);

        future.complete(null);

        assertThat(callbackCalled.get()).isFalse();
        verify(appender, atLeast(0)).doAppend(eventCaptor.capture());
        assertThat(eventCaptor.getAllValues()).anySatisfy(event -> {
            assertThat(event.getLevel()).isEqualTo(Level.WARN);
            assertThat(event.getMessage()).startsWith("An error occurred while pushing");
        });
    }
}
 
Example 6
Source File: ClientRequestContextTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void pushWithOldServiceCtx() {
    final ServiceRequestContext sctx = serviceRequestContext();
    try (SafeCloseable ignored = sctx.push()) {
        assertCurrentCtx(sctx);
        // The root of ClientRequestContext is sctx.
        final ClientRequestContext cctx = clientRequestContext();
        try (SafeCloseable ignored1 = cctx.push()) {
            assertCurrentCtx(cctx);
            try (SafeCloseable ignored2 = sctx.push()) {
                assertCurrentCtx(sctx);
            }
            assertCurrentCtx(cctx);
        }
        assertCurrentCtx(sctx);
    }
    assertCurrentCtx(null);
}
 
Example 7
Source File: RequestContextExporterTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void shouldUseOwnAttrToStoreInternalState() {
    final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
    final ServiceRequestContext rootCtx = ServiceRequestContext.of(req);
    final RequestContextExporter exporter = RequestContextExporter.builder().build();

    // Create an internal state.
    exporter.export(rootCtx);
    final Object rootState = rootCtx.attr(RequestContextExporter.STATE);
    assertThat(rootState).isNotNull();

    // Create a child context.
    final ClientRequestContext childCtx;
    try (SafeCloseable unused = rootCtx.push()) {
        childCtx = ClientRequestContext.of(req);
    }
    assertThat(childCtx.root()).isSameAs(rootCtx);
    assertThat(childCtx.attr(RequestContextExporter.STATE)).isSameAs(rootState);
    assertThat(childCtx.ownAttr(RequestContextExporter.STATE)).isNull();

    // Make sure a new internal state object is created.
    exporter.export(childCtx);
    final Object childState = childCtx.attr(RequestContextExporter.STATE);
    assertThat(childState).isNotNull().isNotSameAs(rootState);
}
 
Example 8
Source File: DefaultClientRequestContextTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void attrsDoNotIterateRootWhenKeyIsSame() {
    final HttpRequest req = HttpRequest.of(HttpMethod.GET, "/");
    final ServiceRequestContext serviceContext = ServiceRequestContext.of(req);
    try (SafeCloseable ignored = serviceContext.push()) {
        final ClientRequestContext clientContext = ClientRequestContext.of(req);
        final AttributeKey<String> fooKey = AttributeKey.valueOf(DefaultClientRequestContextTest.class,
                                                                 "foo");
        clientContext.setAttr(fooKey, "foo");
        serviceContext.setAttr(fooKey, "bar");
        final Iterator<Entry<AttributeKey<?>, Object>> attrs = clientContext.attrs();
        assertThat(attrs.next().getValue()).isEqualTo("foo");
        assertThat(attrs.hasNext()).isFalse();
    }
}
 
Example 9
Source File: RequestScopedMdcTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void getAll() {
    final ServiceRequestContext ctx = newContext();

    MDC.put("foo", "1");
    MDC.put("bar", "2");
    RequestScopedMdc.put(ctx, "bar", "3");
    RequestScopedMdc.put(ctx, "baz", "4");

    assertThat(MDC.getCopyOfContextMap()).containsOnly(
            Maps.immutableEntry("foo", "1"),
            Maps.immutableEntry("bar", "2"));

    assertThat(RequestScopedMdc.getAll(ctx)).containsOnly(
            Maps.immutableEntry("bar", "3"),
            Maps.immutableEntry("baz", "4"));

    try (SafeCloseable ignored = ctx.push()) {
        // The case where thread-local and request-scoped maps are both non-empty.
        assertThat(MDC.getCopyOfContextMap()).containsOnly(
                Maps.immutableEntry("foo", "1"),
                Maps.immutableEntry("bar", "3"),
                Maps.immutableEntry("baz", "4"));

        // The case where only request-scoped map is available.
        MDC.clear();
        assertThat(MDC.getCopyOfContextMap()).containsOnly(
                Maps.immutableEntry("bar", "3"),
                Maps.immutableEntry("baz", "4"));

        // The case where thread-local and request-scoped maps are both empty.
        RequestScopedMdc.clear(ctx);
        assertThat(MDC.getCopyOfContextMap()).isIn(Collections.emptyMap(), null);

        // The case where only thread-local map is available.
        MDC.put("qux", "5");
        assertThat(MDC.getCopyOfContextMap()).containsOnly(
                Maps.immutableEntry("qux", "5"));
    }
}
 
Example 10
Source File: AnnotatedService.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse convertResponse(ServiceRequestContext ctx,
                                    ResponseHeaders headers,
                                    @Nullable Object result,
                                    HttpHeaders trailers) throws Exception {
    if (result instanceof HttpResponse) {
        return (HttpResponse) result;
    }
    try (SafeCloseable ignored = ctx.push()) {
        for (final ResponseConverterFunction func : functions) {
            try {
                return func.convertResponse(ctx, headers, result, trailers);
            } catch (FallthroughException ignore) {
                // Do nothing.
            } catch (Exception e) {
                throw new IllegalStateException(
                        "Response converter " + func.getClass().getName() +
                        " cannot convert a result to HttpResponse: " + result, e);
            }
        }
    }
    // There is no response converter which is able to convert 'null' result to a response.
    // In this case, a response with the specified HTTP headers would be sent.
    // If you want to force to send '204 No Content' for this case, add
    // 'NullToNoContentResponseConverterFunction' to the list of response converters.
    if (result == null) {
        return HttpResponse.of(headers, HttpData.empty(), trailers);
    }
    throw new IllegalStateException(
            "No response converter exists for a result: " + result.getClass().getName());
}
 
Example 11
Source File: AnnotatedService.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the service method with arguments.
 */
private Object invoke(ServiceRequestContext ctx, HttpRequest req,
                      @Nullable AggregatedHttpRequest aggregatedRequest) {
    try (SafeCloseable ignored = ctx.push()) {
        final ResolverContext resolverContext = new ResolverContext(ctx, req, aggregatedRequest);
        final Object[] arguments = AnnotatedValueResolver.toArguments(resolvers, resolverContext);
        return method.invoke(object, arguments);
    } catch (Throwable cause) {
        return handleExceptionWithContext(exceptionHandler, ctx, req, cause);
    }
}
 
Example 12
Source File: RequestContextStorageCustomizingTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void requestContextStorageDoesNotAffectOtherThread() throws InterruptedException {
    final EventLoop eventLoop = eventLoopExtension.get();
    final ServiceRequestContext ctx = newCtx();

    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    final CountDownLatch latch3 = new CountDownLatch(1);
    try (SafeCloseable ignored = ctx.push()) {
        assertThat(CustomRequestContextStorageProvider.current()).isEqualTo(ctx);
        assertThat(CustomRequestContextStorageProvider.pushCalled()).isOne();

        eventLoop.execute(() -> {
            final ServiceRequestContext ctx1 = newCtx();
            try (SafeCloseable ignored1 = ctx1.push()) {
                assertThat(CustomRequestContextStorageProvider.current()).isEqualTo(ctx1);
                assertThat(CustomRequestContextStorageProvider.pushCalled()).isEqualTo(2);
                latch1.countDown();
                try {
                    latch2.await();
                } catch (InterruptedException e) {
                    // ignore
                }
            }
            assertThat(CustomRequestContextStorageProvider.current()).isNull();
            assertThat(CustomRequestContextStorageProvider.popCalled()).isEqualTo(2);
            latch3.countDown();
        });

        latch1.await();
        assertThat(CustomRequestContextStorageProvider.current()).isEqualTo(ctx);
        assertThat(CustomRequestContextStorageProvider.pushCalled()).isEqualTo(2);
    }
    assertThat(CustomRequestContextStorageProvider.current()).isNull();
    assertThat(CustomRequestContextStorageProvider.popCalled()).isOne();
    latch2.countDown();
    latch3.await();
}
 
Example 13
Source File: THttpService.java    From armeria with Apache License 2.0 5 votes vote down vote up
private void invoke(
        ServiceRequestContext ctx, SerializationFormat serializationFormat, int seqId,
        ThriftFunction func, RpcRequest call, CompletableFuture<HttpResponse> res) {

    final RpcResponse reply;

    try (SafeCloseable ignored = ctx.push()) {
        reply = unwrap().serve(ctx, call);
    } catch (Throwable cause) {
        handleException(ctx, RpcResponse.ofFailure(cause), res, serializationFormat, seqId, func, cause);
        return;
    }

    reply.handle((result, cause) -> {
        if (func.isOneWay()) {
            handleOneWaySuccess(ctx, reply, res, serializationFormat);
            return null;
        }

        if (cause != null) {
            handleException(ctx, reply, res, serializationFormat, seqId, func, cause);
            return null;
        }

        try {
            handleSuccess(ctx, reply, res, serializationFormat, seqId, func, result);
        } catch (Throwable t) {
            handleException(ctx, RpcResponse.ofFailure(t), res, serializationFormat, seqId, func, t);
        }

        return null;
    }).exceptionally(CompletionActions::log);
}
 
Example 14
Source File: RequestScopedMdcTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void get() {
    final ServiceRequestContext ctx = newContext();
    RequestScopedMdc.put(ctx, "foo", "1");
    assertThat(RequestScopedMdc.get(ctx, "foo")).isEqualTo("1");
    assertThat(MDC.get("foo")).isNull();

    try (SafeCloseable ignored = ctx.push()) {
        assertThat(MDC.get("foo")).isEqualTo("1");
        // Request-scoped property should have priority over thread-local one.
        MDC.put("foo", "2");
        assertThat(MDC.get("foo")).isEqualTo("1");

        // A client context should expose the properties from the root context.
        final ClientRequestContext cctx = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));
        assertThat(cctx.root()).isSameAs(ctx);
        assertThat(RequestScopedMdc.get(cctx, "foo")).isEqualTo("1");

        // A client context can override the property from the root context,
        // but it shouldn't affect the root context's own property.
        RequestScopedMdc.put(cctx, "foo", "3");
        assertThat(RequestScopedMdc.get(ctx, "foo")).isEqualTo("1");
        assertThat(RequestScopedMdc.get(cctx, "foo")).isEqualTo("3");

        try (SafeCloseable ignored2 = cctx.push()) {
            // If both ctx and cctx do not have 'foo' set, thread-local property should be retrieved.
            RequestScopedMdc.remove(ctx, "foo");
            RequestScopedMdc.remove(cctx, "foo");
            assertThat(MDC.get("foo")).isEqualTo("2");
        }
    }
}
 
Example 15
Source File: RequestContextStorageCustomizingTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void hook() {
    final AtomicBoolean pushed = new AtomicBoolean();
    final AtomicBoolean popped = new AtomicBoolean();
    final AtomicBoolean got = new AtomicBoolean();

    RequestContextStorage.hook(delegate -> new RequestContextStorageWrapper(delegate) {
        @Nullable
        @Override
        public <T extends RequestContext> T push(RequestContext toPush) {
            pushed.set(true);
            return super.push(toPush);
        }

        @Override
        public void pop(RequestContext current, @Nullable RequestContext toRestore) {
            popped.set(true);
            super.pop(current, toRestore);
        }

        @Nullable
        @Override
        public <T extends RequestContext> T currentOrNull() {
            got.set(true);
            return super.currentOrNull();
        }
    });

    try {
        final ServiceRequestContext ctx = newCtx();

        assertThat(pushed).isFalse();
        assertThat(popped).isFalse();
        assertThat(got).isFalse();

        try (SafeCloseable ignored = ctx.push()) {
            assertThat(pushed).isTrue();
            assertThat(popped).isFalse();
            assertThat(got).isFalse();

            assertThat(ServiceRequestContext.current()).isSameAs(ctx);
            assertThat(popped).isFalse();
            assertThat(got).isTrue();
        }

        assertThat(popped).isTrue();
    } finally {
        RequestContextStorage.hook(storage -> storage.as(CustomRequestContextStorage.class));
    }
}
 
Example 16
Source File: RequestScopedMdcTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void getAllNested() {
    MDC.put("foo", "1");
    MDC.put("bar", "2");

    final ServiceRequestContext ctx = newContext();
    try (SafeCloseable ignored = ctx.push()) {
        final ClientRequestContext cctx = ClientRequestContext.of(HttpRequest.of(HttpMethod.GET, "/"));

        // When the root context map exists but it's empty:
        try (SafeCloseable ignored2 = cctx.push()) {
            assertThat(RequestScopedMdc.getAll(cctx)).isEmpty();
            assertThat(MDC.getCopyOfContextMap()).containsOnly(
                    Maps.immutableEntry("foo", "1"),
                    Maps.immutableEntry("bar", "2"));
        }

        // When the root context map is not empty:
        RequestScopedMdc.put(ctx, "bar", "3");
        RequestScopedMdc.put(ctx, "baz", "4");
        try (SafeCloseable ignored2 = cctx.push()) {
            // root context's properties should be retrieved.
            assertThat(RequestScopedMdc.getAll(cctx)).containsOnly(
                    Maps.immutableEntry("bar", "3"),
                    Maps.immutableEntry("baz", "4"));
            assertThat(MDC.getCopyOfContextMap()).containsOnly(
                    Maps.immutableEntry("foo", "1"),
                    Maps.immutableEntry("bar", "3"),
                    Maps.immutableEntry("baz", "4"));

            // root context's properties should be overwritten by own properties.
            RequestScopedMdc.put(cctx, "baz", "5");
            RequestScopedMdc.put(cctx, "qux", "6");

            assertThat(RequestScopedMdc.getAll(cctx)).containsOnly(
                    Maps.immutableEntry("bar", "3"),
                    Maps.immutableEntry("baz", "5"),
                    Maps.immutableEntry("qux", "6"));
            assertThat(MDC.getCopyOfContextMap()).containsOnly(
                    Maps.immutableEntry("foo", "1"),
                    Maps.immutableEntry("bar", "3"),
                    Maps.immutableEntry("baz", "5"),
                    Maps.immutableEntry("qux", "6"));
        }
    }
}
 
Example 17
Source File: FramedGrpcService.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Nullable
private <I, O> ArmeriaServerCall<I, O> startCall(
        String fullMethodName,
        ServerMethodDefinition<I, O> methodDef,
        ServiceRequestContext ctx,
        HttpHeaders headers,
        HttpResponseWriter res,
        SerializationFormat serializationFormat) {
    final MethodDescriptor<I, O> methodDescriptor = methodDef.getMethodDescriptor();
    final ArmeriaServerCall<I, O> call = new ArmeriaServerCall<>(
            headers,
            methodDescriptor,
            compressorRegistry,
            decompressorRegistry,
            res,
            maxInboundMessageSizeBytes,
            maxOutboundMessageSizeBytes,
            ctx,
            serializationFormat,
            jsonMarshallers.get(methodDescriptor.getServiceName()),
            unsafeWrapRequestBuffers,
            useBlockingTaskExecutor,
            defaultHeaders.get(serializationFormat));
    final ServerCall.Listener<I> listener;
    try (SafeCloseable ignored = ctx.push()) {
        listener = methodDef.getServerCallHandler().startCall(call, MetadataUtil.copyFromHeaders(headers));
    } catch (Throwable t) {
        call.setListener(new EmptyListener<>());
        call.close(GrpcStatus.fromThrowable(t), new Metadata());
        logger.warn(
                "Exception thrown from streaming request stub method before processing any request data" +
                " - this is likely a bug in the stub implementation.");
        return null;
    }
    if (listener == null) {
        // This will never happen for normal generated stubs but could conceivably happen for manually
        // constructed ones.
        throw new NullPointerException(
                "startCall() returned a null listener for method " + fullMethodName);
    }
    call.setListener(listener);
    return call;
}
 
Example 18
Source File: BraveServiceTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static RequestLog testServiceInvocation(SpanHandler spanHandler,
                                                CurrentTraceContext traceContext,
                                                float samplingRate) throws Exception {
    final Tracing tracing = Tracing.newBuilder()
                                   .localServiceName(TEST_SERVICE)
                                   .addSpanHandler(spanHandler)
                                   .currentTraceContext(traceContext)
                                   .sampler(Sampler.create(samplingRate))
                                   .build();

    final HttpTracing httpTracing = HttpTracing.newBuilder(tracing)
                                               .serverRequestParser(ArmeriaHttpServerParser.get())
                                               .serverResponseParser(ArmeriaHttpServerParser.get())
                                               .build();

    final HttpRequest req = HttpRequest.of(RequestHeaders.of(HttpMethod.POST, "/hello/trustin",
                                                             HttpHeaderNames.SCHEME, "http",
                                                             HttpHeaderNames.AUTHORITY, "foo.com"));
    final ServiceRequestContext ctx = ServiceRequestContext.builder(req).build();
    final RpcRequest rpcReq = RpcRequest.of(HelloService.Iface.class, "hello", "trustin");
    final HttpResponse res = HttpResponse.of(HttpStatus.OK);
    final RpcResponse rpcRes = RpcResponse.of("Hello, trustin!");
    final RequestLogBuilder logBuilder = ctx.logBuilder();
    logBuilder.requestContent(rpcReq, req);
    logBuilder.endRequest();

    try (SafeCloseable ignored = ctx.push()) {
        final HttpService delegate = mock(HttpService.class);
        final BraveService service = BraveService.newDecorator(httpTracing).apply(delegate);
        when(delegate.serve(ctx, req)).thenReturn(res);

        // do invoke
        service.serve(ctx, req);

        verify(delegate, times(1)).serve(eq(ctx), eq(req));
    }

    logBuilder.responseHeaders(ResponseHeaders.of(HttpStatus.OK));
    logBuilder.responseFirstBytesTransferred();
    logBuilder.responseContent(rpcRes, res);
    logBuilder.endResponse();
    return ctx.log().ensureComplete();
}
 
Example 19
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void testServiceContextWithFullLogs() throws Exception {
    final List<ILoggingEvent> events = prepare(a -> {
        // Export all properties.
        for (BuiltInProperty p : BuiltInProperty.values()) {
            a.addBuiltIn(p);
        }
        // .. and an attribute.
        a.addAttribute("attrs.my_attr_name", MY_ATTR, new CustomObjectNameStringifier());
        a.addAttribute("attrs.my_attr_value", MY_ATTR, new CustomObjectValueStringifier());
        // .. and some HTTP headers.
        a.addRequestHeader(HttpHeaderNames.USER_AGENT);
        a.addResponseHeader(HttpHeaderNames.DATE);
    });

    final ServiceRequestContext ctx = newServiceContext("/foo", "bar=baz");
    try (SafeCloseable ignored = ctx.push()) {
        final RequestLogBuilder log = ctx.logBuilder();
        log.serializationFormat(ThriftSerializationFormats.BINARY);
        log.requestLength(64);
        log.requestHeaders(RequestHeaders.of(HttpMethod.GET, "/foo?bar=baz",
                                             HttpHeaderNames.USER_AGENT, "some-client"));
        log.requestContent(RPC_REQ, THRIFT_CALL);
        log.endRequest();
        log.responseLength(128);
        log.responseHeaders(ResponseHeaders.of(HttpStatus.OK,
                                               HttpHeaderNames.DATE, "some-date"));
        log.responseContent(RPC_RES, THRIFT_REPLY);
        log.endResponse();

        final ILoggingEvent e = log(events);
        final Map<String, String> mdc = e.getMDCPropertyMap();
        assertThat(mdc).containsEntry("local.host", "server.com")
                       .containsEntry("local.ip", "5.6.7.8")
                       .containsEntry("local.port", "8080")
                       .containsEntry("remote.host", "client.com")
                       .containsEntry("remote.ip", "1.2.3.4")
                       .containsEntry("remote.port", "5678")
                       .containsEntry("client.ip", "9.10.11.12")
                       .containsEntry("req.direction", "INBOUND")
                       .containsEntry("req.authority", "server.com:8080")
                       .containsEntry("req.method", "GET")
                       .containsEntry("req.name", RPC_REQ.method())
                       .containsEntry("req.serviceName", RPC_REQ.serviceType().getName())
                       .containsEntry("req.path", "/foo")
                       .containsEntry("req.query", "bar=baz")
                       .containsEntry("scheme", "tbinary+h2")
                       .containsEntry("req.content_length", "64")
                       .containsEntry("req.content", "[world]")
                       .containsEntry("res.status_code", "200")
                       .containsEntry("res.content_length", "128")
                       .containsEntry("res.content", "Hello, world!")
                       .containsEntry("req.headers.user-agent", "some-client")
                       .containsEntry("res.headers.date", "some-date")
                       .containsEntry("tls.session_id", "0101020305080d15")
                       .containsEntry("tls.proto", "TLSv1.2")
                       .containsEntry("tls.cipher", "some-cipher")
                       .containsEntry("attrs.my_attr_name", "some-name")
                       .containsEntry("attrs.my_attr_value", "some-value")
                       .containsKey("req.id")
                       .containsKey("elapsed_nanos")
                       .hasSize(29);
    }
}
 
Example 20
Source File: RequestContextExportingAppenderTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Test
void testServiceContextWithMinimalLogs() throws Exception {
    final List<ILoggingEvent> events = prepare(a -> {
        // Export all properties.
        for (BuiltInProperty p : BuiltInProperty.values()) {
            a.addBuiltIn(p);
        }
    });

    final ServiceRequestContext ctx = newServiceContext("/foo", "name=alice");
    try (SafeCloseable ignored = ctx.push()) {
        final RequestLogBuilder log = ctx.logBuilder();
        log.endRequest();
        log.endResponse();

        final ILoggingEvent e = log(events);
        final Map<String, String> mdc = e.getMDCPropertyMap();
        assertThat(mdc).containsEntry("local.host", "server.com")
                       .containsEntry("local.ip", "5.6.7.8")
                       .containsEntry("local.port", "8080")
                       .containsEntry("remote.host", "client.com")
                       .containsEntry("remote.ip", "1.2.3.4")
                       .containsEntry("remote.port", "5678")
                       .containsEntry("client.ip", "9.10.11.12")
                       .containsEntry("req.direction", "INBOUND")
                       .containsEntry("req.authority", "server.com:8080")
                       .containsEntry("req.name", "GET")
                       .containsEntry("req.serviceName", ctx.config().service().getClass().getName())
                       .containsEntry("req.method", "GET")
                       .containsEntry("req.path", "/foo")
                       .containsEntry("req.query", "name=alice")
                       .containsEntry("scheme", "none+h2")
                       .containsEntry("req.content_length", "0")
                       .containsEntry("res.status_code", "0")
                       .containsEntry("res.content_length", "0")
                       .containsEntry("tls.session_id", "0101020305080d15")
                       .containsEntry("tls.proto", "TLSv1.2")
                       .containsEntry("tls.cipher", "some-cipher")
                       .containsKey("elapsed_nanos")
                       .containsKey("req.id")
                       .hasSize(23);
    }
}