python - Python 3.x 中的日志记录错误 : TypeError: a bytes-like object is required, 而不是 'str'

标签 python python-3.x logging byte

我使用的是 Python 3.6.5。

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

“类型错误:需要类字节对象,而不是‘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 行,在发射中 流.write(消息) 类型错误:需要类似字节的对象,而不是“str”

还有...

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

最佳答案

在您的记录器设置中,您:

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

这不起作用,两者必须同步。有两种方法可以修复它。 要么:

  • 使用[Python.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())
    

关于python - Python 3.x 中的日志记录错误 : TypeError: a bytes-like object is required, 而不是 'str',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58179496/

相关文章:

python - 在 PyQt5 中截取网页

python-3.x - 如何让 Python "import.util.module_from_spec"更像 "import"”?

python - 在临时文件夹上设置 SFTP 服务器?

java - Tomcat:@Overriden 日志过滤器混合输出及其非覆盖变体

javascript - 如何将 bunyan 日志记录函数绑定(bind)到 ES6 中的类函数?

python - 什么时候不使用 asyncio 有意义?

python - 获取当前日期/时间并与其他日期进行比较

javascript - NodeJS 中的缩进式多行日志记录

python - 如何在我的项目的Scrapy的items.py中添加Django_app.models

python - 如何将数据帧转换为字典,保留 1 列作为键并将第二列的值与每个键相加