What is the difference between warnings.warn()
and logging.warn()
in terms of what they do and how they should be used?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
logging.warning
just logs something at theWARNING
level, in the same way thatlogging.info
logs at theINFO
level andlogging.error
logs at theERROR
level. It has no special behaviour.warnings.warn
emits aWarning
, which may be printed tostderr
, ignored completely, or thrown like a normalException
(potentially crashing your application) depending upon the preciseWarning
subclass emitted and how you've configured your Warnings Filter. By default, warnings will be printed tostderr
or ignored.Warnings emitted by
warnings.warn
are often useful to know about, but easy to miss (especially if you're running a Python program in a background process and not capturingstderr
). For that reason, it can be helpful to have them logged. Python provides a built-in integration between thelogging
module and thewarnings
module to let you do this; just calllogging.captureWarnings(True)
at the start of your script and all warnings emitted by thewarnings
module will automatically be logged at levelWARNING
.One raises an exception which can be caught or ignored as desired, and the other optionally adds an entry to the log based on the current logging level. One should be used when one is warning about various things in code, and the other should be used when logging.
I agree with the other answer --
logging
is for logging andwarning
is for warning -- but I'd like to add more detail.Here is a tutorial-style HOWTO taking you through the steps in using the
logging
module. http://docs.python.org/2/howto/logging.htmlIt directly answers your question:
Besides the canonical explanation in official documentation
It is also worth noting that, by default
warnings.warn("same message")
will show up only once. That is a major noticeable difference. Quoted from official doc