Richard Fergie
Richard Fergie

Reputation: 63

Logging Response time in Yesod

I would like to log the amount of time a request takes in Yesod.

I think I can do this with something like the following:

yesodMiddleware handler = do
          t1 <- liftIO $ getCurrentTime
          addHeader "Vary" "Accept, Accept-Language"
          authorizationCheck
          h <- handler --may need to seq this?
          t2 <- liftIO $ getCurrentTime
          -- unsure about this part
          $(logInfo) "Some string that includes t2-t1"
          h

Am I missing something? Is there a better way?

There used to be a "timed" function in Yesod.Logger but I can't figure out where it has gone

Upvotes: 2

Views: 632

Answers (1)

MaxGabriel
MaxGabriel

Reputation: 7705

I created a small Wai Middleware you can use to time requests:

-- Network/Wai/Middleware/RequestTimer.hs

module Network.Wai.Middleware.RequestTimer (
    requestTimer,
    ) where

import Prelude
import Network.Wai
import Data.Time (getCurrentTime, diffUTCTime)

requestTimer :: Middleware
requestTimer app req sendResponse = do
    t0 <- getCurrentTime
    app req $ \rsp -> do
        t1 <- getCurrentTime
        putStrLn $ "The request time is " ++ (show $ diffUTCTime t1 t0)
        sendResponse rsp

I then added this module to exposed-modules in my .cabal file

library
    exposed-modules: Application
                     Foundation
                     Import
                     -- lots more here
                     Network.Wai.Middleware.RequestTimer

Then in Application.hs I apply the middleware:

import Network.Wai.Middleware.RequestTimer

makeApplication :: AppConfig DefaultEnv Extra -> IO Application
makeApplication conf = do
    foundation <- makeFoundation conf

    -- Create the WAI application and apply middlewares
    app <- toWaiAppPlain foundation
    return $ requestTimer app -- Note that you can chain multiple middlewares together here.

Now when making requests, you'll see

The request time is 3.014697s

printed in console.

I'd like to explain the middleware more but I honestly have no idea how it's working—I'm just cropping stuff from RequestLogger and the other Wai middlewares. Hopefully I can get a better understanding of it tonight and come back and edit this answer with details, but I'm about to be late to work.

Upvotes: 2

Related Questions