1

I try to log handled exception from my Python Azure Function in Application Insights as exception. Whatever i do it is always written as track with error severity level. Output in local console is "red" as excepted.

What i tried:

  • Changing function.json logging section to:

    "ApplicationInsights": {
      "LogLevel": {
          "Default": "Error"
      } 
    
  • various calls of exception method

    except Exception as e:
        logger.exception("An error has occured",exc_info=e)
        logger.exception("An error has occured")
        logger.exception()
  • tried to call telmetry client directly
    tc.track_exception()
  • clearing and adding handlers to logger

Edit:

Example to clarify what i mean: image

5
  • Try this logger.error('My exception', exc_info=True) Commented Apr 7, 2020 at 9:40
  • Didn't work. Exception is still logged as trace with error severity level in application insights. Commented Apr 7, 2020 at 10:01
  • Maybe I didn't understand what you want. You'd like to log the exception as plain string ? Because, then use you'll have to use logger.error('My exception: {}.format(e)) Commented Apr 7, 2020 at 10:25
  • I would like to log my exception as exception in application insights. Currently it is logged as a trace Commented Apr 7, 2020 at 10:33
  • So isn't my below answer okay ? Gives you both formats. Commented Apr 9, 2020 at 16:49

2 Answers 2

2

Thanks to Orsiris de Jong after many hours of fight I found the solution:

handler = AzureLogHandler(connection_string = "instrmental key here")
handler.setLevel(logging.ERROR)
logger = logging.getLogger()
logger.propagate = False
if(handler not in logger.handlers):
    logger.addHandler(handler)
try:
    raise Exception("test")
except Exception as e:
    logger.exception('An error has occured', exc_info=True)

This handler changed trace into exception in Application Insights and resolved problem with double logging

Sign up to request clarification or add additional context in comments.

Comments

0

Logging the exception as plain text instead of logging a full trace goes like the following:

handler = AzureLogHandler(connection_string = "instrmental key here")
handler.setLevel(logging.ERROR)
logger = logging.getLogger()
logger.addHandler(handler)
try:
    raise Exception("test")
except Exception as e:
    # Logging as string
    logger.debug('The following error has occured: {0}'.format(e))
    # Logging as full trace
    # logger.debug('The following error was traced:', exc_info=True)

1 Comment

Hi, thank you for answer! When I added AzureLogHandler it started to work but now my excepions are logged twice.

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.