I can't get logging to display. Am I doing something wrong? Other logging that is generated by cookiecutter-django works fine, but when I try to implement logging myself for debugging I am not able to get any display
settings.py:
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": "INFO",
"class": "logging.StreamHandler",
"formatter": "verbose",
},
"file": {
"level": "INFO",
"class": "logging.FileHandler",
"formatter": "verbose",
"filename": "debug.log",
},
},
"root": {"level": "INFO", "handlers": ["console", "file"]},
}
view.py:
class run(viewsets.ModelViewSet):
serializer_class = RunSerializer
def list(self, request):
return Response("Get")
def create(self, request):
logger = logging.getLogger("root")
logger.info(request.data)
logger.info(request.POST)
return Response({200})
this logging does not display to console
Related
Given the following logging config:
settings.py
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"filters": {
"require_debug_false": {"()": "django.utils.log.RequireDebugFalse",},
"require_debug_true": {"()": "django.utils.log.RequireDebugTrue",},
},
"formatters": {
"django.server": {
"()": "django.utils.log.ServerFormatter",
"format": "[{server_time}] {message}",
"style": "{",
}
},
"handlers": {
"console": {"level": "INFO", "filters": ["require_debug_true"], "class": "logging.StreamHandler",},
"file": {
"level": "ERROR",
"filters": ["require_debug_false"],
"class": "logging.FileHandler",
"filename": BASE_DIR / "debug.log",
},
"django.server": {"level": "INFO", "class": "logging.StreamHandler", "formatter": "django.server",},
"mail_admins": {
"level": "ERROR",
"filters": ["require_debug_false"],
"class": "django.utils.log.AdminEmailHandler",
},
},
"loggers": {
"django": {"handlers": ["file", "console"], "level": "INFO",},
"django.server": {"handlers": ["django.server"], "level": "INFO", "propagate": False,},
},
}
Present Output
Console logs information- and warning-level alerts to the console
Log file debug.log is created
Compilation errors are not printed to the log file in production
What about this config does not allow errors to be sent to the log file?
I'm following this guidance for Django and Azure. I'm able to get dependancies and requests, but not traces.
I added this to middleware:
'opencensus.ext.django.middleware.OpencensusMiddleware'
Here is the LOGGING and OPENCENSUS portions of settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': '%(asctime)s - %(levelname)s - %(processName)s - %(name)s\n%(message)s',
},
},
"handlers": {
"azure": {
"level": "DEBUG",
"class": "opencensus.ext.azure.log_exporter.AzureLogHandler",
"instrumentation_key": assert_env('APPINSIGHTS_INSTRUMENTATIONKEY'),
},
"console": {
"level": "DEBUG",
"class": "logging.StreamHandler",
"formatter": "default",
},
},
"loggers": {
"logger_name": {"handlers": ["azure", "console"]},
},
# For some reason, this is needed or logging doesn't show up in the
# celery log file.
'skyforge.tasks': {
'handlers': ['azure','console'],
'level': assert_env('DJANGO_LOG_LEVEL'),
},
}
OPENCENSUS = {
'TRACE': {
'SAMPLER': 'opencensus.trace.samplers.ProbabilitySampler(rate=1)',
'EXPORTER': '''opencensus.ext.azure.trace_exporter.AzureExporter(
service_name='skyforge'
)'''
#Assumes Environmental Variable 'APPINSIGHTS_INSTRUMENTATIONKEY'
}
}
Any guidance on where to look for why no trace logs. The django-critical and django-tasks are still going to the console.
This is the part that is wrong:
"loggers": {
"logger_name": {"handlers": ["azure", "console"]},
The "logger_name" needed to be populated with the App name so that
logger = logging.getLogger(__name__) worked properly.
Also a level is needed in the logger.
Here is what worked for me.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'default': {
'format': '%(asctime)s - %(levelname)s - %(processName)s - %(name)s\n%(message)s',
},
},
'handlers': {
'azure': {
'class': 'opencensus.ext.azure.log_exporter.AzureLogHandler',
'formatter':'default'
# https://pypi.org/project/opencensus-ext-azure/
#Assumed ENV APPLICATIONINSIGHTS_CONNECTION_STRING
},
'console': {
'class': 'logging.StreamHandler',
'formatter': 'default',
},
},
'loggers': {
'polls': {
'handlers': ['azure', 'console'],
'level':'DEBUG'
},
}
}
The following options did not make a difference:
'level' parameter in handler
'filter':'[]' in handler
'stream':sys.stdout in handler.
I put the Appinsights connection string in an environmental variable, but the reference shows how to place in settings also. Also the original key in settings seems to work also.
APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentaionKey=<key uuid>
I have a django serializer as below,
class VideoSerializer(CustomSerializer):
class Meta:
model = apis_models.Video
fields = '__all__'
def to_representation(self, video):
data = super().to_representation(video)
return {
'ordering': {
'video': {
"label": "Order By",
"options": {
"Newest First": '-upload_date',
"Oldest First": 'upload_date',
"Views (High)": "views",
"Views (Low)": "-views"
}
}
},
'body': data,
}
Which prints the output as below.
The "ordering" key appears in each element.
I need it to be appear only once at top. I believe using to_representation would be the best way to do it since it is a constant value. But I am not sure how do I get it only once.
How could I get it? Please help.
{
"count": 339,
"next": "http://10.0.0.238:8000/videos/?page=2",
"previous": null,
"results": [
{
"ordering": {
"video": {
"label": "Order By",
"options": {
"Newest First": "-upload_date",
"Oldest First": "upload_date",
"Views (High)": "views",
"Views (Low)": "-views"
}
}
},
"body": {
"id": 6142,
"source": {
"id": 5,
"name": "kpopdeepfakes_net",
"domain": "https://kpopdeepfakes.net",
}
}
},
{
"ordering": {
"video": {
"label": "Order By",
"options": {
"Newest First": "-upload_date",
"Oldest First": "upload_date",
"Views (High)": "views",
"Views (Low)": "-views"
}
}
},
"body": {
"id": 6153,
"source": {
"id": 5,
"name": "kpopdeepfakes_net",
"domain": "https://kpopdeepfakes.net",
}
}
},
I did it by adding below to my viewset.
def get_paginated_response(self, data):
return Response({
'ordering': {
'video': {
"label": "Order By",
"options": {
"Newest First": '-upload_date',
"Oldest First": 'upload_date',
"Views (High)": "views",
"Views (Low)": "-views"
}
}
},
'results': data
})
A beginner django question...
Here's a JSON response...
"data": [
{
"type": "Subject",
"id": "0",
"attributes": {
"created": "2019-01-01T00:00:00Z",
"modified": "2019-01-01T00:00:00Z",
"subject_code": "A&H",
"subject_name": "AH",
"subject_short_name": "A & HUM"
},
"relationships": {
"organization": {
"data": {
"type": "Organization",
"id": "61"
}
},
"created_user": {
"data": null
},
"last_updated_user": {
"data": null
}
},
"links": {
"self": "http://localhost:8001/v1/subject_owner/0"
}
},
The above response is coming from a serializer
queryset = Subject.objects.all()
I have a query which is
http://localhost:8001/v1/subject_owner?owner_ids=62,63
So, how do we write a filtering condition for the owner_ids as a list? The response should have only the results where the owner_ids match organization_id. I have tried few:
queryset.filter(organization__in=[owner_id_list])
and
queryset.filter(organization=owner_id_list)
and obviously they don't work. Any help will be appreciated.
FYI, here's the model class...
class SubjectManager(models.Manager):
def get_by_natural_key(self, subject_code):
return self.get(subject_code=subject_code)
class Subject(get_subject_base_class(Organization)):
objects = SubjectManager()
def __str__(self):
return self.subject_code
def natural_key(self):
return (self.subject_code,)
You have to make something like that:
owner_id_list = [62, 63]
Subject.objects.filter(organization_id__in=owner_id_list)
So I'm trying to create an /api/info url that return various data on my application. It pulls data from various models and puts it together in one response. I got the following:
class SessionInfo(generics.GenericAPIView):
def get(self, request, format=None):
token = Token.objects.get(user=self.request.user)
userprofile = UserProfile.objects.get(user=self.request.user)
is_admin = self.request.user.is_staff
is_primary_owner = userprofile.primary_owner
managers = userprofile.reports_to.all()
man = ["test manager 1", "test manager 2"]
pages = Page.objects.filter(published=True, show_in_menu=True)
pages_output = JSONRenderer().render(PageSerializer(pages).data)
content = {
'user': {
"username": str(self.request.user.username),
"first_name": str(self.request.user.first_name),
"last_name": str(self.request.user.last_name),
"is_admin": is_admin,
"is_primary_owner": is_primary_owner,
"api_token": token.key,
"timezone": 'blalala',
"managers": man,
},
'license': {
"plan" : "gold",
"expiry_date" : "lol",
},
'feature_flags': {
'billing_test': False,
},
'pages': { pages_output },
}
return Response(content)
However it doesn't properly serialize and render pages, making it an escaped string instead:
{
"feature_flags": {
"billing_test": false
},
"user": {
"username": "test#user.com",
"first_name": "Test",
"last_name": "User",
"is_admin": true,
"managers": [
"test manager 1",
"test manager 2"
],
"api_token": "08d1a5827da9a90e7746949ffd2e69e87c51b272",
"timezone": "blalala",
"is_primary_owner": false
},
"license": {
"expiry_date": "lol",
"plan": "gold"
},
"pages": [
"[{\"id\": 1, \"title\": \"Trololol\"}, {\"id\": 2, \"title\": \"NEW pages\"}]"
]
}
if I use directuly use pages_output = PageSerializer(pages) I get:
<webapp_api_v1.serializers.PageSerializer object at 0x10a0d8f90> is not JSON serializable
How can I make a serializer properly nest within my constructed response? Thanks!
Solved it with pages_output = PageSerializer(pages).data and changing 'pages': pages_output,