我正在尝试使用RotatingHandler
用于 Python 中的日志记录目的。我将备份文件保留为 500 个,这意味着我猜它将创建最多 500 个文件,并且我设置的大小是 2000 字节(不确定建议的大小限制是多少)。
如果我运行下面的代码,它不会将所有内容记录到文件中。我想将所有内容记录到文件中 -
#!/usr/bin/python
import logging
import logging.handlers
LOG_FILENAME = 'testing.log'
# Set up a specific logger with our desired output level
my_logger = logging.getLogger('agentlogger')
# Add the log message handler to the logger
handler = logging.handlers.RotatingFileHandler(LOG_FILENAME, maxBytes=2000, backupCount=100)
# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
my_logger.addHandler(handler)
my_logger.debug('debug message')
my_logger.info('info message')
my_logger.warn('warn message')
my_logger.error('error message')
my_logger.critical('critical message')
# Log some messages
for i in range(10):
my_logger.error('i = %d' % i)
这就是我的打印出来的内容testing.log
file -
2013-11-22 12:59:34,782 - agentlogger - WARNING - warn message
2013-11-22 12:59:34,782 - agentlogger - ERROR - error message
2013-11-22 12:59:34,782 - agentlogger - CRITICAL - critical message
2013-11-22 12:59:34,782 - agentlogger - ERROR - i = 0
2013-11-22 12:59:34,782 - agentlogger - ERROR - i = 1
2013-11-22 12:59:34,783 - agentlogger - ERROR - i = 2
2013-11-22 12:59:34,783 - agentlogger - ERROR - i = 3
2013-11-22 12:59:34,783 - agentlogger - ERROR - i = 4
2013-11-22 12:59:34,783 - agentlogger - ERROR - i = 5
2013-11-22 12:59:34,783 - agentlogger - ERROR - i = 6
2013-11-22 12:59:34,784 - agentlogger - ERROR - i = 7
2013-11-22 12:59:34,784 - agentlogger - ERROR - i = 8
2013-11-22 12:59:34,784 - agentlogger - ERROR - i = 9
它不打印出来INFO
, DEBUG
以某种方式将消息写入文件中。有什么想法为什么它不起作用?
而且,现在,我已经在这个 python 文件中定义了所有内容以用于日志记录。我想在中定义上述内容logging conf
文件并使用读取它fileConfig()
功能。我不知道如何使用RotatingFileHandler
中的示例logging.conf
file?
UPDATE:-
下面是我更新后的 Python 代码,我已对其进行了修改以用于log.conf
file -
#!/usr/bin/python
import logging
import logging.handlers
my_logger = logging.getLogger(' ')
my_logger.config.fileConfig('log.conf')
my_logger.debug('debug message')
my_logger.info('info message')
my_logger.warn('warn message')
my_logger.error('error message')
my_logger.critical('critical message')
# Log some messages
for i in range(10):
my_logger.error('i = %d' % i)
下面是我的log.conf file
-
[loggers]
keys=root
[handlers]
keys=logfile
[formatters]
keys=logfileformatter
[logger_root]
level=DEBUG
handlers=logfile
[logger_zkagentlogger]
level=DEBUG
handlers=logfile
qualname=zkagentlogger
propagate=0
[formatter_logfileformatter]
format=%(asctime)s %(name)-12s: %(levelname)s %(message)s
[handler_logfile]
class=handlers.RotatingFileHandler
level=NOTSET
args=('testing.log',2000,100)
formatter=logfileformatter
但每当我编译它时,这就是我在控制台上收到的错误 -
$ python logtest3.py
Traceback (most recent call last):
File "logtest3.py", line 6, in <module>
my_logger.config.fileConfig('log.conf')
AttributeError: 'Logger' object has no attribute 'config'
知道我在这里做错了什么吗?