计数器的作用
- 如果需要将
日志信息
传输到map
或reduce
任务, 比较好的方法之一是看能否用一个计数器
值来记录某一特定事件的发生 - 获取计数器值比输出日志更方便,还有根据计数器值统计
特定事件
的发生次数要比分析一堆日志文件容易得多
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/205c3e37062fbea9003f37a376830985.png)
hadoop内置计数器列表:
计数器 | 包 |
---|
MapReduce任务计数器 | org.apache.hadoop.mapreduce.TaskCounter |
文件系统计数器 | org.apache.hadoop.mapreduce.FileSystemCounter |
FileInputFormat计数器 | org.apache.hadoop.mapreduce.lib.input.FileInputFormatCounter |
FileOutputFormat计数器 | org.apache.hadoop.mapreduce.lib.output.FileOutputFormatCounter |
作业计数器 | org.apache.hadoop.mapreduce.JobCounter |
运行一次MR,显示的日志
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6e5360c1ad06fa28a9a167869961a8e5.png)
利用自定义计数器统计map和reduce阶段接受的数据条数
利用context上下午统计map阶段读取的数据
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
Counter counter = context.getCounter("MR_COUNT", "MapRecordCounter");
counter.increment(1L);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/841a3112ac0507bf90f0abfd16941d62.png)
自定义枚举统计reduce阶段处理的数据条数
public class SortReducer extends Reducer<PairWritable,IntWritable,Text,IntWritable> {
private Text outPutKey = new Text();
public static enum Counter{
REDUCE_INPUT_RECORDS, REDUCE_INPUT_VAL_NUMS,
}
@Override
public void reduce(PairWritable key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
context.getCounter(Counter.REDUCE_INPUT_RECORDS).increment(1L);
for(IntWritable value : values) {
context.getCounter(Counter.REDUCE_INPUT_VAL_NUMS).increment(1L);
outPutKey.set(key.getFirst());
context.write(outPutKey, value);
}
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/eb9e477fe6938efcc1a72fb64b374bbd.png)