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?
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");