How To Implement logRequestResponse in Spray


Spray has the feature to log request and response of every route through logRequestResponse. We needn’t to add log in each route because it could be done from a single place. This also helps to maintain clean code.
Please see below example:-

class HubServices extends Actor with HubRoutes {
  def actorRefFactory: ActorContext = context
  // logs just the request method and response status at info level
  def requestMethodAndResponseStatusAsInfo(req: HttpRequest): Any => Option[LogEntry] = {
    case res: HttpResponse => Some(LogEntry(req.method + ":" + req.uri + ":" + res.message.status, InfoLevel))
    case _ => None // other kind of responses
  }

  def routeWithLogging = logRequestResponse(requestMethodAndResponseStatusAsInfo _)(hubRoutes)

  def receive: Receive = runRoute(routeWithLogging)
}

Now execute sbt run, run the http://localhost:8080/module/BANG from browser and see the log in console.

[INFO] [01/08/2015 22:00:50.925] [ForkJoinPool-3-worker-7] [akka://HubActorSystem/user/hubServices] GET:http://localhost:8080/module/BANG:200 OK

We could change log format and level, depending on the requirement. For complete example, you can pull the code from spray-akka-starter.

About Ayush Mishra

Ayush is the Sr. Software Consultant @ Knoldus Software LLP. In his 5 years of experience he has become developer with proven experience in architecting and developing web applications. Ayush has a Masters in Computer Application from U.P. Technical University, Ayush is a strong-willed and self-motivated professional who takes deep care in adhering to quality norms within projects. He is capable of managing challenging projects with remarkable deadline sensitivity without compromising code quality. .
This entry was posted in Agile, Akka, Scala, Web and tagged , , , . Bookmark the permalink.

3 Responses to How To Implement logRequestResponse in Spray

  1. Pingback: Ceiba3D Studio | How To Implement logRequestResponse in Spray

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s