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
019 package org.apache.hadoop.metrics2.sink;
020
021 import java.io.Closeable;
022 import java.io.File;
023 import java.io.FileWriter;
024 import java.io.IOException;
025 import java.io.PrintWriter;
026
027 import org.apache.commons.configuration.SubsetConfiguration;
028 import org.apache.hadoop.classification.InterfaceAudience;
029 import org.apache.hadoop.classification.InterfaceStability;
030 import org.apache.hadoop.metrics2.AbstractMetric;
031 import org.apache.hadoop.metrics2.MetricsException;
032 import org.apache.hadoop.metrics2.MetricsRecord;
033 import org.apache.hadoop.metrics2.MetricsSink;
034 import org.apache.hadoop.metrics2.MetricsTag;
035
036 /**
037 * A metrics sink that writes to a file
038 */
039 @InterfaceAudience.Public
040 @InterfaceStability.Evolving
041 public class FileSink implements MetricsSink, Closeable {
042 private static final String FILENAME_KEY = "filename";
043 private PrintWriter writer;
044
045 @Override
046 public void init(SubsetConfiguration conf) {
047 String filename = conf.getString(FILENAME_KEY);
048 try {
049 writer = filename == null
050 ? new PrintWriter(System.out)
051 : new PrintWriter(new FileWriter(new File(filename), true));
052 }
053 catch (Exception e) {
054 throw new MetricsException("Error creating "+ filename, e);
055 }
056 }
057
058 @Override
059 public void putMetrics(MetricsRecord record) {
060 writer.print(record.timestamp());
061 writer.print(" ");
062 writer.print(record.context());
063 writer.print(".");
064 writer.print(record.name());
065 String separator = ": ";
066 for (MetricsTag tag : record.tags()) {
067 writer.print(separator);
068 separator = ", ";
069 writer.print(tag.name());
070 writer.print("=");
071 writer.print(tag.value());
072 }
073 for (AbstractMetric metric : record.metrics()) {
074 writer.print(separator);
075 separator = ", ";
076 writer.print(metric.name());
077 writer.print("=");
078 writer.print(metric.value());
079 }
080 writer.println();
081 }
082
083 @Override
084 public void flush() {
085 writer.flush();
086 }
087
088 @Override
089 public void close() throws IOException {
090 writer.close();
091 }
092 }