SPARK-3179. Add task OutputMetrics.

Can you move this code and (separately) the code in lines 995 through 1004 into methods that can be called here and also by saveAsHadoopDataset to avoid the code duplication?