用于文件处理程序并在Python中显示的不同日志记录级别 [英] Different logging levels for filehandler and display in Python
问题描述
我正在Python中使用logging
模块来编写调试和错误消息.
I am using the logging
module in Python to write debug and error messages.
我想将所有logging.DEBUG
或更高级别的消息写入文件.
I want to write to file all messages of logging.DEBUG
or greater.
但是,我只想在屏幕上打印logging.WARNING
或更高版本的消息.
However, I only want to print to the screen messages of logging.WARNING
or greater.
是否可以仅使用一个Logger
和一个FileHandler
?
Is this possible using just one Logger
and one FileHandler
?
推荐答案
如上所述,处理程序非常易于创建和添加,以至于最好只使用两个处理程序.但是,如果由于某些原因您要坚持使用,请
As it has been mentioned, handlers are so easy to create and add that you're probably better off just using two handlers. If, however, for some reason you want to stick to one, the Python logging cookbook has a section describing more or less what you want to do: logging to both console and file, but at different levels (it even shows you how to do different formatting). It does it with a single StreamHandler
rather than a FileHandler
, though:
import logging
# set up logging to file - see previous section for more details
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M',
filename='/temp/myapp.log',
filemode='w')
# define a Handler which writes INFO messages or higher to the sys.stderr
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# set a format which is simpler for console use
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
# Now, we can log to the root logger, or any other logger. First the root...
logging.info('Jackdaws love my big sphinx of quartz.')
# Now, define a couple of other loggers which might represent areas in your
# application:
logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')
logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')
如注释中所讨论,此代码仍生成两个处理程序,但通过使用basicConfig()隐藏一种"构造.我强烈建议您同时创建两者.
As discussed in the comments this code still generates two handlers, but "hides" one construction through the use of basicConfig(). I would strongly encourage you to create both explicitly.
这篇关于用于文件处理程序并在Python中显示的不同日志记录级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!