Inderpal Singh
Inderpal Singh

Reputation: 270

Customizing exceptions in python. How to log errors?

I am customizing exceptions in my python code. I have inherited exception class in to other and now defining some custom errors as classes derived from my custom exception class like this:

class DataCollectorError(Exception): pass
class ParamNullError(DataCollectorError) : pass
class ParamInvalidTypeError(DataCollectorError) : pass

I am raising these exceptions in my python function like:

def READ_METER_DATA (regIndex, numRegisters, slaveUnit):
    if not regIndex:
        raise ParamNullError, "register index is null"

    if not numRegisters:
        raise ParamNullError, "number of registers should not be null"

    if not slaveUnit:
        raise ParamNullError, "Meter Id should not be null"

    if(isinstance(regIndex, int) == False):
        raise ParamInvalidTypeError, "register index passed is not int"

    if(isinstance(numRegisters, int) == False):
        raise ParamInvalidTypeError, "number of registers passed is not int"

Now I want to log error messages into log file using logger but don't know where to do it.

  1. should I do it by putting that function code in try catch but then how will I be getting those error messages
  2. should I do it inside custom error class I have created (DataCollectorError)
  3. or in individual error classes like ParamNullError etc.

But then I don't know where and how to get that error message to log them.

Upvotes: 2

Views: 1759

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121604

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

When your application catches an exception, use the logging.exception() function to log it; the exception is automatically added to the log entry:

log = logging.getLogger('some-identifier')

try:
    #
except DataCollectorError:
    log.exception('An error occurred')

Exceptions have a .args tuple argument by default, and the first value in that tuple is your message.

Some style feedback on your code:

  • Don't test for == False. Rather, use not:

    if not isinstance(regIndex, int):
    
  • Raise instances of your exception:

    raise ParamNullError("register index is null")
    

    rather than the raise class, message style, to make it easier to move to Python 3.

Upvotes: 5

Related Questions