001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.hadoop.metrics2.sink;
020
021import java.io.BufferedOutputStream;
022import java.io.File;
023import java.io.FileWriter;
024import java.io.PrintWriter;
025
026import org.apache.commons.configuration.SubsetConfiguration;
027import org.apache.hadoop.classification.InterfaceAudience;
028import org.apache.hadoop.classification.InterfaceStability;
029import org.apache.hadoop.metrics2.AbstractMetric;
030import org.apache.hadoop.metrics2.MetricsException;
031import org.apache.hadoop.metrics2.MetricsRecord;
032import org.apache.hadoop.metrics2.MetricsSink;
033import org.apache.hadoop.metrics2.MetricsTag;
034
035/**
036 * A metrics sink that writes to a file
037 */
038@InterfaceAudience.Public
039@InterfaceStability.Evolving
040public class FileSink implements MetricsSink {
041  private static final String FILENAME_KEY = "filename";
042  private PrintWriter writer;
043
044  @Override
045  public void init(SubsetConfiguration conf) {
046    String filename = conf.getString(FILENAME_KEY);
047    try {
048      writer = filename == null
049          ? new PrintWriter(System.out)
050          : new PrintWriter(new FileWriter(new File(filename), true));
051    }
052    catch (Exception e) {
053      throw new MetricsException("Error creating "+ filename, e);
054    }
055  }
056
057  @Override
058  public void putMetrics(MetricsRecord record) {
059    writer.print(record.timestamp());
060    writer.print(" ");
061    writer.print(record.context());
062    writer.print(".");
063    writer.print(record.name());
064    String separator = ": ";
065    for (MetricsTag tag : record.tags()) {
066      writer.print(separator);
067      separator = ", ";
068      writer.print(tag.name());
069      writer.print("=");
070      writer.print(tag.value());
071    }
072    for (AbstractMetric metric : record.metrics()) {
073      writer.print(separator);
074      separator = ", ";
075      writer.print(metric.name());
076      writer.print("=");
077      writer.print(metric.value());
078    }
079    writer.println();
080  }
081
082  @Override
083  public void flush() {
084    writer.flush();
085  }
086}