21

I am newbie to Django.I am trying for Django logging now. While trying,I am getting this error ["No handlers could be found for logger "sample" "]..here is my code,

(In my settings.py)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'simple': {
            'format': '%(asctime)s %(levelname)s %(name)s %(message)s'
        },
    },
    'handlers': {
        'default': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': '/home/linuxuser/mani/f/logs/msg.log',
            'maxBytes': 1024*1024*5, # 5 MB
            'backupCount': 5,
            'formatter':'simple',
        },
    },
    'loggers': {
        'sample': {
            'handlers': ['default'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

(In my views.py)

import logging
import logging.handlers
from django.conf import settings
logger = logging.getLogger('sample')

def empdel(request,id):
    e = get_object_or_404(emp, pk=id)
    e.delete()
    logger.info('A row is deleted successfully !!!')
    return HttpResponseRedirect('/empthanks/')

While running this code, i got this error ie ["No handlers could be found for logger "sample" "].. Whats wrong with my code? Why i am getting such a error even i am using handler in LOGGING? and also i am trying to save log message into the file that i have used in LOGGING...any idea?? Thanks in advance !!!

Tugrul Ates
  • 9,451
  • 2
  • 33
  • 59
Mani
  • 251
  • 1
  • 3
  • 5
  • 1
    This exact code works for me (I changed the filename). Can you get the logger from the Django `shell`? Have you tried restarting the `runserver`? – sneeu Jul 19 '11 at 13:50
  • @ sneeu : ya its working now.I have used django 1.2.3 before,so it was not working..now i have upgraded into django 1.3,hence it is working now..one more doubt?It saves my log message(what i have used in my code) & also some dafault messages into that file..for example: DEBUG django.db.backends (0.049) some sql query..why its happening?any idea? – Mani Jul 20 '11 at 05:29
  • Django has a few loggers of its own which it looks like are on, I’d suggest having a look at the [docs](https://docs.djangoproject.com/en/1.3/topics/logging/#django-s-logging-extensions). – sneeu Jul 20 '11 at 12:08
  • Just in case someone came here looking for this https://stackoverflow.com/q/44188270/1581226 – qwerty Nov 28 '17 at 10:28

2 Answers2

23

The docs are a little unclear about this, but when you use the built-in functionality for specifying logging settings, you don't need to get an instance of the logger.

You would simply do the following:

import logging

def empdel(request,id):
    e = get_object_or_404(emp, pk=id)
    e.delete()
    logging.info('A row is deleted successfully !!!')
    return HttpResponseRedirect('/empthanks/')
xeeton
  • 422
  • 2
  • 7
  • 10
    I think you are mixing things up. By calling the module level functions in `logging`, the logger that's used is the root logger. Your example is analogous to `import logging`, `logger = logging.getLogger()`, `logger.info(...)`. – glarrain Jun 28 '13 at 23:45
13

I think you have misunderstood what a Handler is in the context of the logging package.

A Handler is an object which you attach to a Logger. Whenever the logger has a message to process, it sends the message to all of its handlers. Additionally, Loggers exist in a tree structure, with the aptly named "root" Logger at its root. After sending a message to its Handlers, a Logger may pass it on to its parent in the tree (determined by the Logger instance's propagate attribute).

As a slightly humorous aside, I once found an application bug in which someone started using the Logger named "root", which is different from the Root Logger.

Don't use the root logger (accessed by logging.info and company, or logging.getLogger()). Any Handlers you attach or settings you alter will also affect well behaved libraries that propagate their errors up to the root logger. Case in point: I once wrote a simple script using the root logger out of laziness. I then incorporated a few calls to boto and got an explosion of debug messages that were being propagated to the root logger. It is recommended that you always create a logger whose name matches your package's name in the namespace (this also leads to nice inheritance structure with getLogger's interpretation of .) by creating loggers with logging.getLogger(__name__)

I strongly recommend giving a thorough reading to the section on Logger Objects in the logging docs: https://docs.python.org/2/library/logging.html

You may notice that your config also specifies a Formatter. Formatters handle the presentation of a message when it is processed by a Handler, so that a single message may be formatted differently for terminal output than for, for example, rsyslog.


All of that said, to fix your code you can use the logger you have created, and just attach a handler to it. I would recommend creating a StreamHandler (the base Handler class is not meant to be instantiated, but for horrible reasons is not an ABC), since that covers a lot of typical use cases.

myhandler = logging.StreamHandler()  # writes to stderr
myformatter = logging.Formatter(fmt='%(levelname)s: %(message)s')
myhandler.setFormatter(myformatter)
logger.addHandler(myhandler)

However, it seems that Django config already includes a lot of this information, not configured the way that I do things above, of course. Not having actually written Django apps, I don't want to give you bad information on this, but Django provides nice docs here: https://docs.djangoproject.com/en/dev/topics/logging/

sirosen
  • 1,716
  • 13
  • 17
  • what horrible reasons? – n611x007 Aug 04 '15 at 14:52
  • 1
    @naxa I don't remember with 100% clarity exactly what I had in mind, but it was probably just a lament over python's historic aversion to ABCs. The was a long-held view that the notion of a class which can't be instantiated isn't necessary when you can duck type things. The argument is that you shouldn't need to define the base class, just implement its protocol. That attitude has changed since `logging` was first added in 2002, and ABCs were added in 2007, precisely because of cases like the base Handler class. – sirosen Aug 11 '15 at 23:52