代码
import logging
from logging import config
LOGGING_CONFIG = {
"version": 1,
"formatters": {
"default": {
'format': '%(asctime)19.19s %(levelname)1.1s %(message)s',
},
"file": {
'format': '%(asctime)19.19s %(filename)s %(lineno)s %(levelname)1.1s %(message)s',
},
"plain": {
"format": "%(message)s",
},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "INFO",
"formatter": "default",
},
"file": {
"class": "logging.FileHandler",
"level": 20,
"filename": "./log.txt",
"formatter": "default",
},
"rotate_file": {
"class": "logging.handlers.RotatingFileHandler",
"level": 20,
"filename": "./log.txt",
"formatter": "default",
"maxBytes": 52428800,
"backupCount": 7,
}
},
"loggers": {
"tmp": {
"handlers": ["console", "rotate_file"],
"level": "INFO",
"propagate": False,
},
},
"disable_existing_loggers": True,
}
config.dictConfig(LOGGING_CONFIG)
logger = logging.getLogger("tmp")
logger.info("吃\ud83d\udc3a")
报错信息
2021-02-28 22:35:55 I 吃\ud83d\udc3a
--- Logging error ---
Traceback (most recent call last):
File "/home/vagrant/.pyenv/versions/3.6.9/lib/python3.6/logging/__init__.py", line 996, in emit
stream.write(msg)
UnicodeEncodeError: 'utf-8' codec can't encode characters in position 23-24: surrogates not allowed
Call stack:
File "/home/vagrant/code/xxx/tmp.py", line 55, in <module>
logger.info("吃\ud83d\udc3a")
Message: '吃\ud83d\udc3a'
Arguments: ()
这种问题怎么 fix 呀?
1
Sunyanzi 2021-02-28 23:39:54 +08:00 1
|
2
lxy42 2021-02-28 23:48:14 +08:00 1
```
In [38]: print('\U0001f43a') 🐺 In [39]: hex(ord('🐺')) Out[39]: '0x1f43a' ``` |
3
chenqh OP @Sunyanzi 虽然你这个样子不会报错,但是日志变成这个样子了
``` 2021-03-01 00:05:07 I b'\\u5403\\ud83d\\udc3a' ``` 日志都不能肉眼识别了,那么日志的意义就没有了呀 |
5
Sunyanzi 2021-03-01 00:12:28 +08:00 1
|
6
Sylv 2021-03-01 04:20:31 +08:00 via iPhone 1
\ud83d\udc3a 是 🐺 的 UTF-16 编码,然后再用默认的 UTF-8 编码 encode 肯定就出错了。
|
7
Sylv 2021-03-01 04:20:47 +08:00 via iPhone
|
8
joApioVVx4M4X6Rf 2021-03-01 16:02:58 +08:00
|