Python Forum

Full Version: general python help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a function
def abc(self):
try:
  handler = logging.FileHandler(logpath)
  handler.setFormatter(formatter)
  logger.addHandler(handler)
 except:
    logger.info("abc")

def xyz(self):
 ..some code..
I am not able to access the logger in except block for func abc.Is there any way such that i can log the error occuring in function abc or
Is it possible to throw the exception to xyz and log it in xyz
Can have boilerplate code for logging separate.
Example:
import my_log

def xyz(x, y):
   try:
       return(x + y)
   except Exception as error:
       my_log.logger.exception('msg')

if __name__ == '__main__':
   my_log.logger.info('Start')
   value = xyz(33, 50)
   # value = xyz(33, '50') # make error
   my_log.logger.debug(value)
   my_log.logger.info('Finish')
   print(value)
logg.log:
Output:
2018-07-09 20:56:52,397 - my_log - INFO - Start 2018-07-09 20:56:52,397 - my_log - DEBUG - 83 2018-07-09 20:56:52,397 - my_log - INFO - Finish 2018-07-09 20:57:20,748 - my_log - INFO - Start 2018-07-09 20:57:20,748 - my_log - ERROR - msg Traceback (most recent call last): File "C:\code\log\code.py", line 5, in xyz return(x + y) TypeError: unsupported operand type(s) for +: 'int' and 'str' 2018-07-09 20:57:20,749 - my_log - DEBUG - None 2018-07-09 20:57:20,749 - my_log - INFO - Finish
Logger setup that gets import:
# my_log.py
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# create a file handler
handler = logging.FileHandler('logg.log')
handler.setLevel(logging.DEBUG)

# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# add the handlers to the logger
logger.addHandler(handler)