PYTHON LOGGING with StreamHandler and FileHandler

Peter Otten __peter__ at web.de
Tue Nov 25 16:06:35 CET 2014


Ganesh Pal wrote:

> Thanks for the hint ,  I was able to get the error messages on the console
>  by setting the StreamHandler level to WARNING .
> 
> It works for  me know  but    one  LAST  question , it might sound simple,
> but  Iam not able to understand the difference between
> 
> - (a)   ch.setLevel(logging.WARNING)  and ch.setLevel(logging.ERROR) ,
> both are giving the same output for the below program .

Quoting 
<https://docs.python.org/2.7/library/logging.html#logging.Logger.setLevel>

"""
Logger.setLevel(lvl)
Sets the threshold for this logger to lvl. Logging messages which are less 
severe than lvl will be ignored.
"""

INFO is both below WARNING and ERROR. If you add

logger.warn("whatever")

to your code 'whatever' will disappear from your log when you switch the 
level from WARNING to ERROR.


> import logging
> import sys
> 
> # StreamHandler
> 
> formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -
> %(message)s')
> 
> root = logging.getLogger()
> ch = logging.StreamHandler(sys.stdout)
> ch.setLevel(logging.WARNING)  =========================> (  even with
> ch.setLevel(logging.ERROR) I get the same output )
> ch.setFormatter(formatter)
> root.addHandler(ch)
> 
> # FileHandler
> 
> ch1  = logging.FileHandler('/var/tmp/myapp1.log')
> ch1.setFormatter(formatter)
> logger = logging.getLogger('myapp')
> logger.setLevel(logging.DEBUG)
> logger.addHandler(ch1)
> logger.error('We have a problem')
> logger.info('While this is just chatty')
> 
> 
> # echo > /var/tmp/myapp1.log
> # python final_logger.py
> 2014-11-25 13:16:35,772 - myapp - ERROR - We have a problem
> # cat /var/tmp/myapp1.log
> 
> 2014-11-25 13:16:35,772 - myapp - ERROR - We have a problem
> 2014-11-25 13:16:35,773 - myapp - INFO - While this is just chatty
> 
> Regards,
> Ganesh
> 
> 
> 
> 
> On Tue, Nov 25, 2014 at 12:17 PM, dieter <dieter at handshake.de> wrote:
> 
>>
>> You read the handler related documentation of the logging module.
>> When I remember right, you will find there a method allowing you
>> to control which message levels are handled by the the respective
>> handler.
>>
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>





More information about the Python-list mailing list