简体   繁体   中英

Between raise Error and logging the Error, which one is a better practice in Python?

Python tutorial have a section called Errors and Exceptions which use the structure as;

try:
    [statement]
except [Built-in ExceptionType]:
    do something when an exception has been captured.
finally:
    do something whether exception occurred or not.

This can also handle by raise an Error directly, too.

try:
    raise [Built-in ExceptionType]
except [Built-in ExceptionType above] as e:
    print(f'foo error: {e}')

There are several built-in ExceptionType which the good practice is developer should catch every specific exceptions type that developer should look for. (refer from Why is "except: pass" a bad programming practice? )

However, after I reading logging section. I'm thinking about I want to log the error into the log file and let user to aware the error (maybe just print the text and user can inform IT support) rather than throwing an exception on screen. Therefore, instead of try / except combo above then I can use the following error message and logged it.

if len(symbol) != 1:
    error_message = f'Created box with symbol={symbol}, width={width} and height={height}, Symbol needs to be a string of length 1'
    logger.error(error_message)
    print(f'\nError! symbol={symbol}, width={width} and height={height} -- Symbol needs to be a string of length 1')
    return

I doubt that what the better current practice is between:

a) raise Error on screen and

b) logging the Error for further investigation?

c) Other method (please suggest me)

I hope that I'm not try to comparing two different things.For me, I want to choose b) and store the error in log. this is easier for investigation and does not give unnecessary information to the users. but I do not sure I'm on the right track or not. Thank you very much.

Logging and raising exceptions are two different things for two different purposes. Logs let you inspect what your program did after the fact. Raising exceptions has important effects on the program flow right now . Sometimes you want one, sometimes you want the other, sometimes you want both.

The question is always whether an error is expected or unexpected, whether you have some plan what to do in case it occurs, and whether it is useful to notify anyone about the occurrence of the error or not.

Expected errors that you have a "backup plan" for should be caught and handled, that is regular program control flow. Unexpected errors probably should halt the program, or at least the particular function in which they occurred. If a higher up caller feels like handling the exception, let them. And whether to log an error or not (in addition to handling or not handling it) depends on whether anyone can glean any useful insight from that log entry or whether it would just be noise.

You should log all errors no matter if they are thrown or handled for log analysis and refactoring amongst other purposes.

Whether to throw or to handle the error usually depends on the intended purpose of the code and the severity of the error.

Although "throwing" should be only used in debugging and handled 'gracefully' by dedicated exception code in the production version of the application. No user likes crashes.

  • If the error impacts the business logic, end result of the code, or can cause damages to the user of the software , you want to terminate the execution. You do it either by throwing the error or handling it through a dedicated error handling procedure that shutdowns the program.
  • If the error is not severe and does not impact the normal functionality of the program, you can choose whether you want to handle it or throw it based on the best practices in your team and requirements of the project.

As deceze already mentions, logging and exceptions are two totally distinct things. As a general rule:

  • you raise an exception when you encounter an unexpected / invalid condition that you cannot handle at this point of the code. What will became of this exception (whether someone up in the call stack will handle it or not) is none of your concern at this point

  • you only catch an exception when you can handle it or when you want to log it (eventually with additionnal context informations) THEN reraise it

  • at your application's top-level, you eventually add a catchall exception handler that can log the exception and decide on the best way to deal with the situation depending on the type of application (command-line script, GUI app, webserver etc...).

Logging is mostly a developper/admin tool used for post-mortem inspection, program behaviour analysis etc, it's neither an error handling tool nor an end-user UI feature. Your example:

if len(symbol) != 1:
    error_message = f'Created box with symbol={symbol}, width={width} and height={height}, Symbol needs to be a string of length 1'
    logger.error(error_message)
    print(f'\nError! symbol={symbol}, width={width} and height={height} -- Symbol needs to be a string of length 1')
    return

is a perfect antipattern . If your function expects a one character string and the caller passed anything else then the only sane solution is to raise an exception and let the caller deal with it. How it does is, once again, none of your concerns.

From the Docs :

Returns a new instance of the SMTPHandler class. The instance is initialized with the from and to addresses and subject line of the email. The toaddrs should be a list of strings. 

logging.handlers.SMTPHandler can be used to send logged error message.

    import logging
    import logging.handlers

    smtp_handler = logging.handlers.SMTPHandler(mailhost=("example.com", 25),
                                        fromaddr="from@example.com", 
                                        toaddrs="to@example.com",
                                        subject="Exception notification")
    logger = logging.getLogger()
    logger.addHandler(smtp_handler)

you can break the logic here if the code execution needs to be stopped.

Also look around this answer i have referred earlier collate-output-in-python-logging-memoryhandler-with-smtphandler

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM