-1

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)
Vinay Somawat
  • 639
  • 14
  • 23
Rizan Khan
  • 1
  • 1
  • 1
  • Please refer to this page. This will give your answer. https://stackoverflow.com/questions/55169364/python-how-to-write-error-in-the-console-in-txt-file – Surajit Mitra Jun 25 '20 at 03:36
  • Does this answer your question? [Python: How to write error in the console in txt file?](https://stackoverflow.com/questions/55169364/python-how-to-write-error-in-the-console-in-txt-file) – Rishit Dagli Jun 25 '20 at 06:18

2 Answers2

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
NAGA RAJ S
  • 452
  • 4
  • 12
  • 2
    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. – Surajit Mitra Jun 25 '20 at 03:40
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

M Z
  • 4,571
  • 2
  • 13
  • 27