Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
general python help
#1
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
Reply
#2
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)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python can - general question caslor 0 1,123 Jul-14-2022, 05:21 PM
Last Post: caslor
  General question about serialization/deserialization in python local 1 1,852 Jan-28-2020, 04:35 AM
Last Post: Larz60+
  General reference for Python FLAJA 1 1,615 May-22-2019, 06:41 AM
Last Post: heiner55
  Python with email forms, and frontend code in general MattH 4 3,423 Feb-18-2018, 03:29 AM
Last Post: MattH

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020