Drop-wizard request response logging

懵懂的女人 提交于 2019-12-23 01:57:39

问题


I want to log each request and response in dropwizard into different files. For example I want all the requests to be logged in /var/log/applicationname-request.log and all responses into /var/log/applicationname-response.log

Is there any way in which we can achieve the same?


回答1:


Unfortunately DropWizard currently doesn't support this natively. See this lively discussion for more information.

Fortunately there's a workaround if you're willing to forego configuring logging with DropWizard all together. Somewhere in your run method call the following code to reset the logging and reconfigure it using sfl4j's standard mechanism:

LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();
context.reset();
ContextInitializer initializer = new ContextInitializer(context);
initializer.autoConfig();

Then you can configure logging by adding logback.xml to your classpath and configuring it something like this:

<configuration>
  <appender name="REQUEST" class="ch.qos.logback.core.FileAppender">
    <file>/var/log/applicationname-request.log</file>
    <append>false</append>
    <encoder>
      <pattern>%-5relative %-5level %logger{35} - %msg%n</pattern>
    </encoder>
  </appender>

  <appender name="RESPONSE" class="ch.qos.logback.core.FileAppender">
    <file>/var/log/applicationame-response.log</file>
    <append>false</append>
    <encoder>
      <pattern>%-5relative %-5level %logger{35} - %msg%n</pattern>
    </encoder>
  </appender>

  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <encoder>
      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
  </appender>

  <logger name="org.example.request">
    <level value="DEBUG" />
    <appender-ref ref="REQUEST" />
  </logger>

  <logger name="org.example.response">
    <level value="DEBUG" />
    <appender-ref ref="RESPONSE" />
  </logger>

  <root level="warn">
    <appender-ref ref="STDOUT" />
  </root>
</configuration>

Then you can grab those corresponding loggers in your resource and log away:

static final Logger REQUEST_LOG = LoggerFactory.getLogger("org.example.request");
static final Logger RESPONSE_LOG = LoggerFactory.getLogger("org.example.response");


来源:https://stackoverflow.com/questions/27356918/drop-wizard-request-response-logging

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!