So far, you’ve learned how to create a reference that has the lifetime of some single IO action, but in some cases it would be convenient to have a reference that is available to your entire program, and for the lifetime of the application. Although global mutable data is often cast as inadvisable at best, and an antipattern at worst, there are situations where module-level global variables can be quite useful. One of these situations is when dealing with global concerns like logging or metrics. In this section, we’ll look at how to build a minimal metrics system that you can use to instrument a program.

Let’s start by defining a new record, AppMetrics , that we’ll use to hold all of our different metrics. For our simplified application, we’re going to hold three different metrics: successCount will count all of the times a function call succeeded, failureCount will return all the time a function failed, and callDuration will count the total amount of time that we have spent in each function. We’ll be using Data.Map.Strict from the containers library for the examples in this section. A Map is a dictionary that lets us efficiently associate keys with values. For example, we’ll use a Map String Int to let us efficiently look up Int values given String keys:

​  ​ module ​ ​ Metrics ​ ​ where ​
​  ​ import ​ ​ qualified ​ ​ Data.Map.Strict ​ ​ as ​ Map
​  ​ import ​ ​ Data.IORef ​
​  
​  ​ data ​ ​ AppMetrics ​ = ​ AppMetrics ​
​  { successCount :: ​ Int ​
​  , failureCount :: ​ Int ​
​  , callDuration :: ​ Map ​.​ Map ​ ​ String ​ ​ Int ​
​  } ​ deriving ​ (​ Eq ​, ​ Show ​)

In a real application, you would typically store the set of metrics dynamically rather than choosing a fixed set of things to measure upfront, but for this minimal example we’ll stick with a few prechosen metrics.

Metrics present an interesting challenge to us when we’re trying to design our software. Metrics must be mutable, since their entire purpose is to change as things in our program happen. They must also be available throughout our entire program, since we will ideally be instrumenting much of our application to track what is happening. It is inconvenient to pass around a pure metrics value that we return along with values in our program, so we’d like to have metrics that exist separately from our main application. These constraints make them good candidates for existing as an IORef.

Let’s look at an example of how we might use an IORef to implement metrics for a small sample program.

We know that we want to have our metrics be global to our module so that we can track metrics from any function, and we know that our metrics value needs to be mutable, so a reasonable starting point might be to create a top-level IORef:

​  metrics :: ​ IO ​ (​ IORef ​ ​ AppMetrics ​)
​  metrics = newIORef ​ AppMetrics ​
​  { successCount = 0
​  , failureCount = 0
​  , callDuration = ​ Map ​.empty
​  }

Next, for the sake of testing, let’s write a function that can print some metrics out to the screen so that we can easily verify that our metrics are working as expected:

​  printMetrics :: ​ IO ​ ()
​  printMetrics =
​  metrics >>= readIORef >>= print

We’ll also need some functions to update metrics. For the moment, let’s be optimistic and we’ll just implement a function to increment the success counter:

​  incrementSuccess :: ​ IO ​ ()
​  incrementSuccess =
​  metrics >>= flip modifyIORef incrementSuccess
​  ​ where ​
​  incrementSuccess m =
​  m { successCount = 1 + successCount m }

Finally, let’s write a couple of functions so that we can test our metrics out:

​  successfullyPrintHello :: ​ IO ​ ()
​  successfullyPrintHello = ​ do ​
​  print ​ "Hello" ​
​  incrementSuccess
​  
​  printHelloAndMetrics = ​ do ​
​  successfullyPrintHello
​  printMetrics

We can load our module into ghci to test it:

​  ​ λ ​ printHelloAndMetrics
​  ​ "Hello" ​
​  ​ AppMetrics ​
​  {successCount = 0, failureCount = 0, callDuration = fromList ​ [] ​}

You might notice that this approach didn’t work at all! What happened?

Let’s take another look at our metrics function:

​  metrics :: ​ IO ​ (​ IORef ​ ​ AppMetrics ​)
​  metrics = newIORef ​ AppMetrics ​
​  { successCount = 0
​  , failureCount = 0
​  , callDuration = ​ Map ​.empty
​  }

The problem that we have right now is that metrics is a an IO action, and each time we run that action we get a new reference that is initialized with an empty set of metrics. In other words, every time we pass metrics into (>>=) or get a metrics value in a do block using <- , we’re going to get a brand new empty collection metrics. Instead of getting the metrics when we need it by calling metrics we’re going to need to create a single source of truth for metrics and pass it around through all of our computations.

We could, of course, directly pass around our IORef , but that leaks an implementation detail that we might want to change later. Instead, let’s create a new type that represents an IORef that holds some metrics data.

At this point, we have two choices for how we could do this. One option would be to create a record that holds separate references to each of the things we’d like to potentially update. In this case, we’d replace our existing AppMetrics type with one like this:

​  ​ data ​ ​ AppMetrics ​
​  { successCount :: ​ IORef ​ ​ Int ​
​  , failureCount :: ​ IORef ​ ​ Int ​
​  , callDuration :: ​ IORef ​ (​ Map ​.​ Map ​ ​ String ​ ​ Int ​)
​  }

This can be a great approach to take when you might want to have different threads updating metrics independently, or when want to pull out specific metrics and pass them around while hiding the rest of the metrics from some particular function. The down side to this approach is that it can be a little bit more work to manage, because we now have to implementing updating each reference separately. This can introduce performance problems if you have a lot of functions that want to work with several different metrics, since you’ll have to read and write multiple references for each metrics update.

An alternative approach would be to keep our original AppMetrics definition, and add a newtype wrapper around a reference to the metrics:

​  ​ newtype ​ ​ Metrics ​ = ​ Metrics ​ { appMetricsStore :: ​ IORef ​ ​ AppMetrics ​ }

This approach makes it more efficient to update the entire set of metrics at once, but at the cost of some degree of parallelism. For now, we’ll stick with our original AppMetrics definition and the Metrics wrapper, because it will let us write a bit less code as we’re working through the examples. In an exercise at the end of this chapter, you’ll have an opportunity to refactor some of your metrics code to make use of multiple references.

To go along with our newtype wrapper, let’s rename metrics and have it actually return a Metrics value:

​  newMetrics :: ​ IO ​ ​ Metrics ​
​  newMetrics =
​  ​ let ​
​  emptyAppMetrics = ​ AppMetrics ​
​  { successCount = 0
​  , failureCount = 0
​  , callDuration = ​ Map ​.empty
​  }
​  ​ in ​ ​ Metrics ​ <$> newIORef emptyAppMetrics

The idea behind using a newtype wrapper around our IORef is that we’d like users of our metrics API to be able to ignore the implementation detail that we’re using an IORef to handle the metrics. So far, we’ve updated metrics by modifying the reference value directly, but that’s not going to work if we want to hide the fact that we’re dealing with a reference from the user. Instead, let’s add some utility functions that allow us to modify the metrics. Let’s start with a pair of functions to increment our success and failure counters:

​  tickSuccess :: ​ Metrics ​ -> ​ IO ​ ()
​  tickSuccess (​ Metrics ​ metricsRef) = modifyIORef metricsRef $ ​ \ ​m ->
​  m { successCount = 1 + successCount m }
​  
​  tickFailure :: ​ Metrics ​ -> ​ IO ​ ()
​  tickFailure (​ Metrics ​ metricsRef) = modifyIORef metricsRef $ ​ \ ​m ->
​  m { failureCount = 1 + failureCount m }

Next, let’s add a timeFunction call that will let us run an IO action with a given name and time how long it took to execute. For this function, we’ll need to make sure we’ve added a dependency on the time library to our cabal file, and we’ll import a few functions from Data.Time.Clock to let us do some time calculations:

​  ​ import ​ ​ Data.Maybe ​ (​ fromMaybe ​)
​  ​ import ​ ​ Data.Time.Clock ​
​  ( ​ diffUTCTime ​
​  , ​ getCurrentTime ​
​  , ​ nominalDiffTimeToSeconds ​
​  )
​  
​  timeFunction :: ​ Metrics ​ -> ​ String ​ -> ​ IO ​ a -> ​ IO ​ a
​  timeFunction (​ Metrics ​ metrics) actionName action = ​ do ​
​  startTime <- getCurrentTime
​  result <- action
​  endTime <- getCurrentTime
​  
​  modifyIORef metrics $ ​ \ ​oldMetrics ->
​  ​ let ​
​  oldDurationValue =
​  fromMaybe 0 $ ​ Map ​.lookup actionName (callDuration oldMetrics)
​  
​  runDuration =
​  floor . nominalDiffTimeToSeconds $
​  diffUTCTime endTime startTime
​  
​  newDurationValue = oldDurationValue + runDuration
​  
​  ​ in ​ oldMetrics {
​  callDuration =
​  ​ Map ​.insert actionName newDurationValue $
​  callDuration oldMetrics
​  }
​  
​  pure result

Our timer function is a bit longer than tickSuccess and tickFailure , but not much more complicated. The majority of the work that we’re doing here is to calculate the total amount of time being spent in a given function by first finding the time when we start and finish running the function that was passed in and then adding that time to any already accumulated time for this particular action.

Finally, to make things easier to test, let’s add a displayMetrics function that will print our current metrics to the screen. Since we’re going to want access to all of the fields in our metrics store, we’ll enable RecordWildCards to make it easier:

​  ​ {-# LANGUAGE RecordWildCards #-} ​
​  
​  displayMetrics :: ​ Metrics ​ -> ​ IO ​ ()
​  displayMetrics (​ Metrics ​ metricsStore) = ​ do ​
​  ​ AppMetrics ​{..} <- readIORef metricsStore
​  putStrLn $ ​ "successes: " ​ <> show successCount
​  putStrLn $ ​ "failures: " ​ <> show failureCount
​  for_ (​ Map ​.toList callDuration) $ ​ \ ​(functionName, timing) ->
​  putStrLn $ printf ​ "Time spent in ​​ \" ​​ %s ​​ \" ​​ : %d" ​ functionName timing

Now that we’ve got a few functions that we can use to collect metrics, we can start testing it out. Let’s re-use our traverseDirectory code from earlier in this chapter, but now we’ll collect metrics like how many times we succeeded or failed to open a file, and how long we spent in the various functions that we needed to call to process the files.

We’ll start by modifying traverseDirectory to make use of our metrics code. The changes will be fairly minimal, so let’s look at the final version of the function:

​  ​ {-# LANGUAGE TypeApplications #-} ​
​  ​ import ​ ​ qualified ​ ​ Data.Set ​ ​ as ​ Set
​  ​ import ​ ​ Control.Exception ​
​  
​  traverseDirectory :: ​ Metrics ​ -> ​ FilePath ​ -> (​ FilePath ​ -> ​ IO ​ ()) -> ​ IO ​ ()
​  traverseDirectory metrics rootPath action = ​ do ​
​  seenRef <- newIORef ​ Set ​.empty
​  ​ let ​
​  haveSeenDirectory canonicalPath =
​  ​ Set ​.member canonicalPath <$> readIORef seenRef
​  
​  addDirectoryToSeen canonicalPath =
​  modifyIORef seenRef $ ​ Set ​.insert canonicalPath
​  
​  handler ex = print ex >> tickFailure metrics
​  
​  traverseSubdirectory subdirPath =
​  timeFunction metrics ​ "traverseSubdirectory" ​ $ ​ do ​
​  contents <- listDirectory subdirPath
​  for_ contents $ ​ \ ​file' ->
​  handle @​ IOException ​ handler $ ​ do ​
​  ​ let ​ file = subdirPath <> ​ "/" ​ <> file'
​  canonicalPath <- canonicalizePath file
​  classification <- classifyFile canonicalPath
​  
​  result <- ​ case ​ classification ​ of ​
​  ​ FileTypeOther ​ -> pure ()
​  ​ FileTypeRegularFile ​ ->
​  action file
​  ​ FileTypeDirectory ​ -> ​ do ​
​  alreadyProcessed <- haveSeenDirectory file
​  when (not alreadyProcessed) $ ​ do ​
​  addDirectoryToSeen file
​  traverseSubdirectory file
​  tickSuccess metrics
​  pure result
​  
​  traverseSubdirectory (dropSuffix ​ "/" ​ rootPath)

We’ve added a new parameter, bound to the name metrics , so we can actually keep track of the metrics we want to handle in the function. Additionally, we’ve changed the main loop in traverseSubdirectory so the function it calls is wrapped by timeFunction . This lets us keep track of the total amount of time we’re spending traversing through the directory tree. We’re also now incrementing our failure count if we catch an exception while trying to process a file, and incrementing the success count if we successfully process it.

Our new function will take the path to a directory and will traverse it using our new metrics-aware traverseDirectory function. For each file in the directory listing, we’ll print out the number of words in the file, and we’ll update a global histogram that counts the number of occurrences of each character across all of the files that we’ve processed. Once we’re done traversing the directory we’ll print out the histogram and a summary of our metrics.

We’ll start by importing a couple of modules from the text library to help us deal with the contents of the files:

​  ​ import ​ ​ qualified ​ ​ Data.Text ​ ​ as ​ Text
​  ​ import ​ ​ qualified ​ ​ Data.Text.IO ​ ​ as ​ TextIO

Next we’ll start defining our function. We’ll begin by creating some new metrics and an IORef that we can use to keep track of the histogram that we’ll be updating with each file that we process:

​  directorySummaryWithMetrics :: ​ FilePath ​ -> ​ IO ​ ()
​  directorySummaryWithMetrics root = ​ do ​
​  metrics <- newMetrics
​  histogramRef <- newIORef ​ Map ​.empty

Next, we’ll call our new metric-aware traverseDirectory function, and we’ll pass it in the empty metrics store that we’ve just created:

​  traverseDirectory metrics root $ ​ \ ​file -> ​ do ​

The first thing we want to do for each file is to print out the name of the file we’re trying to process. After that, we’ll read the contents of the file into a Text value so that we can process it:

​  putStrLn $ file <> ​ ":" ​
​  contents <- timeFunction metrics ​ "TextIO.readFile" ​ $
​  ​ TextIO ​.readFile file

You’ll notice here that we’re using the readFile function provided to use in Data.Text.IO . This is a strict function that will ensure we actually read the file right away. If you recall the example you worked through when you first started learning about IO , you saw how using laziness with IO could introduce errors, like accidentally exhausting the number of open file descriptors. Not only will using Text here give us a significant performance improvement over String , but using strict IO here will help us avoid some of the problems that can crop up when we are using laziness with IO. Another unexpected benefit of using TextIO.readFile in our case is that it will fail if it tries to read data that isn’t valid Unicode text. Normally we wouldn’t consider failure to be a benefit, but we have failure metrics we’d like to test and this gives us an easy way to populate a directory with files that will fail and let us see that we’re counting those failures correctly.

Now that we have the contents of the file, let’s do some things with it. We’ll start by counting the number of words. As before, we’d like to time this so that we have an idea of how much time we’re spending with this particular file. We’ll start by printing out the number of words in the file:

​  timeFunction metrics ​ "wordcount" ​ $
​  ​ let ​ wordCount = length $ ​ Text ​.words contents
​  ​ in ​ putStrLn $ ​ " word count: " ​ <> show wordCount

Next, let’s update the histogram. We’ll start by reading the current histogram out of our reference. We’ll use that as the starting point and fold over each of the characters in current text that we have:

​  timeFunction metrics ​ "histogram" ​ $ ​ do ​
​  oldHistogram <- readIORef histogramRef
​  ​ let ​
​  addCharToHistogram histogram letter =
​  ​ Map ​.insertWith (+) letter 1 histogram
​  newHistogram = ​ Text ​.foldl' addCharToHistogram oldHistogram contents
​  writeIORef histogramRef newHistogram

The insertWith function here allows us to provide a merge function to be used in case we happen to have a collision in the map. In our case, we’re using this to let us increment the count of a letter each time we find one. The first time we see a new letter, Map.insertWith will add new entry with the letter as the key and the value 1 . The next time we see that letter, it’ll call our function, (+) , with the old count and the new value that we want to insert, which is always 1 , meaning that each time we see a character we’ll increment the count at that position in the map.

As a final step, we’ll print out the histogram data and then print out all of our metrics:

​  histogram <- readIORef histogramRef
​  putStrLn ​ "Histogram Data:" ​
​  for_ (​ Map ​.toList histogram) $ ​ \ ​(letter, count) ->
​  putStrLn $ printf ​ " %c: %d" ​ letter count
​  
​  displayMetrics metrics

The final version of our function is:

​  directorySummaryWithMetrics :: ​ FilePath ​ -> ​ IO ​ ()
​  directorySummaryWithMetrics root = ​ do ​
​  metrics <- newMetrics
​  histogramRef <- newIORef (​ Map ​.empty :: ​ Map ​.​ Map ​ ​ Char ​ ​ Int ​)
​  traverseDirectory metrics root $ ​ \ ​file -> ​ do ​
​  putStrLn $ file <> ​ ":" ​
​  contents <- timeFunction metrics ​ "TextIO.readFile" ​ $
​  ​ TextIO ​.readFile file
​  timeFunction metrics ​ "wordcount" ​ $
​  ​ let ​ wordCount = length $ ​ Text ​.words contents
​  ​ in ​ putStrLn $ ​ " word count: " ​ <> show wordCount
​  
​  timeFunction metrics ​ "histogram" ​ $ ​ do ​
​  oldHistogram <- readIORef histogramRef
​  ​ let ​
​  addCharToHistogram histogram letter =
​  ​ Map ​.insertWith (+) letter 1 histogram
​  newHistogram =
​  ​ Text ​.foldl' addCharToHistogram oldHistogram contents
​  writeIORef histogramRef newHistogram
​  
​  histogram <- readIORef histogramRef
​  putStrLn ​ "Histogram Data:" ​
​  for_ (​ Map ​.toList histogram) $ ​ \ ​(letter, count) ->
​  putStrLn $ printf ​ " %c: %d" ​ letter count
​  
​  displayMetrics metrics

If you use this function to try to get information about a large directory, you might notice something unexpected. First, the output of the program will start out working like you’d expect: all of the files in the directory will be listed, along with the number of words in them. Once the program has finished outputting the word counts though, it will pause for a while. Depending on the size of the directory you were calculating metrics on, the pause might be anywhere from less than a second up to several seconds. Once it’s done, you might see some metrics like this:

​  successes: 20611
​  failures: 43
​  Time spent in "TextIO.readFile": 24
​  Time spent in "histogram": 0
​  Time spent in "traverseSubdirectory": 91389
​  Time spent in "wordcount": 4304

Calculating the histogram should be a fairly time-consuming operation. The fact that we are waiting a while for the final histogram to be printed out is evidence that there is work there to do, but our metrics code seems to think that we’re spending no time at all here. What’s going on? It turns out that we’ve encountered a bug in our program caused by lazy IO. This is a common problem in Haskell programs, and in the next section, we’ll dive into what causes these problems, how to troubleshoot them, and some techniques for fixing the problem.