The logging Module Interface of python is similar to log4j. It is similar in concept and convenient to use. Logging. config. fileconfig () can be used to describe the log configuration in a file, which simplifies log initialization.
Routine:
# test.py
import logging
import logging.config
logging.config.fileConfig("logging.conf")
#create logger
logger = logging.getLogger("example")
#"application" code
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
logHello = logging.getLogger("hello")
logHello.info("Hello world!")
The configuration file is as follows:
# logging.conf
[loggers]
keys=root,example
[handlers]
keys=consoleHandler,rotateFileHandler
[formatters]
keys=simpleFormatter
[formatter_simpleFormatter]
format=[%(asctime)s](%(levelname)s)%(name)s : %(message)s
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_example]
level=DEBUG
handlers=rotateFileHandler
qualname=example
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[handler_rotateFileHandler]
class=RotatingFileHandler
level=INFO
formatter=simpleFormatter
args=('test.log', 'a', 200000, 9)
Note: In rotatingfilehandler, dorolover () Exits midway through because of a Rename () error. As a result, the log file is not opened, and subsequent log messages fail because the log file is not opened. You can add a try in Rename () or do not use rotatingfilehandler. It is estimated that fileconfig () can be restored once after a period of time.
For details, see: Python logging rotatingfilehandler bug. This error occurs only when the log file is full and the file is switched over. An error occurs when the file is locked. Normal use is normal, and log errors do not affect the operation of the main program. So you can safely use it. If you want to be more reliable, add a try in the source code.
File from: http://www.cppblog.com/jinq0123/archive/2007/09/03/usingloggingconfig.html