Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,17 @@ package org.apache.spark.internal
* All structured logging keys should be defined here for standardization.
*/
object LogKey extends Enumeration {
val EXECUTOR_ID, MIN_SIZE, MAX_SIZE = Value
val APPLICATION_ID = Value
val APPLICATION_STATE = Value
val BUCKET = Value
val CONTAINER_ID = Value
val EXECUTOR_ID = Value
val EXIT_CODE = Value
val MAX_EXECUTOR_FAILURES = Value
val MAX_SIZE = Value
val MIN_SIZE = Value
val REMOTE_ADDRESS = Value
val POD_ID = Value

type LogKey = Value
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we need this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because I want to use 'xxx: LogKey' instead of 'xxx: LogKey.Value' to define a type, it feels like it's a personal preference. Should we restore it?

object TaskLocality extends Enumeration {
// Process local is expected to be used ONLY within TaskSetManager for now.
val PROCESS_LOCAL, NODE_LOCAL, NO_PREF, RACK_LOCAL, ANY = Value
type TaskLocality = Value
def isAllowed(constraint: TaskLocality, condition: TaskLocality): Boolean = {
condition <= constraint
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,15 @@ import org.apache.logging.log4j.core.filter.AbstractFilter
import org.slf4j.{Logger, LoggerFactory}

import org.apache.spark.internal.Logging.SparkShellLoggingFilter
import org.apache.spark.internal.LogKey.LogKey
import org.apache.spark.util.SparkClassUtils

/**
* Mapped Diagnostic Context (MDC) that will be used in log messages.
* The values of the MDC will be inline in the log message, while the key-value pairs will be
* part of the ThreadContext.
*/
case class MDC(key: LogKey.Value, value: String)
case class MDC(key: LogKey, value: Any)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make the type of value from String to Any, so that when using MDC, some code can be omitted, eg: String.valueOf(...) , x.toString


/**
* Wrapper class for log messages that include a logging context.
Expand Down Expand Up @@ -102,9 +103,9 @@ trait Logging {
val context = new java.util.HashMap[String, String]()

args.foreach { mdc =>
sb.append(mdc.value)
sb.append(mdc.value.toString)
if (Logging.isStructuredLoggingEnabled) {
context.put(mdc.key.toString.toLowerCase(Locale.ROOT), mdc.value)
context.put(mdc.key.toString.toLowerCase(Locale.ROOT), mdc.value.toString)
}

if (processedParts.hasNext) {
Expand Down
49 changes: 49 additions & 0 deletions common/utils/src/test/scala/org/apache/spark/util/MDCSuite.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.spark.util

import scala.jdk.CollectionConverters._

import org.scalatest.funsuite.AnyFunSuite // scalastyle:ignore funsuite

import org.apache.spark.internal.{Logging, MDC}
import org.apache.spark.internal.LogKey.EXIT_CODE

class MDCSuite
extends AnyFunSuite // scalastyle:ignore funsuite
with Logging {

test("check MDC message") {
val log = log"This is a log, exitcode ${MDC(EXIT_CODE, 10086)}"
assert(log.message === "This is a log, exitcode 10086")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's verify the returned map as well

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay

assert(log.context === Map("exit_code" -> "10086").asJava)
}

test("custom object as MDC value") {
val cov = CustomObjectValue("spark", 10086)
val log = log"This is a log, exitcode ${MDC(EXIT_CODE, cov)}"
assert(log.message === "This is a log, exitcode CustomObjectValue: spark, 10086")
assert(log.context === Map("exit_code" -> "CustomObjectValue: spark, 10086").asJava)
}

case class CustomObjectValue(key: String, value: Int) {
override def toString: String = {
"CustomObjectValue: " + key + ", " + value
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,15 @@ class PatternLoggingSuite extends LoggingSuiteBase with BeforeAndAfterAll {
s""".*$level $className: This is a log message\n"""
}

override def expectedPatternForBasicMsgWithException(level: Level): String = {
s""".*$level $className: This is a log message\n[\\s\\S]*"""
}

override def expectedPatternForMsgWithMDC(level: Level): String =
s""".*$level $className: Lost executor 1.\n"""

override def expectedPatternForMsgWithMDCAndException(level: Level): String =
s""".*$level $className: Error in executor 1.\njava.lang.RuntimeException: OOM\n.*"""
s""".*$level $className: Error in executor 1.\njava.lang.RuntimeException: OOM\n[\\s\\S]*"""

override def verifyMsgWithConcat(level: Level, logOutput: String): Unit = {
val pattern =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.spark.util

import java.io.File
Expand Down Expand Up @@ -57,14 +58,20 @@ trait LoggingSuiteBase

def msgWithMDCAndException: LogEntry = log"Error in executor ${MDC(EXECUTOR_ID, "1")}."

def expectedPatternForBasicMsg(level: Level): String

def msgWithConcat: LogEntry = log"Min Size: ${MDC(MIN_SIZE, "2")}, " +
log"Max Size: ${MDC(MAX_SIZE, "4")}. " +
log"Please double check."

// test for basic message (without any mdc)
def expectedPatternForBasicMsg(level: Level): String

// test for basic message and exception
def expectedPatternForBasicMsgWithException(level: Level): String
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a new test for basicMsg + Exception

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Let's add comments about each pattern is about

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay


// test for message (with mdc)
def expectedPatternForMsgWithMDC(level: Level): String

// test for message and exception
def expectedPatternForMsgWithMDCAndException(level: Level): String

def verifyMsgWithConcat(level: Level, logOutput: String): Unit
Expand All @@ -79,6 +86,17 @@ trait LoggingSuiteBase
}
}

test("Basic logging with Exception") {
val exception = new RuntimeException("OOM")
Seq(
(Level.ERROR, () => logError(basicMsg, exception)),
(Level.WARN, () => logWarning(basicMsg, exception)),
(Level.INFO, () => logInfo(basicMsg, exception))).foreach { case (level, logFunc) =>
val logOutput = captureLogOutput(logFunc)
assert(expectedPatternForBasicMsgWithException(level).r.matches(logOutput))
}
}

test("Logging with MDC") {
Seq(
(Level.ERROR, () => logError(msgWithMDC)),
Expand All @@ -98,7 +116,7 @@ trait LoggingSuiteBase
(Level.INFO, () => logInfo(msgWithMDCAndException, exception))).foreach {
case (level, logFunc) =>
val logOutput = captureLogOutput(logFunc)
assert(expectedPatternForMsgWithMDCAndException(level).r.findFirstIn(logOutput).isDefined)
assert(expectedPatternForMsgWithMDCAndException(level).r.matches(logOutput))
}
}

Expand Down Expand Up @@ -137,6 +155,22 @@ class StructuredLoggingSuite extends LoggingSuiteBase {
}""")
}

override def expectedPatternForBasicMsgWithException(level: Level): String = {
compactAndToRegexPattern(
s"""
{
"ts": "<timestamp>",
"level": "$level",
"msg": "This is a log message",
"exception": {
"class": "java.lang.RuntimeException",
"msg": "OOM",
"stacktrace": "<stacktrace>"
},
"logger": "$className"
}""")
}

override def expectedPatternForMsgWithMDC(level: Level): String = {
compactAndToRegexPattern(
s"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ import org.apache.spark.deploy.k8s.Config._
import org.apache.spark.deploy.k8s.Constants._
import org.apache.spark.deploy.k8s.KubernetesConf
import org.apache.spark.deploy.k8s.KubernetesUtils.addOwnerReference
import org.apache.spark.internal.Logging
import org.apache.spark.internal.{Logging, LogKey, MDC}
import org.apache.spark.internal.config._
import org.apache.spark.resource.ResourceProfile
import org.apache.spark.scheduler.cluster.SchedulerBackendUtils.DEFAULT_NUMBER_EXECUTORS
Expand Down Expand Up @@ -143,7 +143,8 @@ class ExecutorPodsAllocator(
snapshotsStore.addSubscriber(podAllocationDelay) { executorPodsSnapshot =>
onNewSnapshots(applicationId, schedulerBackend, executorPodsSnapshot)
if (failureTracker.numFailedExecutors > maxNumExecutorFailures) {
logError(s"Max number of executor failures ($maxNumExecutorFailures) reached")
logError(log"Max number of executor failures " +
log"(${MDC(LogKey.MAX_EXECUTOR_FAILURES, maxNumExecutorFailures)}) reached")
stopApplication(EXCEED_MAX_EXECUTOR_FAILURES)
}
}
Expand Down Expand Up @@ -532,7 +533,8 @@ class ExecutorPodsAllocator(
currentTime - creationTime > executorIdleTimeout
} catch {
case e: Exception =>
logError(s"Cannot get the creationTimestamp of the pod: ${state.pod}", e)
logError(log"Cannot get the creationTimestamp of the pod: " +
log"${MDC(LogKey.POD_ID, state.pod)}", e)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO POD_ID is not a suitable key here. state.pod actually outputs a whole Pod Spec, and there is no such a "pod id" concept in the K8s, in practice, we use namespace and pod name to identify a pod.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pan3793 Thanks for the suggestion. Do you mind creating a PR to improve this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would like to have a try, it may take a few hours to learn this new log framework.

Copy link
Member

@gengliangwang gengliangwang Apr 3, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The inital PR of the framework is in #45729. Thank you in advance!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pan3793 Thank you very much for correcting this issue.

true
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import org.apache.spark.deploy.k8s.integrationtest.DepsTestsSuite.{DEPS_TIMEOUT,
import org.apache.spark.deploy.k8s.integrationtest.KubernetesSuite._
import org.apache.spark.deploy.k8s.integrationtest.Utils.getExamplesJarName
import org.apache.spark.deploy.k8s.integrationtest.backend.minikube.Minikube
import org.apache.spark.internal.{LogKey, MDC}
import org.apache.spark.internal.config.{ARCHIVES, PYSPARK_DRIVER_PYTHON, PYSPARK_PYTHON}

private[spark] trait DepsTestsSuite { k8sSuite: KubernetesSuite =>
Expand Down Expand Up @@ -326,7 +327,7 @@ private[spark] trait DepsTestsSuite { k8sSuite: KubernetesSuite =>
s3client.createBucket(createBucketRequest)
} catch {
case e: Exception =>
logError(s"Failed to create bucket $BUCKET", e)
logError(log"Failed to create bucket ${MDC(LogKey.BUCKET, BUCKET)}", e)
throw new SparkException(s"Failed to create bucket $BUCKET.", e)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ import org.apache.spark.deploy.{ExecutorFailureTracker, SparkHadoopUtil}
import org.apache.spark.deploy.history.HistoryServer
import org.apache.spark.deploy.security.HadoopDelegationTokenManager
import org.apache.spark.deploy.yarn.config._
import org.apache.spark.internal.Logging
import org.apache.spark.internal.{Logging, MDC}
import org.apache.spark.internal.LogKey.{EXIT_CODE, REMOTE_ADDRESS}
import org.apache.spark.internal.config._
import org.apache.spark.internal.config.UI._
import org.apache.spark.metrics.{MetricsSystem, MetricsSystemInstances}
Expand Down Expand Up @@ -745,9 +746,10 @@ private[spark] class ApplicationMaster(
case _: InterruptedException =>
// Reporter thread can interrupt to stop user class
case SparkUserAppException(exitCode) =>
val msg = s"User application exited with status $exitCode"
val msg = log"User application exited with status " +
log"${MDC(EXIT_CODE, exitCode)}"
logError(msg)
finish(FinalApplicationStatus.FAILED, exitCode, msg)
finish(FinalApplicationStatus.FAILED, exitCode, msg.message)
case cause: Throwable =>
logError("User class threw exception: ", cause)
finish(FinalApplicationStatus.FAILED,
Expand Down Expand Up @@ -854,7 +856,8 @@ private[spark] class ApplicationMaster(
logInfo(s"Driver terminated or disconnected! Shutting down. $remoteAddress")
finish(FinalApplicationStatus.SUCCEEDED, ApplicationMaster.EXIT_SUCCESS)
} else {
logError(s"Driver terminated with exit code ${exitCode}! Shutting down. $remoteAddress")
logError(log"Driver terminated with exit code ${MDC(EXIT_CODE, exitCode)}! " +
log"Shutting down. ${MDC(REMOTE_ADDRESS, remoteAddress)}")
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gengliangwang
Perhaps it would be more reasonable to write this in this way

logError(log"Driver terminated with exit code ${MDC(EXIT_CODE, exitCode)}! " + log"Shutting down. $remoteAddress")

Not every variable needs to be recorded in the field content of JSON
Unfortunately, we currently do not support this syntax as above, it will fail to compile.
So I submitted a separate PR to address this issue: #45813

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@panbingkun Let's put all the variables into the context during the migration. If the context is too verbose, we can configure log4j to only show a subset of keys later.
Otherwise, there will be back-and-forth during the migration. remoteAddress can be helpful for debugging here.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay

finish(FinalApplicationStatus.FAILED, exitCode)
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ import org.apache.spark.deploy.security.HadoopDelegationTokenManager
import org.apache.spark.deploy.yarn.ResourceRequestHelper._
import org.apache.spark.deploy.yarn.YarnSparkHadoopUtil._
import org.apache.spark.deploy.yarn.config._
import org.apache.spark.internal.Logging
import org.apache.spark.internal.{Logging, MDC}
import org.apache.spark.internal.LogKey.APPLICATION_ID
import org.apache.spark.internal.config._
import org.apache.spark.internal.config.Python._
import org.apache.spark.launcher.{JavaModuleOptions, LauncherBackend, SparkAppHandle, YarnCommandBuilderUtils}
Expand Down Expand Up @@ -1198,7 +1199,7 @@ private[spark] class Client(
getApplicationReport()
} catch {
case e: ApplicationNotFoundException =>
logError(s"Application $appId not found.")
logError(log"Application ${MDC(APPLICATION_ID, appId)} not found.")
cleanupStagingDir()
return YarnAppReport(YarnApplicationState.KILLED, FinalApplicationStatus.KILLED, None)
case NonFatal(e) if !e.isInstanceOf[InterruptedIOException] =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ import org.apache.spark.deploy.yarn.ResourceRequestHelper._
import org.apache.spark.deploy.yarn.YarnSparkHadoopUtil._
import org.apache.spark.deploy.yarn.config._
import org.apache.spark.executor.ExecutorExitCode
import org.apache.spark.internal.Logging
import org.apache.spark.internal.{Logging, MDC}
import org.apache.spark.internal.LogKey.{CONTAINER_ID, EXECUTOR_ID}
import org.apache.spark.internal.config._
import org.apache.spark.resource.ResourceProfile
import org.apache.spark.resource.ResourceProfile.DEFAULT_RESOURCE_PROFILE_ID
Expand Down Expand Up @@ -789,7 +790,8 @@ private[yarn] class YarnAllocator(
getOrUpdateNumExecutorsStartingForRPId(rpId).decrementAndGet()
launchingExecutorContainerIds.remove(containerId)
if (NonFatal(e)) {
logError(s"Failed to launch executor $executorId on container $containerId", e)
logError(log"Failed to launch executor ${MDC(EXECUTOR_ID, executorId)} " +
log"on container ${MDC(CONTAINER_ID, containerId)}", e)
// Assigned container should be released immediately
// to avoid unnecessary resource occupation.
amClient.releaseAssignedContainer(containerId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ import org.apache.hadoop.yarn.api.records.{FinalApplicationStatus, YarnApplicati
import org.apache.spark.{SparkContext, SparkException}
import org.apache.spark.deploy.yarn.{Client, ClientArguments, YarnAppReport}
import org.apache.spark.deploy.yarn.config._
import org.apache.spark.internal.{config, Logging}
import org.apache.spark.internal.{config, Logging, MDC}
import org.apache.spark.internal.LogKey.APPLICATION_STATE
import org.apache.spark.launcher.SparkAppHandle
import org.apache.spark.scheduler.TaskSchedulerImpl
import org.apache.spark.scheduler.cluster.CoarseGrainedClusterMessages._
Expand Down Expand Up @@ -116,8 +117,8 @@ private[spark] class YarnClientSchedulerBackend(
try {
val YarnAppReport(_, state, diags) =
client.monitorApplication(logApplicationReport = false)
logError(s"YARN application has exited unexpectedly with state $state! " +
"Check the YARN application logs for more details.")
logError(log"YARN application has exited unexpectedly with state " +
log"${MDC(APPLICATION_STATE, state)}! Check the YARN application logs for more details.")
diags.foreach { err =>
logError(s"Diagnostics message: $err")
}
Expand Down