Disabling Logging Handler for a Second

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri May 22 23:56:43 EDT 2009


En Fri, 22 May 2009 08:26:49 -0300, VenkataRamaKrishna Boddu  
<bvrkchowdary at yahoo.co.in> escribió:

> Is there any way, I can disable one logging Handler, while other Log  
> Handler are still available for servicing.....

> import logging;
> import sys;
>
> thelog = logging.getLogger('app.scsi.cdb');
> strmHdlr = logging.StreamHandler(sys.stdout);
> fHdlr = logging.FileHandler('a.log')

Please don't use ; to end statements. In Python, ; is a statement  
*separator*, only required when putting two or more statements in a single  
line. This is very rarely done; I bet most Python users don't even know  
about ;

> ## Now, I want to disable the strmHdlr for some moment without
> ## actually removing the Handler from logger Object,
> ## I want to say something like
> ##
> ## thelog.disable('StreamHandler');
> ##
> ## So., that it disables all the Stream Handlers attached to the Logger  
> Object
>
> ## The Need for me is that, I should write My Email Id only to File  
> Stream
> ## and because of some reasons of moduler design, I don't have  
> references to the
> ## both the Handlers
>
> ## Here, I don't have want to do the StreamHandler removing stuff and  
> adding it again later on
> thelog.removeHandler(strmHdlr);
> thelog.info('Email: bvrkchowdary at yahoo.co.in');

Instead of disable/enable handlers (or remove/reinsert them), use any of  
these:

- Levels: loggers have a minimum level to process, and handlers too. If  
you set the StreamHandler to a slightly higher level than the others, it  
won't process certain messages. You may use the existing level names, or  
create a new one (logging.addLevelName), let's say DETINFO = INFO-5  
(DETailed INFO). Set the logger and the file handler level both to  
DETINFO, and the stream handler to INFO. Then use DETINFO to log the email.

- Filters: You can install a filter onto the stream handler (using  
handler.addFilter) that rejects any record whose msg starts with 'Email:'  
(or whatever you consider apropiate)

-- 
Gabriel Genellina




More information about the Python-list mailing list