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)
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)
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With