Search in sources :

Example 6 with CustomRequestLog

use of org.eclipse.jetty.server.CustomRequestLog in project dropwizard by dropwizard.

the class LogbackClassicRequestLogFactory method build.

@Override
public RequestLog build(String name) {
    final Logger logger = (Logger) LoggerFactory.getLogger("http.request");
    logger.setAdditive(false);
    final LoggerContext context = logger.getLoggerContext();
    final LevelFilterFactory<ILoggingEvent> levelFilterFactory = new NullLevelFilterFactory<>();
    final AsyncAppenderFactory<ILoggingEvent> asyncAppenderFactory = new AsyncLoggingEventAppenderFactory();
    final LayoutFactory<ILoggingEvent> layoutFactory = (c, tz) -> new RequestLogLayout(c);
    final AppenderAttachableImpl<ILoggingEvent> attachable = new AppenderAttachableImpl<>();
    for (AppenderFactory<ILoggingEvent> appender : appenders) {
        attachable.addAppender(appender.build(context, name, layoutFactory, levelFilterFactory, asyncAppenderFactory));
    }
    return new CustomRequestLog(new DropwizardSlf4jRequestLogWriter(attachable), ClassicLogFormat.pattern(timeZone));
}
Also used : Context(ch.qos.logback.core.Context) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) ConsoleAppenderFactory(io.dropwizard.logging.ConsoleAppenderFactory) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) LoggerFactory(org.slf4j.LoggerFactory) AsyncLoggingEventAppenderFactory(io.dropwizard.logging.async.AsyncLoggingEventAppenderFactory) LoggerContext(ch.qos.logback.classic.LoggerContext) Valid(javax.validation.Valid) JsonTypeName(com.fasterxml.jackson.annotation.JsonTypeName) RequestLogFactory(io.dropwizard.request.logging.RequestLogFactory) NullLevelFilterFactory(io.dropwizard.logging.filter.NullLevelFilterFactory) Map(java.util.Map) JsonIgnore(com.fasterxml.jackson.annotation.JsonIgnore) CoreConstants(ch.qos.logback.core.CoreConstants) PatternLayoutBase(ch.qos.logback.core.pattern.PatternLayoutBase) AppenderAttachableImpl(ch.qos.logback.core.spi.AppenderAttachableImpl) RequestLog(org.eclipse.jetty.server.RequestLog) LayoutFactory(io.dropwizard.logging.layout.LayoutFactory) TimeZone(java.util.TimeZone) AppenderFactory(io.dropwizard.logging.AppenderFactory) LevelFilterFactory(io.dropwizard.logging.filter.LevelFilterFactory) NotNull(javax.validation.constraints.NotNull) List(java.util.List) Logger(ch.qos.logback.classic.Logger) CustomRequestLog(org.eclipse.jetty.server.CustomRequestLog) AsyncAppenderFactory(io.dropwizard.logging.async.AsyncAppenderFactory) Collections(java.util.Collections) CustomRequestLog(org.eclipse.jetty.server.CustomRequestLog) NullLevelFilterFactory(io.dropwizard.logging.filter.NullLevelFilterFactory) AppenderAttachableImpl(ch.qos.logback.core.spi.AppenderAttachableImpl) Logger(ch.qos.logback.classic.Logger) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) LoggerContext(ch.qos.logback.classic.LoggerContext) AsyncLoggingEventAppenderFactory(io.dropwizard.logging.async.AsyncLoggingEventAppenderFactory)

Example 7 with CustomRequestLog

use of org.eclipse.jetty.server.CustomRequestLog in project dropwizard by dropwizard.

the class LogbackClassicRequestLogFactoryTest method testLogFormat.

@Test
void testLogFormat() throws Exception {
    final LogbackClassicRequestLogFactory factory = new LogbackClassicRequestLogFactory();
    @SuppressWarnings("unchecked") final Appender<ILoggingEvent> appender = mock(Appender.class);
    final Request request = mock(Request.class);
    final Response response = mock(Response.class, RETURNS_DEEP_STUBS);
    final HttpChannelState channelState = mock(HttpChannelState.class);
    factory.setAppenders(Collections.singletonList((context, applicationName, layoutFactory, levelFilterFactory, asyncAppenderFactory) -> appender));
    final String tz = TimeZone.getAvailableIDs((int) TimeUnit.HOURS.toMillis(-5))[0];
    factory.setTimeZone(TimeZone.getTimeZone(tz));
    CustomRequestLog logger = null;
    try {
        when(channelState.isInitial()).thenReturn(true);
        when(request.getRemoteHost()).thenReturn("10.0.0.1");
        // Jetty log format compares against System.currentTimeMillis, so there
        // isn't a way for us to set our own clock
        when(request.getTimeStamp()).thenReturn(System.currentTimeMillis());
        when(request.getMethod()).thenReturn("GET");
        when(request.getRequestURI()).thenReturn("/test/things");
        when(request.getProtocol()).thenReturn("HTTP/1.1");
        when(request.getHttpChannelState()).thenReturn(channelState);
        when(response.getCommittedMetaData().getStatus()).thenReturn(200);
        when(response.getHttpChannel().getBytesWritten()).thenReturn(8290L);
        final ArgumentCaptor<ILoggingEvent> captor = ArgumentCaptor.forClass(ILoggingEvent.class);
        logger = (CustomRequestLog) factory.build("my-app");
        logger.log(request, response);
        verify(appender, timeout(1000)).doAppend(captor.capture());
        final ILoggingEvent event = captor.getValue();
        assertThat(event.getFormattedMessage()).startsWith("10.0.0.1").doesNotContain("%").contains("\"GET /test/things HTTP/1.1\"").contains("-0500");
    } catch (Exception e) {
        if (logger != null) {
            logger.stop();
        }
        throw e;
    }
}
Also used : Response(org.eclipse.jetty.server.Response) Request(org.eclipse.jetty.server.Request) Response(org.eclipse.jetty.server.Response) ConsoleAppenderFactory(io.dropwizard.logging.ConsoleAppenderFactory) BeforeEach(org.junit.jupiter.api.BeforeEach) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SyslogAppenderFactory(io.dropwizard.logging.SyslogAppenderFactory) Mockito.timeout(org.mockito.Mockito.timeout) RequestLogFactory(io.dropwizard.request.logging.RequestLogFactory) ArgumentCaptor(org.mockito.ArgumentCaptor) HttpChannelState(org.eclipse.jetty.server.HttpChannelState) Appender(ch.qos.logback.core.Appender) Jackson(io.dropwizard.jackson.Jackson) YamlConfigurationFactory(io.dropwizard.configuration.YamlConfigurationFactory) RETURNS_DEEP_STUBS(org.mockito.Mockito.RETURNS_DEEP_STUBS) BaseValidator(io.dropwizard.validation.BaseValidator) TimeZone(java.util.TimeZone) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) DiscoverableSubtypeResolver(io.dropwizard.jackson.DiscoverableSubtypeResolver) ResourceConfigurationSourceProvider(io.dropwizard.configuration.ResourceConfigurationSourceProvider) FileAppenderFactory(io.dropwizard.logging.FileAppenderFactory) Mockito.when(org.mockito.Mockito.when) BootstrapLogging(io.dropwizard.logging.BootstrapLogging) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) TimeUnit(java.util.concurrent.TimeUnit) CustomRequestLog(org.eclipse.jetty.server.CustomRequestLog) Collections(java.util.Collections) Mockito.mock(org.mockito.Mockito.mock) CustomRequestLog(org.eclipse.jetty.server.CustomRequestLog) HttpChannelState(org.eclipse.jetty.server.HttpChannelState) Request(org.eclipse.jetty.server.Request) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) Test(org.junit.jupiter.api.Test)

Example 8 with CustomRequestLog

use of org.eclipse.jetty.server.CustomRequestLog in project kafka by apache.

the class JsonRestServer method start.

/**
 * Start the JsonRestServer.
 *
 * @param resources         The path handling resources to register.
 */
public void start(Object... resources) {
    log.info("Starting REST server");
    ResourceConfig resourceConfig = new ResourceConfig();
    resourceConfig.register(new JacksonJsonProvider(JsonUtil.JSON_SERDE));
    for (Object resource : resources) {
        resourceConfig.register(resource);
        log.info("Registered resource {}", resource);
    }
    resourceConfig.register(RestExceptionMapper.class);
    ServletContainer servletContainer = new ServletContainer(resourceConfig);
    ServletHolder servletHolder = new ServletHolder(servletContainer);
    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    context.addServlet(servletHolder, "/*");
    RequestLogHandler requestLogHandler = new RequestLogHandler();
    Slf4jRequestLogWriter slf4jRequestLogWriter = new Slf4jRequestLogWriter();
    slf4jRequestLogWriter.setLoggerName(JsonRestServer.class.getCanonicalName());
    CustomRequestLog requestLog = new CustomRequestLog(slf4jRequestLogWriter, CustomRequestLog.EXTENDED_NCSA_FORMAT + " %{ms}T");
    requestLogHandler.setRequestLog(requestLog);
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] { context, new DefaultHandler(), requestLogHandler });
    StatisticsHandler statsHandler = new StatisticsHandler();
    statsHandler.setHandler(handlers);
    jettyServer.setHandler(statsHandler);
    /* Needed for graceful shutdown as per `setStopTimeout` documentation */
    jettyServer.setStopTimeout(GRACEFUL_SHUTDOWN_TIMEOUT_MS);
    jettyServer.setStopAtShutdown(true);
    try {
        jettyServer.start();
    } catch (Exception e) {
        throw new RuntimeException("Unable to start REST server", e);
    }
    log.info("REST server listening at " + jettyServer.getURI());
}
Also used : CustomRequestLog(org.eclipse.jetty.server.CustomRequestLog) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) JacksonJsonProvider(com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider) Slf4jRequestLogWriter(org.eclipse.jetty.server.Slf4jRequestLogWriter) IOException(java.io.IOException) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) ServletContainer(org.glassfish.jersey.servlet.ServletContainer) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) ResourceConfig(org.glassfish.jersey.server.ResourceConfig) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler)

Aggregations

CustomRequestLog (org.eclipse.jetty.server.CustomRequestLog)8 RequestLogWriter (org.eclipse.jetty.server.RequestLogWriter)3 Test (org.junit.jupiter.api.Test)3 ILoggingEvent (ch.qos.logback.classic.spi.ILoggingEvent)2 JacksonJsonProvider (com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider)2 ConsoleAppenderFactory (io.dropwizard.logging.ConsoleAppenderFactory)2 RequestLogFactory (io.dropwizard.request.logging.RequestLogFactory)2 IOException (java.io.IOException)2 Collections (java.util.Collections)2 TimeZone (java.util.TimeZone)2 JettyWebServer (org.springframework.boot.web.embedded.jetty.JettyWebServer)2 Logger (ch.qos.logback.classic.Logger)1 LoggerContext (ch.qos.logback.classic.LoggerContext)1 Appender (ch.qos.logback.core.Appender)1 Context (ch.qos.logback.core.Context)1 CoreConstants (ch.qos.logback.core.CoreConstants)1 PatternLayoutBase (ch.qos.logback.core.pattern.PatternLayoutBase)1 AppenderAttachableImpl (ch.qos.logback.core.spi.AppenderAttachableImpl)1 JsonIgnore (com.fasterxml.jackson.annotation.JsonIgnore)1 JsonProperty (com.fasterxml.jackson.annotation.JsonProperty)1