This is my code printing logs also. If you will replace (1,0,-4) with (1,0,1) at the bottom of page, you will get an valueerror. So, I want to print this error in my mathslog.txt file,how to do it? Code is starting from here:
import logging
import math
LOG_FORMAT = "%(levelname)s - %(asctime)s - %(message)s"
logging.basicConfig(filename="E:\\logs\\mathslogs.log", level= logging.DEBUG, filemode='w',format= LOG_FORMAT ,datefmt= '%y/%m/%d %I:%M:%S %p')
logger = logging.getLogger()
def quadraticc_formula(a,b,c):
"""Return the solutions to the equation ax^2 + bx + c=0."""
logger.info("Calculating quadratic_formula for values ({0},{1},{2})".format(a,b,c))
#Compute the discrminant
logger.debug("#Compute the discriminant")
disc = b**2 - 4*a*c
# Compute the two roots
logger.debug("Compute the two roots")
root1 = (-b + math.sqrt(disc))/(2*a)
root2 = (-b - math.sqrt(disc))/(2*a)
#Return the roots
logger.debug("#Successfully Calculated")
return (root1,root2)
roots = quadraticc_formula(1,0,-4)
print(roots)
you can write this in log file also,by using exception to log.
try:
roots = quadraticc_formula(1,0,-4) print(roots)
except Exception as msg:
log.error(msg) #writes in log file
Another method, if you want to catch all uncaught exceptions in your logger, is to take advantage of sys
module's excepthook
. Doing this once will make all exceptions go through your logger. This leaves freedom for you to use try
except
blocks that actually make more sense programmatically.
# set the excepthook to route through your logger before you call quadraticc_formula
sys.excepthook = lambda type, value, tb: logger.exception(value)
Here's a link to a more thorough discussion: Using python's logging module to log all exceptions and errors
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.