简体   繁体   English

在Python中设置语言环境以进行日志记录

[英]setting locale in Python for logging

I'm trying to use the Python logging framework. 我正在尝试使用Python日志框架。 It works well except for one thing. 除了一件事,它运作良好。

This sample code: 此示例代码:

import logging

FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
logging.info('test')

produces this output: 产生这个输出:

2014-03-18 11:23:43,082 test

Note the comma rather than "." 请注意逗号而不是“。” separating seconds from milliseconds. 将秒与毫秒分开。 We are in the USA and there should be a setting somewhere which controls this. 我们在美国,应该有一个控制这个的地方。

What can I set so that the default locale info uses a period "." 我可以设置什么,以便默认的区域设置信息使用句点“。”。 for a decimal separator? 小数分隔符?

The milliseconds are not part of the locale - you can't specify them using eg strftime . 毫秒不是语言环境的一部分 - 您不能使用例如strftime指定它们。 Hence the ,nnn with the milliseconds is tacked on explicitly as per ISO 8601 . 因此,nnn根据ISO 8601 ,明确地加上具有毫秒的,nnn

Update: Although the standard allows for a dot or a comma, it implies that a comma is preferred. 更新:虽然标准允许使用点或逗号,但它表示首选逗号。 Currently, logging doesn't allow this to be configurable, so if you need this, refer to this answer in the duplicate question. 目前,日志记录不允许这是可配置的,因此如果您需要,请在重复的问题中参考此答案

Try this at basicConfig: 在basicConfig试试这个:

logging.basicConfig(format=FORMAT, level=logging.INFO, datefmt="%Y-%m-%d %H:%M:%S")

instead of : or - in my code, you can use any character if you wish. 而不是:或 - 在我的代码中,如果你愿意,你可以使用任何字符。

Output: 输出:

2014-03-19 00:48:22 test

The following code snippet, after the logging.basicConfig() call, works for me in Python 3.4: logging.basicConfig()调用之后,以下代码片段在Python 3.4中适用于我:

for h in logging.getLogger().handlers:
    h.formatter.default_msec_format = '%s.%03d'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM