Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django management command does not show logs of my library

This question is a simpler version of this 4 years old question without answer Django management command doesn't show logging output from python library:

I have a command:

class Command(BaseCommand):
  def handle(self, *args, **options):
  ...
  MyParser(data)

And in MyParser:

logger = logging.getLogger(__name__)

Class MyParser:
   def __init__(self, data):
       logger.info('hello')

Why the logger does not display to stdout when I run the command? With a print it is OK but I need a logger

PS:

I tried this but it does not change anything

from parser import logger
root_logger = logger
root_logger.setLevel(logging.INFO)
MyParser(data)
like image 319
Benjamin Avatar asked Oct 26 '25 04:10

Benjamin


2 Answers

I will base this on the fact that you haven't properly configured your logging configuration which is the most likely. By default, there is no logging on anything except django.requests (or something along those lines.

If you want your logging messages to appear, you would need something that catches & forward your messages to the appropriate handlers.

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'console': {
            'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'console',
        },
    },
    'loggers': {
        '': {
            'level': 'INFO',
            'handlers': ['console'],
        },
    },
}

(I've - shamelessly - extracted & stripped this code block from this blog post on django logging)

like image 108
Wonskcalb Avatar answered Oct 27 '25 19:10

Wonskcalb


I'm 90% sure this will be a configuration issue and not that you are using logger incorrectly.

The Django logging docs do not, in my opinion, make life any easier.

Firstly, add this to your settings .py file, replacing any other LOGGING = statements:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'INFO',
        },
        '': {
            'handlers': ['console'],
            'level': 'INFO',
        },
    },
}

Notice the '' logger, its there to catch all log messages (whereas the default only catches ones from django itself).

If that alone doesn't work, try setting DEBUG=True in the settings as well (not in production, obviously). For why this might be needed, the docs say, "the default only displays log records when DEBUG=True".

like image 44
FiddleStix Avatar answered Oct 27 '25 17:10

FiddleStix