Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to choose handler while logging in python

I am working on a project with python and I need to help about logging part. My logger have two handler(syslog and file log) and it send logs to both of them. Sometimes I need to send logs only one of them. How can I choose handler to be used? Thanks for help...

global my_Sysloghandler
global my_logger, my_log_handler

my_Sysloghandler=logging.handlers.SysLogHandler()
my_log_handler= logging.FileHandler('/var/log/{0}.log'.format(__project__))
my_log_handler.setFormatter(logging.Formatter('%(asctime)s %(message)s'))                                                                              
my_log_handler.setLevel(level)
my_logger= logging.getLogger('my_logger')
my_logger.addHandler(my_log_handler)
my_logger.addHandler(my_Sysloghandler)

my_logger.debug('This log is sent to both handler but I want to send it only my_logger')
like image 400
ibrahim Avatar asked Nov 04 '22 09:11

ibrahim


1 Answers

I think your choices are:

  • Prioritize one over the other (i.e. SysLogHandler gets INFO messages or above, while FileHandler gets DEBUG or above)
  • Use two different logger instances.

FWIW, the regular logging docs can be tough to read through. Instead, take a look at the Logging HOWTO and Logging Cookbook for something more easily digestible.

like image 200
Raymond Hettinger Avatar answered Nov 09 '22 08:11

Raymond Hettinger