inheritance - Customizing exceptions in python. How to log errors? -


i customizing exceptions in python code. have inherited exception class in other , defining custom errors classes derived custom exception class this:

class datacollectorerror(exception): pass class paramnullerror(datacollectorerror) : pass class paraminvalidtypeerror(datacollectorerror) : pass 

i raising these exceptions in python function like:

def read_meter_data (regindex, numregisters, slaveunit):     if not regindex:         raise paramnullerror, "register index null"      if not numregisters:         raise paramnullerror, "number of registers should not null"      if not slaveunit:         raise paramnullerror, "meter id should not null"      if(isinstance(regindex, int) == false):         raise paraminvalidtypeerror, "register index passed not int"      if(isinstance(numregisters, int) == false):         raise paraminvalidtypeerror, "number of registers passed not int" 

now want log error messages log file using logger don't know it.

  1. should putting function code in try catch how getting error messages
  2. should inside custom error class have created (datacollectorerror)
  3. or in individual error classes paramnullerror etc.

but don't know , how error message log them.

just use standard logging module; it'll log exceptions with exception message out of box.

when application catches exception, use logging.exception() function log it; exception automatically added log entry:

log = logging.getlogger('some-identifier')  try:     # except datacollectorerror:     log.exception('an error occurred') 

exceptions have .args tuple argument default, , first value in tuple message.

some style feedback on code:

  • don't test == false. rather, use not:

    if not isinstance(regindex, int): 
  • raise instances of exception:

    raise paramnullerror("register index null") 

    rather raise class, message style, make easier move python 3.


Comments

Popular posts from this blog

php - mySql Join with 4 tables -

css - Text drops down with smaller window -

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -