Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Avoid `logger=logging.getLogger(__name__)`

You can use logging.basicConfig to define the default interface available through logging as follows:

import logging
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)s.%(funcName)s +%(lineno)s: %(levelname)-8s [%(process)d] %(message)s',
                    )

This definition will now be used whenever you do the following anywhere in your application:

import logging
logging.error(...)

While __name__ is not available, the equivalent (and other options) are available through the default LogRecord attributes that can be used for error string formatting - including module, filename and pathname. The following is a two-script demonstration of this in action:

scripta.py

import logging
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(module)s %(name)s.%(funcName)s +%(lineno)s: %(levelname)-8s [%(process)d] %(message)s',
                    )

from scriptb import my_view

my_view()

scriptb.py

import logging

def my_view():
    # Log an error message
    logging.error('Something went wrong!')

The logging definition is defined in scripta.py, with the added module parameter. In scriptb.py we simply need to import logging to get access to this defined default. When running scripta.py the following output is generated:

2016-01-14 13:22:24,640 scriptb root.my_view +9: ERROR    [14144] Something went wrong!

Which shows the module (scriptb) where the logging of the error occurs.

According to this answer you can continue to use any per-module configuration of logging from Django, by turning off Django handling and setting up the root handler as follows:

# settings.py - django config
LOGGING_CONFIG = None # disables Django handling of logging
LOGGING = {...}  # your standard Django logging configuration

import logging.config
logging.config.dictConfig(LOGGING)


This post first appeared on Martin Fitzpatrick – Python Coder, Postgraduate, please read the originial post: here

Share the post

Avoid `logger=logging.getLogger(__name__)`

×

Subscribe to Martin Fitzpatrick – Python Coder, Postgraduate

Get updates delivered right to your inbox!

Thank you for your subscription

×