English 中文(简体)
在Python中使用日志记录时,会设置区域设置,并且无法获取日志
原标题:When using logging in Python, the locale is set, and the log cannot be obtained

我正在尝试使用Python中的日志记录模块。它运行良好,预计当我设置障碍。

以下是示例代码(python3.9):

import logging
import locale
from time import asctime

logging.basicConfig(
    level=logging.INFO,
    filename="test.log",
    encoding="utf-8",
    filemode="w",
    format= %(asctime)s - %(name)s - %(levelname)s - %(message)s ,
    datefmt="%Y-%m-%d %H:%M:%S"
)

logging.info("before")
locale.setlocale(locale.LC_ALL, "zh_CN.UTF-8")
logging.info("after")

程序意外退出。

当我检查<code>test.log</code>时,我只得到了这个:

2023-07-14 10:37:43-根-信息-之前

它在之后错过了的日志记录。

In my limited experience with pyhton. I have done some research in Google and other Q&A community. The problem seems to be related to the asctime. But I still can t know the deeper reason.

我想知道为什么(源代码级别)当我设置区域设置时,日志记录无法再工作。

提前谢谢。

问题回答

当我运行您显示的代码时,程序终止,我得到一个显示错误的堆栈回溯。在我的情况下,错误是:

<code>locale.Error:不支持的区域设置

这是由于我的系统不支持请求的区域设置而引发的异常。

如果你没有得到堆栈回溯,但它正在悄悄退出,那就更神秘了。可以禁用堆栈回溯。

您可以尝试的另一件事是将setlocale()调用封装在try:块中,看看您得到了什么。示例:

try:
    locale.setlocale(locale.LC_ALL, "zh_CN.UTF-8")
except Exception as e:
    print(repr(e))

在我的情况下,它打印出与我上面列出的相同的异常。





相关问题
Get webpage contents with Python?

I m using Python 3.1, if that helps. Anyways, I m trying to get the contents of this webpage. I Googled for a little bit and tried different things, but they didn t work. I m guessing that this ...

What is internal representation of string in Python 3.x

In Python 3.x, a string consists of items of Unicode ordinal. (See the quotation from the language reference below.) What is the internal representation of Unicode string? Is it UTF-16? The items ...

What does Python s builtin __build_class__ do?

In Python 3.1, there is a new builtin function I don t know in the builtins module: __build_class__(...) __build_class__(func, name, *bases, metaclass=None, **kwds) -> class Internal ...

what functional tools remain in Python 3k?

I have have read several entries regarding dropping several functional functions from future python, including map and reduce. What is the official policy regarding functional extensions? is lambda ...

Building executables for Python 3 and PyQt

I built a rather simple application in Python 3.1 using PyQt4. Being done, I want the application to be distributed to computers without either of those installed. I almost exclusively care about ...