Before using the logging module is just the internet casually searched a post, looked at the approximate method directly used. The problem now is that when you add a handler to a Logger object, you use Streamhandler in the configuration file, and you specify the output to stdout (the default is stderr). And since only one logger and one handler are used in the program, all log levels (INFO,DEBUG,ERROR, etc.) are redirected to a place that is standard output. But for now, the result is that log information such as error,critical should be exported to the stderr at the same time.
Went to see the official document on the logging module in the detailed explanation, only to find that the original logger object can be specified multiple handler, the Logger object of all the output will undergo multiple handler filter. And you can enter different log contents into two places by setting different level parameters on multiple handler.
Here's a simple example
#logging. conf
[loggers]
keys=root,simpleexample
[handlers]
Keys=consolehandler,filehandler
[formatters]
keys=simpleformatter
[logger_root]
level=debug
handlers=consolehandler
[ Logger_simpleexample]
level=debug
handlers=consolehandler,filehandler
propagate=0
qualname =simpleexample
[Handler_consolehandler]
class=streamhandler
level=debug
formatter= Simpleformatter
args= (Sys.stderr,)
[Handler_filehandler]
class=filehandler
level=warning
formatter=simpleformatter
args= (' SimpleExample.log ', ' W ')
[Formatter_simpleformatter]
format=% (asctime) s-% (name) s-% (levelname) s-% (message) s
#logging_test. py
Import Logging.config
Logging.config.fileConfig ("logging.conf")
log = Logging.getlogger (' simpleexample ')
log.info ("Log Info")
log.error ("Log Error")
You can see that in the configuration file above, you specify two handler for a logger, one for command-line output and one for the specified log file. Execute one and see the result:
[Wanghai01@tc-crm-rd03.tc test]$ python logging_test.py
2012-01-04 19:40:18,669-simpleexample-info-log INFO
2012-01-04 19:40:18,670-simpleexample-error-log ERROR
[Wanghai01@tc-crm-rd03 test]$ Cat SimpleExample.log
2012-01-04 19:40:18,670-simpleexample-error-log ERROR
As you can see, info and error are printed on the console handler, but only error information is in the log file.
Sentiment, encountered some details of the problem, sometimes search no more blog also useless, because people meet the needs and you are not the same, may not pay attention to this function point. Look at the official document or the King Ah, the following is the corresponding link: http://docs.python.org/library/logging.html