@Override
  public void run() {
    Path tmpFile = null;
    try {
      // Dump metrics to string as JSON
      String json;
      try {
        json = jsonWriter.writeValueAsString(metricRegistry);
      } catch (JsonProcessingException e) {
        LOGGER.error("Unable to convert json to string ", e);
        return;
      }

      // Metrics are first dumped to a temp file which is then renamed to the destination
      try {
        tmpFile = Files.createTempFile(metricsDir, "hmetrics", "json", FILE_ATTRS);
      } catch (IOException e) {
        LOGGER.error("failed to create temp file for JSON metrics", e);
        return;
      } catch (SecurityException e) {
        // This shouldn't ever happen
        LOGGER.error("failed to create temp file for JSON metrics: no permissions", e);
        return;
      } catch (UnsupportedOperationException e) {
        // This shouldn't ever happen
        LOGGER.error("failed to create temp file for JSON metrics: operation not supported", e);
        return;
      }

      // Write json to the temp file.
      try (BufferedWriter bw = Files.newBufferedWriter(tmpFile, StandardCharsets.UTF_8)) {
        bw.write(json);
      } catch (IOException e) {
        LOGGER.error("Unable to write to temp file " + tmpFile, e);
        return;
      }

      // Atomically move temp file to the destination file
      try {
        Files.move(tmpFile, path, StandardCopyOption.ATOMIC_MOVE);
      } catch (Exception e) {
        LOGGER.error("Unable to rename temp file {} to {}", tmpFile, path);
        LOGGER.error("Exception during rename", e);
      }
    } catch (Throwable t) {
      // catch all errors (throwable and exceptions to prevent subsequent tasks from being suppressed)
      LOGGER.error("Error executing scheduled task ", t);
    } finally {
      // If something happened and we were not able to rename the temp file, attempt to remove it
      if (tmpFile != null && tmpFile.toFile().exists()) {
        // Attempt to delete temp file, if this fails, not much can be done about it.
        try {
          Files.delete(tmpFile);
        } catch (Exception e) {
          LOGGER.error("failed to delete temporary metrics file " +  tmpFile, e);
        }
      }
    }
  }
A metrics reporter for CodahaleMetrics that dumps metrics periodically into
a file in JSON format. Only files on local filesystems are supported.
standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/common/metrics/metrics2/JsonFileMetricsReporter.java