Pyspark日志记录:以错误的日志级别打印信息

时间:2020-05-13 19:07:39

标签: apache-spark logging pyspark qubole

感谢您的时间!

在调试代码时,我想创建(大量)数据的清晰摘要并将其打印到输出中,但是一旦完成,请停止创建并打印这些摘要以加快处理速度。建议我使用实现的日志记录。它可以按预期的方式将文本字符串作为消息打印到输出中,但是,当打印数据帧摘要时,它似乎忽略了日志级别,而是创建并始终打印它们。

是否正在记录要使用的权限,或者有更好的方法吗?我可以#阻塞代码行或使用if语句等,但这是一个庞大的代码,我知道以后添加更多元素时,我将需要进行相同的检查-似乎完全像日志记录那样。

from pyspark.sql.functions import col,count
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

df = spark.createDataFrame([(1,2),(3,4)],["COLA","COLB"])

print "1"
logger.setLevel(logging.DEBUG)
logger.debug("1 - DEBUG - Print the message and show the table")
logger.debug(df.show())

print "2"
logger.setLevel(logging.INFO)
logger.debug("2 - INFO - Don't print the message or show the table")
logger.debug(df.show())

print "3"
logger.setLevel(logging.INFO)
logger.debug("3 - INFO - Don't print the message or show the collected data")
logger.debug(df.collect())

print "4"
logger.setLevel(logging.DEBUG)
logger.debug("4 - DEBUG - Print the message and the collected data")
logger.debug(df.collect())

输出:

1
DEBUG:__main__:1 - DEBUG - Print the message and show the table
+----+----+
|COLA|COLB|
+----+----+
|   1|   2|
|   3|   4|
+----+----+
DEBUG:__main__:None
2
+----+----+
|COLA|COLB|
+----+----+
|   1|   2|
|   3|   4|
+----+----+
3
4
DEBUG:__main__:4 - DEBUG - Print the message and the collected data
DEBUG:__main__:[Row(COLA=1, COLB=2), Row(COLA=3, COLB=4)]

1 个答案:

答案 0 :(得分:0)

Logging按预期工作,如果我们使用的是df.show()(或)df.collect(),则它们会在执行火花时执行,即使它们位于logger.debug中。

  • 如果将日志级别设置为DEBUG,则可以看到INFO级别的日志。

  • 如果将日志级别设置为INFO,则看不到DEBUG级别的日志。

您可以采取的一种解决方法是,将collect()/take(n)结果存储到变量中,然后在日志记录中使用该变量。

from pyspark.sql.functions import col,count
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

df = spark.createDataFrame([(1,2),(3,4)],["COLA","COLB"])

#storing results but don't use collect on huge dataset instead use `.take`
res=df.collect() 

#get 10 records from df
res=df.take(10)

print "1"
#1
logger.setLevel(logging.DEBUG)
logger.debug("1 - DEBUG - Print the message and show the table")
#DEBUG:__main__:1 - DEBUG - Print the message and show the table
logger.debug(res)
#DEBUG:__main__:[Row(COLA=1, COLB=2), Row(COLA=3, COLB=4)]

print "2"
#2
logger.setLevel(logging.INFO)
logger.debug("2 - INFO - Don't print the message or show the table")
logger.debug(res) #this won't print as loglevel is INFO.
logger.info("result: " + str(res)) #this will get printed out
#INFO:__main__:result: [Row(COLA=1, COLB=2), Row(COLA=3, COLB=4)]

使用.take代替.collect()