betontalpfa
betontalpfa

Reputation: 3742

Python logger exception to file

I use logging. The logger writes to file only. (and not to standard output.) In some cases logger raises exception from inside a logger method. My goal is say to logger not to write anything on to standard out/err, in case of any error at all. All internal exception should be handled internally, and should be written into the log file.


Details:

My logger raised charmap error. This particular issue has been solved based on this thread. But I afraid of that in a specific case, other exception can occur (file IO error, etc), on the field, which is very frustrating, that the logger fails, while the system works. I want to ensure that the logger don't print anything on standard out/err at all.


My expected behavior is something like this:

try:
    logger.debug('Some error maker')
except:
    try:
        logger.debug('Error during log')
    except:
        pass

Just, of course, I don't want to write try-except around all of my logger statement.

Is there anything similar feature in the logger? Something quiet mode?

Upvotes: 0

Views: 472

Answers (2)

sophros
sophros

Reputation: 16640

To improve over @mdgm answer you can use the built-in features of logging to log stack trace and details of the exception:

def my_logger(thing_to_log):
    try:
        logger.debug(thing_to_log)
    except Exception:
        try:
            logger.debug('Error during log', exc_info=True, stack_info=True)
        except Exception:
            pass

Upvotes: 0

mdgm
mdgm

Reputation: 224

What about a function like this?

def my_logger(thing_to_log):
    try:
        logger.debug(thing_to_log)
    except Exception:
        try:
            logger.debug('Error during log')
        except Exception:
            pass

In the rest of the code you'll only need:

my_logger(thing_to_log)

Upvotes: 1

Related Questions