No handlers could be found for logger “django_facebook.models” - django-facebook

while installing django_facebook, i got an error :
Validating models...
No handlers could be found for logger "django_facebook.models"
Unhandled exception in thread started by <function wrapper at 0x1032a5758>
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 93, in wrapper
fn(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 101, in inner_run
self.validate(display_num_errors=True)
File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 310, in validate
num_errors = get_validation_errors(s, app)
File "/Library/Python/2.7/site-packages/django/core/management/validation.py", line 113, in get_validation_errors
from django.utils.image import Image
File "/Library/Python/2.7/site-packages/django/utils/image.py", line 154, in <module>
Image, _imaging, ImageFile = _detect_image_library()
File "/Library/Python/2.7/site-packages/django/utils/image.py", line 108, in _detect_image_library
_("Neither Pillow nor PIL could be imported: %s") % err
django.core.exceptions.ImproperlyConfigured: Neither Pillow nor PIL could be imported: No module named Image
It is a pure django project created by pycharm. I was following the document of django_facebook, installation section. What I do is just get facebook app and type the code 'django_facebook' in INSTALLED_APP in settings.py.
It's same results when syncdb also.
I'm using python-2.7.5 and django-1.6.5.
I can't find any answer to solve this. anybody knows this?

Regarding the warningNo handlers could be found for logger "django_facebook.models" and not the error. This question came up on search for that warning, thought this would be useful for others.
django-facebook outputs logs when in operation, just like other django components do. You have to tell Django what you want to do with these messages. In django terminology the app outputs some messages as a logger without needing to know what to do with them, you have to then patch these to a handler which doesn't know anything about your use case, but does know about sending emails/texts/carrier pigeons.
In your settings.py file find LOGGING=..., in the loggers dict you will have to specify what handlers you want to handle the output from django-facebook.
For more information see the docs on logging https://djangoproject.com/en/dev/topics/logging/
My logging variable looks like this, notice the bit at the bottom:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins','console'],
'level': 'ERROR',
'propagate': True,
},
'django_facebook.models': {
'handlers': ['mail_admins','console'],
'level': 'ERROR',
'propagate': True,
}
}
}

You could try pip install pillow

Related

Simple Log to File example for django 1.3+

The release notes say:
Django 1.3 adds framework-level
support for Python’s logging module.
That's nice. I'd like to take advantage of that. Unfortunately the documentation doesn't hand it all to me on a silver platter in the form of complete working example code which demonstrates how simple and valuable this is.
How do I set up this funky new feature such that I can pepper my code with
logging.debug('really awesome stuff dude: %s' % somevar)
and see the file "/tmp/application.log" fill up with
18:31:59 Apr 21 2011 awesome stuff dude: foobar
18:32:00 Apr 21 2011 awesome stuff dude: foobar
18:32:01 Apr 21 2011 awesome stuff dude: foobar
What's the difference between the default Python logging and this 'framework-level support'?
I truly love this so much here is your working example! Seriously this is awesome!
Start by putting this in your settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format' : "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
'datefmt' : "%d/%b/%Y %H:%M:%S"
},
},
'handlers': {
'null': {
'level':'DEBUG',
'class':'django.utils.log.NullHandler',
},
'logfile': {
'level':'DEBUG',
'class':'logging.handlers.RotatingFileHandler',
'filename': SITE_ROOT + "/logfile",
'maxBytes': 50000,
'backupCount': 2,
'formatter': 'standard',
},
'console':{
'level':'INFO',
'class':'logging.StreamHandler',
'formatter': 'standard'
},
},
'loggers': {
'django': {
'handlers':['console'],
'propagate': True,
'level':'WARN',
},
'django.db.backends': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False,
},
'MYAPP': {
'handlers': ['console', 'logfile'],
'level': 'DEBUG',
},
}
}
Now what does all of this mean?
Formaters I like it to come out as the same style as ./manage.py runserver
Handlers - I want two logs - a debug text file, and an info console. This allows me to really dig in (if needed) and look at a text file to see what happens under the hood.
Loggers - Here is where we nail down what we want to log. In general django gets WARN and above - the exception (hence propagate) is the backends where I love to see the SQL calls since they can get crazy.. Last is my app were I have two handlers and push everything to it.
Now how do I enable MYAPP to use it...
Per the documentation put this at the top of your files (views.py)..
import logging
log = logging.getLogger(__name__)
Then to get something out do this.
log.debug("Hey there it works!!")
log.info("Hey there it works!!")
log.warn("Hey there it works!!")
log.error("Hey there it works!!")
Log levels are explained here and for pure python here.
Based partially on the logging config suggested by rh0dium and some more research I did myself, I started assembling an example Django project with nice logging defaults – fail-nicely-django.
Sample logfile output:
2016-04-05 22:12:32,984 [Thread-1 ] [INFO ] [djangoproject.logger] This is a manually logged INFO string.
2016-04-05 22:12:32,984 [Thread-1 ] [DEBUG] [djangoproject.logger] This is a manually logged DEBUG string.
2016-04-05 22:12:32,984 [Thread-1 ] [ERROR] [django.request ] Internal Server Error: /
Traceback (most recent call last):
File "/Users/kermit/.virtualenvs/fail-nicely-django/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/kermit/.virtualenvs/fail-nicely-django/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/kermit/projekti/git/fail-nicely-django/djangoproject/brokenapp/views.py", line 12, in brokenview
raise Exception('This is an exception raised in a view.')
Exception: This is an exception raised in a view.
The detailed usage is explained in the README, but essentially, you copy the logger module to your Django project and add from .logger import LOGGING at the bottom of your settings.py.

Django logging - ValueError: 'NoneType' object has no attribute 'split'

I am trying to configure some logging within an application that uses Django that will ultimately log a few different types of information to separate log files (such as time taken to run a module, markers for different modules to categorize flow, etc).
The application is deploying to a VirtualBox Ubuntu 16.04 environment.
Right now, I'm simply trying to get some simple test information logged into a file called eems-dashboard.log (which I created, is empty, and seem to have full access to) just to try to get the logging to work initially. The setup in settings.py looks like this:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose'
},
'log_file':{
'level': 'DEBUG',
'filename': '/var/log/eems-dashboard.log',
'formatter': 'verbose'
}
},
'loggers': {
'': {
'handlers': ['log_file'],
'level': 'DEBUG',
},
'django.request': {
'handlers': ['log_file'],
'propagate': True,
'level': 'DEBUG'
},
'apps': {
'handlers': ['log_file'],
'level': 'DEBUG',
'propagate': True,
}
}
}
However, whenever I try to run a local deployment of this application, I get the following error:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/webapps/uiux/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/webapps/uiux/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 338, in execute
django.setup()
File "/webapps/uiux/env/lib/python3.5/site-packages/django/__init__.py", line 22, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "/webapps/uiux/env/lib/python3.5/site-packages/django/utils/log.py", line 75, in configure_logging
logging_config_func(logging_settings)
File "/usr/lib/python3.5/logging/config.py", line 795, in dictConfig
dictConfigClass(config).configure()
File "/usr/lib/python3.5/logging/config.py", line 566, in configure
'%r: %s' % (name, e))
ValueError: Unable to configure handler 'log_file': 'NoneType' object has no attribute 'split'
I have found some limited information on this error, but none of the solutions seem to apply to the problem at hand. I've allowed full permissions to the file path for the log file, but that's all the troubleshooting advice I was able to find. I'm pretty sure it has to do with the syntax of the LOGGING configuration and not an issue with any of the other modules that appear in the error. I am very new to programming/developing in general for context. Thank you.
You'll need to specify a class for that log_file handler. I dug into Python's logging/config.py module and it attempts to find a class key in the given config before calling split() on said key. As you did not specify a class key in your log_file dict, it will attempt to call split() on None.
e.g.
'log_file':{
'level': 'DEBUG',
'filename': '/var/log/eems-dashboard.log',
'formatter': 'verbose',
'class': 'logging.handlers.SysLogHandler'
}
Check out the docs to see which logging handler is right for you.
https://docs.python.org/2/library/logging.handlers.html

When docker run, an error occurs. “ValueError: Unable to configure handler 'watchtower': You must specify a region.”

First, I use the server environment
sever: django + nginx + uwsgi
cloud: docker + AWS ECS
logging: AWS CloudWatch log service + watchtower third party app
If I run server locally with python manage.py runserver, the log is stored well in the CloudWatch log. However, if I build my project with docker and docker run --rm -it -p 8080: 80 image_name command, the following error occurs.
Traceback (most recent call last):
File "/usr/lib/python3.5/logging/config.py", line 558, in configure
handler = self.configure_handler(handlers[name])
File "/usr/lib/python3.5/logging/config.py", line 731, in configure_handler
result = factory(**kwargs)
File "/usr/local/lib/python3.5/dist-packages/watchtower/__init__.py", line 78, in __init__
self.cwl_client = (boto3_session or boto3).client("logs")
File "/usr/local/lib/python3.5/dist-packages/boto3/__init__.py", line 83, in client
return _get_default_session().client(*args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/boto3/session.py", line 263, in client
aws_session_token=aws_session_token, config=config)
File "/usr/local/lib/python3.5/dist-packages/botocore/session.py", line 836, in create_client
client_config=config, api_version=api_version)
File "/usr/local/lib/python3.5/dist-packages/botocore/client.py", line 70, in create_client
verify, credentials, scoped_config, client_config, endpoint_bridge)
File "/usr/local/lib/python3.5/dist-packages/botocore/client.py", line 224, in _get_client_args
verify, credentials, scoped_config, client_config, endpoint_bridge)
File "/usr/local/lib/python3.5/dist-packages/botocore/args.py", line 45, in get_client_args
endpoint_url, is_secure, scoped_config)
File "/usr/local/lib/python3.5/dist-packages/botocore/args.py", line 103, in compute_client_args
service_name, region_name, endpoint_url, is_secure)
File "/usr/local/lib/python3.5/dist-packages/botocore/client.py", line 297, in resolve
service_name, region_name)
File "/usr/local/lib/python3.5/dist-packages/botocore/regions.py", line 122, in construct_endpoint
partition, service_name, region_name)
File "/usr/local/lib/python3.5/dist-packages/botocore/regions.py", line 135, in _endpoint_for_partition
raise NoRegionError()
botocore.exceptions.NoRegionError: You must specify a region.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "django_app/manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 341, in execute
django.setup()
File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 22, in setup
configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
File "/usr/local/lib/python3.5/dist-packages/django/utils/log.py", line 75, in configure_logging
logging_config_func(logging_settings)
File "/usr/lib/python3.5/logging/config.py", line 795, in dictConfig
dictConfigClass(config).configure()
File "/usr/lib/python3.5/logging/config.py", line 566, in configure
'%r: %s' % (name, e))
ValueError: Unable to configure handler 'watchtower': You must specify a region.
The error message points out the region problem and I do not know how to fix it.
The django logging setting is shown below.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'watchtower': {
'level': 'DEBUG',
'class': 'watchtower.CloudWatchLogHandler',
'formatter': 'verbose',
},
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['watchtower', 'console'],
'level': 'INFO',
'propagate': True,
},
'django.user': {
'handlers': ['watchtower'],
'level': DJANGO_LOG_LEVEL,
'propagate': False,
},
'django.partner': {
'handlers': ['watchtower'],
'level': DJANGO_LOG_LEVEL,
'propagate': False,
}
}
}
Where is the problem?
You need to provide aws credentials inside your container. You can mount them dinamically using a volume:
docker run -v $HOME/.aws:/root/.aws --rm -it -p 8080: 80 image_name
Your credentials should be locally in $HOME/.aws, then they are mounted into the home directory of the user that runs your application (change /root to another dir if the user is other)
The AWS region is not configured inside your container, and probably neither are the credentials. Have a look at the documentation or here.
The files generated by the CLI for the profile configured in the previous section look like this:
~/.aws/credentials
[default]
aws_access_key_id=AKIAIOSFODNN7EXAMPLE
aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
~/.aws/config
[default]
region=us-west-2
output=json
The following settings are supported.
aws_access_key_id – AWS access key.
aws_secret_access_key – AWS secret key.
aws_session_token – AWS session token. A session token is only required if you are using temporary security credentials.
region – AWS region.
output – output format (json, text, or table)

How do I get django to tell me where I am inside my code

I am starting to us logging in my django project at the moment (on step at a time) and I was wondering if there was a way to put where I am in my code into the error message using python. I.e. If I am in something.views.something_view how do I get this class/function location to then tag it onto logging.error("something went wrong in "+???)?
You should configure the logging at application level (in settings.py) using a dictionary, in this way:
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': '[%(levelname)s] [%(asctime)s] [%(name)s:%(lineno)s] %(message)s',
'datefmt': '%d/%b/%Y %H:%M:%S'
},
},
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'logfile': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(LOGS_DIR, 'application.log'),
'maxBytes': 5242880, # 5MB
'backupCount': 10,
'formatter': 'standard',
},
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
'formatter': 'standard'
},
},
'loggers': {
'django': {
'handlers':['console'],
'level':'DEBUG',
'propagate': False,
},
'django.db.backends': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': False,
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'DEBUG',
'propagate': False,
},
'com.mysite': {
'handlers': ['console', 'logfile'],
'level': 'DEBUG',
'propagate': True,
},
}
}
The line:
'format': '[%(levelname)s] [%(asctime)s] [%(name)s:%(lineno)s] %(message)s'
will produce a log output like:
[DEBUG] [11/Aug/2013 12:34:43] [com.mysite.apps.myapp.middleware.MyMiddleware:28] My log message
where:
com.mysite.apps.myapp.middleware.MyMiddleware
is the class that has logged your message and :28 the line in your code.
A logger is configured in this way at module-level:
import logging
logger = logging.getLogger(__name__)
in this way, your logger will automatically be resolved using the fully qualified class name!
You can use logging module, which comes with Python 2.3
You must set a proper formatter for your logger to obtain what you want, so you must set ,
import logging
my_logger = logging.getLogger('my_first_logger')
my_logger.setLevel('INFO') # You can check docs for more info about levels
formatter = logging.Formatter(
"%(asctime)s %(levelname)s %(name)s %(process)d %(threadName)s %(module)s:%(lineno)d %(funcName)s() %(message)s\n\n\n" # You set your logger debug information here. Check docs for detailed info about what information you can log
filename = 'logs/my_first_log.log'
handler = logging.FileHandler(filename, mode='a')
handler.setFormatter(formatter)
my_logger.addHandler(handler)
)
And usage:
import logging
my_log = logging.getLogger('my_first_logger')
my_log.info('Your log goes here...)
Output will be like:
2013-08-12 12:43:34,070 INFO my_code_file 26924 MainThread my_module:72 myFunc() Your log goes here...
Update: I forgot to add FileHandler file setter. I fixed that. You must do this for each log file you will use. If you will log your all activity into a single log file. Then you need to set the logger object only once. then you will just import it and use it. If you have more than one log file, You must set each log file seperately, then you can use it anywhere you want with:
my_log = logging.getLogger('my_first_logger')
my_log.info('Blah blah blah...')
The python inspect module should give you the information you're after.
Logger also has the option to log the line numebers where the log call is made. You need to add %(lineno)d to your formatter. But to log arbitrary line numbers you can try something on the lines of:
import inspect
info = inspect.getframeinfo(inspect.currentframe())
lineno = info.lineno
print info
print lineno
Edit:
Got the context after seeing alecxe's comment. YOu can either use process_exception middleware or django signal got_request_exception
https://docs.djangoproject.com/en/dev/ref/signals/#got-request-exception
logger.exception() will log the stack trace for you

concise way to change django console log level

I just want to be able to override the console log level in the settings file. I read the django logging document, but I'm having trouble making the logging do what I want. The documentation assures me that:
"From Django 1.5 forward, the project’s logging configuration is merged with Django’s defaults, hence you can decide if you want to add to, or replace the existing configuration. To completely override the default configuration, set the disable_existing_loggers key to True in the LOGGING dictConfig. Alternatively you can redefine some or all of the loggers."
So I tried just adding the following to my settings.py:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console':{
'level': 'DEBUG',
},
},
}
...but I get an exception:
<snip>
File "/usr/lib/python2.7/logging/config.py", line 575, in configure
'%r: %s' % (name, e))
ValueError: Unable to configure handler 'console': 'NoneType' object has no attribute 'split'
Fair enough. It seems to want the whole configuration block. So I tried what I thought would be the simplest console logger config:
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'console':{
'level': 'INFO',
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
},
'loggers': {
'default': {
'handlers': ['console'],
'level': 'INFO',
'filters': []
}
}
}
My intention is to set the log-level to INFO, but I still see a bunch of DEBUG messages, and the string MYFORMATTER doesn't appear in any of them anyway.
Finally, with blind optimism, I attempted this:
from django.utils.log import DEFAULT_LOGGING
DEFAULT_LOGGING['handlers']['console']['level'] = 'INFO'
I must be missing something quite obvious here.
BTW, I'm using Django 1.5.1.
Answering my own question here, I ended up going with the following in the settings.py file:
import logging
logging.basicConfig(
level = logging.INFO,
format = " %(levelname)s %(name)s: %(message)s",
)
You can do this to set the django logging level :
import logging
logging.disable(logging.INFO)
logging.disable(lvl)
Provides an overriding level lvl for all loggers which takes precedence over the
logger’s own level. When the need arises to
temporarily throttle logging output down across the whole application,
this function can be useful. Its effect is to disable all logging
calls of severity lvl and below, so that if you call it with a value
of INFO, then all INFO and DEBUG events would be discarded, whereas
those of severity WARNING and above would be processed according to
the logger’s effective level. To undo the effect of a call to
logging.disable(lvl), call logging.disable(logging.NOTSET).
http://docs.python.org/2/library/logging.html#logging.disable
I had a similar issue- I was missing a "class" from one of my handlers.

Resources