0

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)
2

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Already >>>logging.basicConfig(filename="E:\logs\mathslogs.log"<<< this step is done. So no need to again open a file and write. Automatically log.error will right inside it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.