将字符串添加到线程名称的末尾

Add string to end of thread name

我正在使用日志模块打印一些数据。这是我的代码:

logging.basicConfig(
    format="%(asctime)s [%(threadName)s] [%(levelname)s]  %(message)s",
    level=logging.INFO,
    handlers=[
        logging.FileHandler("{0}/{1}.log".format(logPath, fileName)),
        logging.StreamHandler(sys.stdout)
    ]
)

我想将一些数据附加到线程名称的末尾,如下所示:

2018-10-30 19:43:54,304 [Thread-2 %SOME INFO%] [WARNING] Foo bar baz

我该怎么做?

Logger class 的 "log" 方法(调试,信息,警告,...)可以接受一个 extra 参数,它是一个字典,可以是用作自定义属性。 documentation 表示:

The second keyword argument is extra which can be used to pass a dictionary which is used to populate the __dict__ of the LogRecord created for the logging event with user-defined attributes. These custom attributes can then be used as you like. For example, they could be incorporated into logged messages.

在您的示例中,我们必须在 format 属性中添加新信息:

logging.basicConfig(
    format="%(asctime)s [%(threadName)s %(threadInfo)s] [%(levelname)s]  %(message)s",
    level=logging.INFO,
    handlers=[
        logging.FileHandler("{0}/{1}.log".format(logPath, fileName)),
        logging.StreamHandler(sys.stdout)
    ]
)

我们可以这样调用日志方法:

logging.info("Foo bar baz", extra={'threadInfo': 'SOME INFO'})