Metrics Layer

The last item we’re going to add to our layer is a metrics manager. This helper is used to enable the publishing of metrics data with tenant context. Recording and publishing metrics is essential to SaaS organizations. While what we have here is rather simple and lightweight, it’s important to have the placeholder here to convey the importance of adding metrics to your SaaS solutions. The file shown below represents the simpler metrics manager we’ve created for this workshop.

package com.amazon.aws.partners.saasfactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.Map;

public class MetricsManager {

    public static void recordMetric(Map<String, Object> event, String source, 
                                    String action, Long duration) {
        String tenantId = TokenManager.getTenantId(event);

        Map<String, Object> metric = new HashMap<>();
        metric.put("tenantId", tenantId);
        metric.put("source", source);
        metric.put("action", action);
        metric.put("duration", duration);
        metric.put("utc", Instant.now().truncatedTo(ChronoUnit.MILLIS)\
            .toString().substring(0, 23).replace('T', ' '));

        String json;
        try {
            json = 
                new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(metric);
        } catch (JsonProcessingException e) {
            // Get the whole stack trace
            final StringWriter sw = new StringWriter();
            final PrintWriter pw = new PrintWriter(sw, true);
            e.printStackTrace(pw);
            LoggingManager.log(event, sw.getBuffer().toString());

            json = e.getMessage();
        }
        LoggingManager.log(event, "MetricsManager::recordMetric\n" + json);
    }
}

Next, select the “Lab 4/layers/metrics-manager“ folder in the navigation tree on the left. Right click on the folder and select “New file“. The will add an entry to the folder. Type the file name “metrics-manager.java“ into the placeholder in the source tree the code above into this new file and save it as “metrics-manager.java“ and press enter. Once the file has been created, double-click on the newly added file to open the empty file editor on in the right-hand pane. Now, paste the contents above into the editor and select “File | Save“ from the menu at the top left of the IDE.