我需要使用socket
日志记录配置文件中标准库中定义的常量。问题,当读取配置文件时,logging.config.fileConfig()
其结尾为:
NameError: name 'socket' is not defined
我的问题与这一问题非常接近,不同之处在于,作为一种解决方法,如果我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=
作为另一个解决方法,我尝试了此处建议的解决方案:如何使用python的fileConfig使用日志记录并配置日志文件文件名,但是由于socket.SOCK_STREAM不是字符串(而且我找不到任何可以在文档中使用的类型,所以这都不起作用:https : //docs.python.org/3.4/library/string.html#formatspec)。
我也曾尝试socket.SOCK_STREAM
用1代替(因为socket.SOCK_STREAM == 1
是True),但是它都不起作用(socket.SOCK_STREAM不是int ...)。
我希望避免将日志记录配置文件转换为字典(但是如果没有其他解决方案,则可以这样做)。
如本节文档所述,在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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句