Viv
Viv

Reputation: 1584

How to log errors before the try- except loop in python?

I am trying to implement Python's logging library for log.

I understand that if something is wrapped in try-catch loop, the exception is caught.

But in one of my example, the import is failing which is the start of the script. This is not getting logged. ( It is only printing this in Jupyter's logs)

How to log these exceptions? Looking for not wrapping the entire script in try - except loop.

Any error on Jupyter or any IDE is printed in the console, why not with logger? isnt there any such implementation

Upvotes: 0

Views: 1157

Answers (2)

magor
magor

Reputation: 709

When using logger, you have to implement the logging of your errors.
In Python, errors are being logged only to the console by default.
So, if you want to use logger, you have to add your logic to catch and log your errors.

The try except block is a common way to handle import on Python.

Quoting Dive into Python:

There are a lot of other uses for exceptions besides handling actual error conditions. A common use in the standard Python library is to try to import a module, and then check whether it worked. Importing a module that does not exist will raise an ImportError exception. You can use this to define multiple levels of functionality based on which modules are available at run-time, or to support multiple platforms (where platform-specific code is separated into different modules).

The next example demonstrates how to use an exception to support platform-specific functionality.

try:
    import termios, TERMIOS                     
except ImportError:
    try:
        import msvcrt                           
    except ImportError:
        try:
            from EasyDialogs import AskPassword 
        except ImportError:
            getpass = default_getpass           
        else:                                   
            getpass = AskPassword
    else:
        getpass = win_getpass
else:
    getpass = unix_getpass

Upvotes: 2

Gidalti
Gidalti

Reputation: 41

The difference with IDE's logs or even if you run a python file from console or terminal is that as soon as the exception is caught the script is interrupted immediately.

If you want to get the exception and do something after it happens, to log it for instance, then you need to use the "try except" block.

I don't know why you are trying to avoid using the "try except" block as it is a basic feature of the language as any other decision-making blocks ("if", "while", "for", etc.).

Try to see it as a common "if" statement:

if trying this:
    works, great!
else:
    do something with this exception

Upvotes: 1

Related Questions