如何在日志记录配置文件中引用标准库? [英] How to refer to a standard library in a logging configuration file?
问题描述
我需要在日志记录配置文件中使用在标准库socket
中定义的常量.问题,使用logging.config.fileConfig()
读取配置文件时,其结尾为:
I need to use a constant defined in the standard library socket
in a logging configuration file. Problem, when reading the config file with logging.config.fileConfig()
it ends with:
NameError: name 'socket' is not defined
我的问题非常接近这一个,不同之处在于,作为一种解决方法,如果我从读取此日志记录配置文件的主脚本中导入丢失的库(例如socket
),则不能解决问题(这是因为我使用python3吗?).
My question is very close to this one, the difference is that if, as a workaround, I import the missing library (e.g. socket
) from the main script reading this logging configuration file, it doesn't solve the problem (is this because I use python3?).
完整的日志记录配置文件:
Complete logging configuration file:
[loggers]
keys=root,mainLogger
[handlers]
keys=mainHandler,nullHandler
[formatters]
keys=defaultFormatter,rawMessageFormatter
[logger_root]
level=INFO
handlers=nullHandler
[logger_mainLogger]
level=DEBUG
handlers=mainHandler
qualname=mainLogger
[handler_nullHandler]
class=NullHandler
args=(50,)
[handler_mainHandler]
class=logging.handlers.SysLogHandler
level=INFO
formatter=defaultFormatter
args=('/dev/log','myapp',socket.SOCK_STREAM)
[formatter_defaultFormatter]
format=%(asctime)s.%(msecs)d %(filename)s: %(funcName)s: %(message)s
datefmt=%Y/%m/%d %H:%M:%S
[formatter_rawMessageFormatter]
format=%(message)s
datefmt=
作为另一个解决方法,我尝试了此处建议的解决方案: https://docs.python.org/3.4/library/string.html# formatspec ).
As another workaround I have tried the solution suggested here: How to use logging with python's fileConfig and configure the logfile filename but this neither works since socket.SOCK_STREAM is not a string (and I don't find any type that could work in the doc: https://docs.python.org/3.4/library/string.html#formatspec).
我还尝试将socket.SOCK_STREAM
替换为1(因为socket.SOCK_STREAM == 1
为True),但是它都不起作用(socket.SOCK_STREAM不是int ...).
I have also tried to replace socket.SOCK_STREAM
by 1 (since socket.SOCK_STREAM == 1
is True) but it doesn't work neither (socket.SOCK_STREAM not being an int...).
我希望避免将日志记录配置文件转换为字典(但是如果没有其他解决方案,则可以这样做).
I would have liked to avoid converting my logging configuration file into a dictionary (but will do that if there's no other solution).
推荐答案
如在文档的本部分中,这些值在logging
包的命名空间中进行评估.因此,您可以执行以下操作:
As documented in this section of the docs, the values are evaluated in the logging
package's namespace. Hence, you can do something like this:
import logging
import socket
# The next line allows 'socket' in the logging package's namespace to pick up
# the stdlib socket module
logging.socket = socket
...
# when the config file is processed, it should work as expected
logging.config.fileConfig(...)
# remove the mapping from the logging package, as not needed any more
# (optional)
del logging.socket
这篇关于如何在日志记录配置文件中引用标准库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!