Skip to main content

A Django app for logging custom application errors

Project description

exceptions_and_logging

A Django app for logging custom application errors on the server side and also spits out JSON error info on the client side. You basically subclass our ApplicationErrors class and the rest is done for you.

Dependencies

  • Django Rest Framework
  • PyYaml

Installation

In your virtual environment run:

pip install exceptions-and-logging

Usage

  1. Add exceptions_and_logging to your Django installed apps:
# settings.py

INSTALLED_APPS = [
    ...

    'exceptions_and_logging',
]
  1. Without logging config.
# your_app.exceptions.py (or wherever your app exceptions are)

from exceptions_and_logging.exceptions import ApplicationErrors

class MyCustomException(ApplicationErrors):
    default_message = "This item: '%(item_name)s' isn't supposed to be null"

    def __init__(self, item_name):
        message = self.default_message % {"item_name": item_name}
        super().__init__(message)

When this error is raised:

  • Generated response on the client side (via Rest Framework):

    • {
        "error":{
            "type":"MyCustomException",
            "message":"This item: 'SomeItem' isn't supposed to be null",
            "code":"error"
            }
      }
      
    • An HTTP 500 Application Error response is returned.

  • Generated log on the server console (stdout):

    • 02/15/2021 04:30:34 PM - APPLICATION ERROR - ERROR
      Error Type: MyCustomException
      Error Message: This item: 'SomeItem' isn't supposed to be null
      Traceback (most recent call last):
        # Bunch of traceback info
        ...
        ...
          raise NullError("SomeItem")
      your_app.exceptions.MyCustomException: This item: 'SomeItem' isn't supposed to be null
      
  1. With Logging Config
# your_app.exceptions.py (or wherever your app exceptions are)

from exceptions_and_logging.exceptions import ApplicationErrors

# Path to your logging config file
module_dir = os.path.dirname(__file__)
config_file = os.path.join(module_dir, "myconfig.yaml")

class MyCustomException(ApplicationErrors):
    default_message = "This item: '%(item_name)s' isn't supposed to be null"
    log_config = config_file 	# Can also be a dict config

    # If no logger name is passed, it will use the default logger name.
    def __init__(self, item_name, logger_name=None):
        message = self.default_message % {"item_name": item_name}
        super().__init__(message, logger_name=logger_name)
  • The ApplicationError class provides hooks for adding extra format strings to the logging message and also extra key, value pairs for the error dict.

  • # Assuming your formatter has extra values like user_id and user_email
    msg_format = '%(asctime)s - APPLICATION ERROR - %(levelname)s\n' \
                 'User Email: %(user_email)s\n' \
        	     'User ID: %(user_id)s\n'\
                 'Error Message: %(message)s\n'
    
    class MyCustomException(ApplicationErrors):
        def __init__(self, user_id, user_email, **err_dict_kwargs):
            self.user_id, self.user_email = user_id, user_email
            super().__init__(**err_dict_kwargs)
    
        # Override this method to return extra kwargs for logging
        def extra_kwargs(self) -> dict:
            dict_ = {
                "user_id": self.user_id,
                "user_email": self.user_email
            }
            return dict_
    
    # in views.py
    
    from rest_framework.views import APIView
    
    from .exceptions import MyCustomException
    
    class TestException(APIView):
    
        def get(self, request):
            raise MyCustomException(
            	"id4", "name@gmail.com", foo="bar", hot="soup"
            	)
    

    Generated response on the client side via Rest Framework:

    {
        "error":{
            "type":"MyCustomException",
            "message":"An application error occurred.",
            "code":"error",
            "foo":"bar",
            "hot":"soup"
        }
    }
    

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

exceptions_and_logging-0.0.2.tar.gz (4.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

exceptions_and_logging-0.0.2-py3-none-any.whl (7.0 kB view details)

Uploaded Python 3

File details

Details for the file exceptions_and_logging-0.0.2.tar.gz.

File metadata

  • Download URL: exceptions_and_logging-0.0.2.tar.gz
  • Upload date:
  • Size: 4.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.23.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.57.0 CPython/3.7.4

File hashes

Hashes for exceptions_and_logging-0.0.2.tar.gz
Algorithm Hash digest
SHA256 03e4326c396327474afa17336cee03cb9db81cee36f48a86fb2c66dec95d83b1
MD5 5cd53ba65acdfb3abf37a010295eff0f
BLAKE2b-256 748a6a6b967011d5806ff63e5cb8b36d2b2d0b13c8589f9ef47c70733dc6962b

See more details on using hashes here.

File details

Details for the file exceptions_and_logging-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: exceptions_and_logging-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 7.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.3.0 pkginfo/1.7.0 requests/2.23.0 setuptools/40.8.0 requests-toolbelt/0.9.1 tqdm/4.57.0 CPython/3.7.4

File hashes

Hashes for exceptions_and_logging-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 5741a22e6690efbfaa60cb58fa04e34120b9326f830cd6d77eee4cddc603f230
MD5 439c442c33031858397758122bf05459
BLAKE2b-256 9f777cabc1f26a71c067c28c13ddb2857abfce559c67c13b965723eb9d072472

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page