gpt4 book ai didi

python3 记录器 - UnicodeEncodeError

转载 作者:行者123 更新时间:2023-12-01 01:30:47 27 4
gpt4 key购买 nike

我有一个这样的记录器设置:

import logging
from logging.handlers import RotatingFileHandler
import sys

# root logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# create a file logger
handler = RotatingFileHandler('log/core-application.log', maxBytes=1024*1024*1, backupCount=3)
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(funcName)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)


# create stdout logger
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(funcName)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

logger.info('Logging all setup')

在我的开发系统上,此日志记录条目工作正常。它记录您在这里看到的内容:

logger.info('消息键:{}'.format('2018-10-19_00:20:56_\xd8\xa7\xd9\x84\xd8\xb5\xd9\x88\xd8\xa7\xd9\x81/'))

我的 ubuntu AWS EC2 服务器上的同一行给了我一个错误:

--- Logging error --- Traceback (most recent call last): File "/usr/lib/python3.5/logging/init.py", line 982, in emit stream.write(msg) UnicodeEncodeError: 'ascii' codec can't encode characters in position 108-113: ordinal not in range(128)

有人能想象这是为什么吗?

顺便说一句:EC2 服务器区域设置为:

LC_ALL=en_US.UTF-8LANG=en_US.UTF-8

提前致谢。

最佳答案

对我有用的是将encoding='utf8' arg 添加到处理程序:

 formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
log_path = '/var/log/app'
log_file = '%s/%s.log' % (log_path, name)
create_log_file(log_file)
handler = logging.FileHandler(log_file, encoding='utf8')
handler.setFormatter(formatter)
logger.addHandler(handler)

关于python3 记录器 - UnicodeEncodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52896485/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com