haojie
haojie

Reputation: 753

Where is the logging in my Django application started by uwsgi?

I use supervisor and uwsgi to start my Django. Here is the conf in supervisor.

[program:myapp]
directory=/home/users
command=uwsgi --ini uwsgi.ini
stdout_logfile_maxbytes=50MB
stdout_logfile_backups=30
stderr_logfile=/var/log/supervisor/supervisor.log
stdout_logfile=/var/log/supervisor/supervisor.log

And this is the ini file of uwsgi

[uwsgi]
http-socket=0.0.0.0:8080
wsgi-file=myapp/wsgi.py
logformat=%(ltime) "%(method) %(uri) %(proto)" status=%(status) res-time=%(msecs)ms
logto=/var/log/supervisor/uwsgi.log

In this way, only method, status and time to reponse etc is listed as follow

14/Jan/2022:13:19:46 +0800 "GET /model/task/?taskid=e69a757974f811ec93e1f58ac6e34980&current=1&pageSize=10000&total=0&model_id=1 HTTP/1.1" status=200 res-time=107ms
14/Jan/2022:13:19:45 +0800 "POST /model/runmodel/ HTTP/1.1" status=200 res-time=3508ms

What I want is if I add a logging.info or logging.debug in my application, it can also writes to the log file. From the doc of uwsgi, it seems I cannot accomplish that by the logformat parameter. Anyone knows if it's possible to do it?

Upvotes: 2

Views: 3878

Answers (1)

akun.dev
akun.dev

Reputation: 339

Good day!

You are right, logformat handles only logging of the uwsgi.

If you want your Django app to log events you will need to add 2 things:

  1. Update settings.py:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    "formatters": {
        "verbose": {
            "format": "[{asctime}] {levelname}: {name}.{message}",
            "style": "{",
        },
    },

    'handlers': {
         "console": {'level': 'DEBUG', "class": "logging.StreamHandler", "formatter": "verbose"},
    },
    "root": {
        "handlers": ["console"],
        "level": "DEBUG",
    },
}
  1. And add following 3 lines of code to the place you want to log, like here in view:
from django.views.generic import TemplateView
from logging import getLogger # This 


logger = getLogger(__name__) # This

# Create your views here.
class IndexView(TemplateView):
    template_name = "index.html"

    def get(self, request, *args, **kwargs):
        logger.info("Index page requested") # And this
        return super().get(request, *args, **kwargs)

This will render the following:

[2022-01-14 07:09:39,874] INFO: logged.views.Index page requested
14/Jan/2022:07:09:39 +0000 "GET / HTTP/1.1" status=200 res-time=18ms

Django docs: https://docs.djangoproject.com/en/4.0/topics/logging

Check the source code: https://github.com/almazkun/uwsgi_logging

Upvotes: 3

Related Questions