简体   繁体   中英

Python logging ValueError to be recorded to .log file

I started playing/learning python logging and I am stuck with some basics and would like to see where I am wrong.

I know there is another solution to check whether the entered number is int/float but I would like to "catch" this error with logger info.

Let's say this is an example:

import logging

logging.basicConfig(filename='myapp.log', level=logging.INFO, format='%(asctime)s :: %(levelname)s :: %(message)s')

def sum(x,y):
    return x+y

if __name__ == '__main__':

    x=float(input('Enter first number:'))
    y=float(input('Enter second number: '))    
   
    sum(x,y)
    logging.info (f"SUM of the numbers is: {sum(x,y)} ")
    logging.debug(f"SUM of the numbers is: {sum(x,y)}")
    logging.warning(f"SUM of the numbers is: {sum(x,y)}")
    logging.error(f"SUM of the numbers is: {sum(x,y)}")
    logging.critical(f"SUM of the numbers is: {sum(x,y)}")

Now, if I enter the second input "bla" in the terminal I get the error: ValueError: could not convert string to float: 'bla'. My question is: how to catch this error in my.log file?

Thank you in advance.

The problem is that the you are directly casting the second number as float when your actual input is a string. This raises the ValueError exception and the code stops.

If you want to simply catch such error you can do something like the following:

import logging

logging.basicConfig(filename='myapp.log', level=logging.INFO, format='%(asctime)s :: %(levelname)s :: %(message)s')

def sum(x,y):
    return x+y

if __name__ == '__main__':
    try:
        x = float(input('Enter first number:'))
        y = float(input('Enter second number: '))
    except ValueError as e:
        logging.error(e)

    sum(x, y)
    logging.info(f"SUM of the numbers is: {sum(x, y)} ")
    logging.debug(f"SUM of the numbers is: {sum(x, y)}")
    logging.warning(f"SUM of the numbers is: {sum(x, y)}")
    logging.error(f"SUM of the numbers is: {sum(x, y)}")
    logging.critical(f"SUM of the numbers is: {sum(x, y)}")

@SebastianT has shown you what to do if you want your program to log errors instead of quitting when an error happens. This is called "handling an exception."

However, to give you some more 'theory' on this: In POSIX systems like Linux, the norm is for programs to just print their error messages to "Standard Error" and for the operating system to capture standard error to a file. This way, the program can't run into issues where it is encountering an error and even its own ability to write to a file is lost and therefore the error messages are lost.

So, I would propose that the actual solution to your problem is not to write your logs to a file from within your code. Instead, redirect your error output to a file as described here .

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