python3.x中的日志记录错误:TypeError:需要类似字节的对象,而不是str

2024-03-28 10:29:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3.6.5。在

使用日志时,我收到以下错误-

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

它在python2.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行,在emit中 流.write(消息) typestr不是必需的,像typestr这样的对象不是必需的

还有。。。在

Message:'开始执行帐户\u Content_匹配加载' 参数:() I1001 06:29:35.870266 140241833649984:29]开始执行帐户_Content_匹配加载


Tags: path对象nameenvlogconfigstreamlogging
1条回答
网友
1楼 · 发布于 2024-03-28 10:29:10

在记录器设置中,您将:

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

这不行,2必须同步。有两种方法可以修复它。要么

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

    stream = StringIO()
    
  • 将所有字符串转换为字节,然后将它们传递给记录器方法(比前者更复杂,意义更小):

    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())
    

相关问题 更多 >