ibrahim
ibrahim

Reputation: 3404

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')

Upvotes: 8

Views: 3406

Answers (1)

Raymond Hettinger
Raymond Hettinger

Reputation: 226256

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.

Upvotes: 7

Related Questions