python - 记录日期格式错误地将 │ 表示为 ¦

标签 python logging utf-8

我有一个设置格式的日志记录脚本。它使用 utf-8 符号以提高可读性,编码设置为保存文件,如下所示。

log = logging.getLogger('general')
fmt = logging.Formatter('%(asctime)s.%(msecs)03d  │  %(levelname)-10s│  %(lineno)4s %(funcName)-20s│  %(message)s',
                        datefmt='%Y/%m/%d │ %H:%M:%S')
handler_error = logging.handlers.RotatingFileHandler("error.log", 'a', encoding="utf-8")
handler_error.setLevel(logging.INFO)
handler_error.setFormatter(fmt)
log.addHandler(handler_error)

理论上,所有的分隔符都应该是 │ 的,但是 datefmt 中的分隔符正在变成 ¦。因此,生成的日志如下所示 - 注意所有正确添加的垂直线,除了日期和时间之间的一组。

我尝试使用 unicode \u2502 而不是 │,但没有帮助。关于如何解决此问题的任何想法?

screenshot of the log

编辑 - 来自其他用户执行的错误日志。

  File "C:\Users\xxx\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 1025, in emit
    msg = self.format(record)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 869, in format
    return fmt.format(record)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 610, in format
    record.asctime = self.formatTime(record, self.datefmt)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python37\lib\logging\__init__.py", line 548, in formatTime
    s = time.strftime(datefmt, ct)
UnicodeEncodeError: 'locale' codec can't encode character '\u2502' in position 9: encoding error

最佳答案

解决方案:需要将LC_CTYPE设置为UTF-8

以下针对更多 Box Drawings 字符的示例表明,在 datefmt 字符串中进行了一些字符转换(类似于 Windows 命令之间的差异 tree vs tree /A)。

# -*- coding: utf-8 -*-

import time, locale
t = time.localtime()
datefmt = '%Y/%m/%d ─│┌┐└┘├┤┬┴┼═║╔╗╚╝╠╣╦╩╬ %H:%M:%S'
print( '\n datefmt:', datefmt)

print( '\nLC_CTYPE:', locale.getlocale(category=locale.LC_CTYPE) )
print( 'strftime:', time.strftime(datefmt, t) )

locale.setlocale(locale.LC_CTYPE, (locale.getlocale()[0], '1252'))
print( '\nLC_CTYPE:', locale.getlocale(category=locale.LC_CTYPE) )
print( 'strftime:', time.strftime(datefmt, t) )

locale.setlocale(locale.LC_CTYPE, (locale.getlocale()[0], 'utf8'))
print( '\nLC_CTYPE:', locale.getlocale(category=locale.LC_CTYPE) )
print( 'strftime:', time.strftime(datefmt, t) )

输出:.\SO\63472673.py

 datefmt: %Y/%m/%d ─│┌┐└┘├┤┬┴┼═║╔╗╚╝╠╣╦╩╬ %H:%M:%S

LC_CTYPE: ('Czech_Czechia', '1250')
strftime: 2020/08/20 ¦--¬L-++T++=¦-¬L-¦¦T¦+ 19:29:14

LC_CTYPE: ('Czech_Czechia', '1252')
strftime: 2020/08/20 -¦+++++¦--+-¦++++¦¦--+ 19:29:14

LC_CTYPE: ('Czech_Czechia', 'utf8')
strftime: 2020/08/20 ─│┌┐└┘├┤┬┴┼═║╔╗╚╝╠╣╦╩╬ 19:29:14

不幸的是,我在 Python 源代码中找不到那个字符转换(可以看到(我的本地)代码页 1250 有一个错误:字符 分别被翻译成 ¦-,即以相反的顺序......

关于python - 记录日期格式错误地将 │ 表示为 ¦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63472673/

相关文章:

python - 反转字典

c# - WCF 当前上下文为 Null

mysql - 告诉 MySQL 连接使用 Django 的 UTF-8

php - 带有日文字符的 substr 问题

php - 在 PHP 中缩短/截断 UTF8 字符串

python - 从 Jinja 表达式中调用的函数中的字典访问值

python - 保留 key

python datetime.date 与 SQL 日期不匹配

c# - 使用 FtpWebRequest 输出日志

Python 日志行未保留