我正在尝试编写一个模块,以便在不同的脚本中使用它
import logging
from logging.handlers import RotatingFileHandler
_logger_name = "Nagios"
_print_format = "%(asctime)s - %(levelname)s - %(message)s"
_level = logging.DEBUG
class Log():
def __init__(self,log_file,logger_name=_logger_name,level=_level):
self.log_file = log_file
self.logger_name = logger_name
self.level = level
def getLog(self):
"""
Return the logging object
"""
_logger = logging.getLogger(self.logger_name)
_logger.setLevel(self.level)
_logger.addHandler(self._rotateLog())
return _logger
def _rotateLog(self):
"""
Rotating the log files if it exceed the size
"""
rh = RotatingFileHandler(self.log_file,
maxBytes=20*1024*1024, backupCount=2)
formatter = logging.Formatter(_print_format)
rh.setFormatter(formatter)
return rh
log = Log("kdfnknf").getLog()
log("hello")
我看到以下错误:
Traceback (most recent call last):
File "nagiosLog.py", line 45, in <module>
log("hello")
TypeError: 'Logger' object is not callable
知道我为什么会收到这个错误,
当使用pdb调试时,我确实看到它返回对象并打印dir(log)我没有看到其中的Logger模块。
我在这里错过了一些东西
请参阅logging文档:
你必须使用一个函数,你不能只调用Logger:
Logger.info(msg,* args,** kwargs)
在此记录器上记录级别为INFO的消息。参数被解释为debug()。
要么
Logger.warning(msg,* args,** kwargs)
在此记录器上记录级别为WARNING的消息。参数>解释为debug()。
所以相反,做:
log.info("Test info level logging...")
log("Hello")
这是错的。正确的是
log.info("Hello")
日志必须打印日志级别,即信息/错误/警告