When using logging in Python, the locale is set, and the log cannot be obtained

55 views Asked by At

I'm trying to use logging module in Python. It works well expect when I set the loacle.

Here is the sample code(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")

The program exit with: Process finished with exit code -1073740940 (0xC0000374)

When I check test.log. I only got this:

2023-07-14 10:37:43 - root - INFO - before

It missed that log record of after.

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.

I want to know why when I set the locale, the logging can't works anymore. And I want to know how to get log after when I set the locale in Python like that.

1

There are 1 answers

1
steveha On

When I run the code you showed, the program terminates and I get a stack backtrace that shows the error. In my case, the error is:

locale.Error: unsupported locale setting

This is an exception that was raised because my system does not support the requested locale.

If you are not getting a stack backtrace, but it's silently quitting, that's more mysterious. It is possible to disable the stack backtrace.

Another thing you could try is to wrap the setlocale() call in a try: block and see what you get. Example:

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

In my case it prints the same exception I listed above.