Python 3.x中的记录错误:TypeError:需要一个类似字节的对象,而不是'str'

时间:2019-10-01 06:55:14

标签: python python-3.x logging byte

我使用的是Python 3.6.5。

使用日志记录时,出现以下错误-

“ TypeError:需要一个类似字节的对象,而不是'str'”

在Python 2.x中工作正常,我也尝试将字符串转换为Byte对象,但无法解决问题

if __name__ == '__main__':
    config_file = '/source/account_content_recommendation/config/sales_central_config.json'
    try:
        ### Read all the parameters -
        params = json.loads(hdfs.read_file(config_file))

        ### Create the logging csv file -
        hdfs_log_path = params["hdfs_log_path"]
        hdfs.create_file(hdfs_log_path, "starting ... ", overwrite = True)
        log_name = 'Account_Content_Matching'


        global stream
        log = logging.getLogger('Acct_Cont_Log')
        stream = BytesIO()
        handler = logging.StreamHandler(stream)
        log.setLevel(logging.DEBUG)

        for handle in log.handlers:
            log.removeHandler(handle)

        log.addHandler(handler)

        #env = sys.argv[1]
        env = 'dev'
        formatter = logging.Formatter('{0}| %(asctime)s| {1}| %(module)s| %(funcName)s| %(lineno)d| %(levelname)s| %(message)r'.format(log_name, env))
        handler.setFormatter(formatter)

        log.info("starting execution of Account_Content_Matching load")
        #log.info("sys args %s"%(str(sys.argv)))

        def flush_log():
            global stream
            msg = stream.getvalue()
            hdfs.append_file(hdfs_log_path, msg)
            stream.seek(0)
            stream.truncate(0)
            print(msg)
            sys.stdout.flush

    except Exception as error:
        raise error

我收到以下错误-

回溯(最近通话最近):   发射中的文件“ /home/ec2-user/anaconda3/envs/tensorflow_p36/lib/python3.6/logging/init.py”,第994行     stream.write(msg) TypeError:需要一个类似字节的对象,而不是'str'

还...

消息:“开始执行Account_Content_Matching加载” 参数:() I1001 06:29:35.870266 140241833649984:29]开始执行Account_Content_Matching加载

1 个答案:

答案 0 :(得分:1)

在记录器设置中,您是:

  • 使用 BytesIO 作为流
  • 传递字符串给它

这不起作用,两个必须同步。有2种解决方法。 任一

  • 使用[Python 3.Docs]: class io.StringIO(initial_value='', newline='\n')(而不是 BytesIO ):

    stream = StringIO()
    
  • 将所有字符串转换为 bytes ,然后再将它们传递给logger方法(更复杂,并且比前者更有意义):

    log.info("starting execution of Account_Content_Matching load".encode())  # log.info(b"starting execution of Account_Content_Matching load")  # For literals
    log.debug(some_string_var.encode())