I have an app named main
in my Django project. This app has a several management commands that I want to log, but nothing is showing up in stdout with the following configuration:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'log_to_stdout': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'stream': sys.stdout,
},
},
'loggers': {
'main': {
'handlers': ['log_to_stdout'],
'level': 'DEBUG',
'propagate': True,
}
}
}
What am I doing wrong? I've tried using my_project.main
as well, but that didn't work either. I'm using 1.3.0 final.
By default, the LOGGING setting is merged with Django's default logging configuration using the following scheme. If the disable_existing_loggers key in the LOGGING dictConfig is set to True (which is the dictConfig default if the key is missing) then all loggers from the default configuration will be disabled.
Basically a Django management command is composed by a class named Command which inherits from BaseCommand . The command code should be defined inside the handle() method. You may be asking yourself, how is that different from a regular Python script, or what's the benefit of it.
The parameter parser is an instance of argparse. ArgumentParser (see the docs). Now you can add as many arguments as you want by calling parser 's add_argument method. In the code above, you are expecting a parameter n of type int which is gotten in the handle method from options .
BaseCommand is a Django object for creating new Django admin commands that can be invoked with the manage.py script. The Django project team as usual provides fantastic documentation for creating your own commands.
you need to namespace your logger. currently you are logging to the root logger, which isn't caught by your handler, which is looking for main
rather than logging.debug("message")
, you want
logger = logging.getLogger('main')
logger.debug("message")
Setting "stream" to sys.stdout is not necessary. However, you should define a formatter:
Example:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'log_to_stdout': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple',
},
},
'loggers': {
'main': {
'handlers': ['log_to_stdout'],
'level': 'DEBUG',
'propagate': 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