我需要在日志配置文件中使用标准库 socket 中定义的常量。问题,当使用 logging.config.fileConfig() 读取配置文件时,它以:
NameError: name 'socket' is not defined
我的问题非常接近 this one ,不同之处在于,如果作为解决方法,我从读取此日志记录配置文件的主脚本中导入缺少的库(例如 socket),它不能解决问题(这是因为我使用python3?)。
完整的日志配置文件:
[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=
作为另一种解决方法,我尝试了此处建议的解决方案:How to use logging with python's fileConfig and configure the logfile filename但这都不起作用,因为 socket.SOCK_STREAM 不是字符串(而且我在文档中找不到任何可以工作的类型:https://docs.python.org/3.4/library/string.html#formatspec)。
我也尝试用 1 替换 socket.SOCK_STREAM(因为 socket.SOCK_STREAM == 1 为 True)但它也不起作用(socket.SOCK_STREAM不是一个 int...)。
我希望避免将日志记录配置文件转换为字典(但如果没有其他解决方案,我会这样做)。
请您参考如下方法:
记录在案in this section of the docs ,这些值在 logging 包的命名空间中进行评估。因此,您可以这样做:
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
