[SPARK-3377] [Metrics] Metrics can be accidentally aggregated(Another solution)

This PR is another solution for #2250 

Closes #2250 
Closes #1067
As a personal preference, I like to use Scala for-comprehensions when dealing with large numbers of optional values like this.  I think you can express this as:

```scala
for (
   appName <- conf.getOption("spark.app.name")
   appId <- conf.getOption("spark.app.id")
   executorId <- conf.getOption("spark.executor.id")
) yield {
  MetricRegistry.name(appId, appName, executorId, source.sourceName)
}.getOrElse {
  MetricRegistry.name(source.sourceName)
}
```