Pyspark не входит в файл - PullRequest
       14

Pyspark не входит в файл

0 голосов
/ 17 января 2019

Я запускаю скрипт pyspark с командой spark-submit, перенаправляя стандартный вывод в файл тоже с помощью tee, чтобы получить журнал.

Команда следующая:

spark-submit test.py  | tee test.xxx

Проблема в том, что только print внутри пользовательской функции UDF был напечатан только на Терминале, но не в файл tee test.xxx, в то время как все остальные отпечатки будут записаны на терминал и файл.

Чтобы смоделировать это поведение, я создал этот минимально полный рабочий пример:

from pyspark import SparkContext
import pyspark.sql.functions as F #udf, col, count, sum, when, avg, mean, min
from pyspark.sql import SQLContext
from pyspark.sql.types import *
def cutURL(input):
    cutURL.lineNumber += 1
    if input==None or input=="" or not(isinstance(input, str)):
        print("WARNING: not proper string URL: empty or null. Possible line: " + str(cutURL.lineNumber))
        res = "Unknown"
        if input==None: print("string is none")
        elif not(isinstance(input, str)): print("input not a string")
        elif input=="": print("empty string")
        return res
    res = input
    try:
        if (bool(re.search("/devices(.+?)&maxdist=[0-9]+", input))):
            res = re.search("/devices(.+?)&maxdist=[0-9]+", input).group()
        else:
            res = re.sub(r'.*?(/devices/[^/]*_)[^/_]*(/read)', r'\1\2', input)
    except:
        print("WARning in cutURL:")
        print(" not matching regular expression: is the string")
    return res


sc = SparkContext.getOrCreate()
sc.setLogLevel("WARN")
sqlContext = SQLContext(sc)
cutURL.lineNumber = 0
print("This will be printed to both file and terminal")
df = sqlContext.createDataFrame([None, "example",  "others"], "string").toDF("url")
cut_URL_udf =  F.udf(cutURL, StringType())
df2 = df.select(cut_URL_udf("url").alias("cut_URL"))
df2.show()

В этом случае строка WARNING: not proper string URL: empty or null. Possible line: печатается только на терминале, но не в файл.

Как сделать так, чтобы вывод, генерируемый внутри UDF pyspark, перенаправлялся в файл?

EDIT Чтобы лучше объяснить мою проблему, я добавляю строку print("This will be printed to both file and terminal"). Этот файл будет распечатан на терминале и записан в файл, в то время как print внутри udf только для терминала.

1 Ответ

0 голосов
/ 18 января 2019

Редактировать: извините, неправильно прочитал уже перенаправления

Решением является использование правильной регистрации вместо печати:

поиск журнала Python:

Пример для входа в консоль и файл:

import logging

# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='/temp/myapp.log',
                    filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)

# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...