尝试理解并学习如何编写包…用我一直使用的东西进行测试,记录…
你能帮助我理解为什么“log”变量不起作用…并且屏幕上没有记录任何内容吗?
谢谢!
main.py:
#!/opt/local/bin/python import sys sys.path.append('CLUSTER') import clusterlogging.differentlogging clusterlogging.differentlogging.consolelogging() log.debug("Successfully logged in")
不同的日志记录.py
#!/opt/local/bin/python def consolelogging(): import logging class NullHandler(logging.Handler): def emit(self, record): pass print "Console Logging loaded" DEFAULTLOGLEVEL=logging.INFO log = logging.getLogger(__name__) log.addHandler(NullHandler()) log.debug("Successfully logged in") def mysqllogging(): print "mysql logging module here" def sysloglogging(): print "rsyslog logging module here"
输出
Console Logging loaded Traceback (most recent call last): File "./svnprod.py", line 10, in <module> log.debug("Successfully logged in") NameError: name 'log' is not defined
问题的根本原因在于,log.debug("Successfully logged in") 的调用是在你定义 log 变量之前发生的。你在 differentlogging.py 中调用了 log.debug,但在调用之前,log 变量并没有被正确定义或初始化。
log.debug("Successfully logged in")
log
differentlogging.py
log.debug
main.py
consolelogging()
NameError
log.debug()
#!/opt/local/bin/python import sys sys.path.append('CLUSTER') import clusterlogging.differentlogging # Call the logging setup function clusterlogging.differentlogging.consolelogging() # Now log should be initialized and available log.debug("Successfully logged in")
#!/opt/local/bin/python import logging class NullHandler(logging.Handler): def emit(self, record): pass print("Console Logging loaded") DEFAULTLOGLEVEL = logging.INFO log = logging.getLogger(__name__) log.setLevel(DEFAULTLOGLEVEL) # Set default logging level log.addHandler(NullHandler()) # Add NullHandler to prevent errors when no handlers are added def consolelogging(): # Initialize the logger to ensure it's ready to use log.debug("Console logging initialized") # Now this will work because log is defined globally def mysqllogging(): print("mysql logging module here") def sysloglogging(): print("rsyslog logging module here")
clusterlogging.differentlogging.consolelogging()
log.debug("Console logging initialized")
如果你希望日志记录器能够在整个程序中使用,可以考虑将 log 作为全局变量,并通过 consolelogging() 函数进行初始化,使其可以在其他模块中共享。