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