How to debud django crontab?
Asked Answered
P

4

6

I have setup a cron job by using django crontab. As per defined in documentation I defined a test job in cron.py and defined it to run in 1 minute interval in settings.py.

#cron.py
def test_cron_run():
    print("\n\nHello World....!! ",timezone.now())

#settings.py
INSTALLED_APPS = [
    'material.theme.cyan',
    'material',
    'material.admin',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    'django_crontab',
]

CRONJOBS = [
    ('*/1 * * * *', 'myapp.cron.test_cron_run','>>'+os.path.join(BASE_DIR,'log/debug7.log')),
]

I have added the cron jobs by running python3 manage.py crontab add. Also the job is added as I can see if I run, python3 manage.py crontab show However I cannot see any log file being generated. Is there any way to debug this, the os logs or something?

Phalanx answered 31/1, 2019 at 14:47 Comment(3)
Is it possible that you're missing a space after the >>?Headroom
what if using ('*/1 * * * *', 'myapp.cron.test_cron_run', '>> test.log'), instead?Hysterics
Yes it runs if I run it forcefully by run command passing the hash value of the job and prints on console, however no log file generated, anyway, is there a way I can hook a debugger to my code to debug my django code?Phalanx
C
5

To combine the tips given here, this is how it worked for me:

import os

CRONJOBS = [
    ('* * * * *', 'myapp.cron.test_cron_run', '>> ' + os.path.join(BASE_DIR,'log/debug7.log' + ' 2>&1 '))
]

Additional notes

  • The directory needs to exist and you need write permission
  • After each change of CRONJOBS, run python3 manage.py crontab add twice
  • Without the 2>&1, error messages from python are not logged as they are written to STDERR
  • Check what is actually written to your crontab with crontab -l
  • If it is not working, you may have a mail from cron. Depending on your system, read it with mail.
Carilyn answered 30/7, 2021 at 5:28 Comment(0)
C
1

Maybe just try adding 2>&1 at the end of you cron job, it will redirect the error output to the standard output.

Cellulosic answered 31/1, 2019 at 15:19 Comment(0)
P
1

I had the same problem. I could only get it to work by including the direct path to the logfile and creating it ahead of time

Pippa answered 9/12, 2020 at 0:9 Comment(1)
Even though, the file had automatically being created, nothing was being written to it. The solution is as you mentioned to create the file yourself.Filaria
E
0
  1. pip install django-crontab
  2. Open settings.py file

Now add these lines in your settings.py file

import os
from django.utils.log import DEFAULT_LOGGING
import logging.config

LOG_DIR = os.path.join(BASE_DIR, 'log')
if not os.path.exists(LOG_DIR):
    os.makedirs(LOG_DIR)

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '{levelname} {asctime} {module} {message}',
            'style': '{',
        },
    },
    'handlers': {
        'cron_file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': os.path.join(LOG_DIR, 'cron_job.log'),
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'student': {
            'handlers': ['cron_file'],
            'level': 'DEBUG',
            'propagate': False,
        },
    },
}

Note: Make sure you have log directory and in your log directory you have file named cron_job.log that defined in loggers settings.

  1. Now create file named cron.py in your any app. For example I have app named student and in my app i have file name cron.py file.

Here is my cron.py file code

import logging
from django.utils import timezone
from datetime import timedelta
from student.models import ForgotPasswordAttempt

logger = logging.getLogger('student')


def delete_old_attempts():
    logger.info('Deleting old attempts')
    now = timezone.now()
    time_threshold = now - timedelta(hours=8)

    attempts_to_delete = ForgotPasswordAttempt.objects.filter(
    forgot_password_attempt__gt=5
    ) | ForgotPasswordAttempt.objects.filter(
    updated_at__lt=time_threshold
    )

    count, _ = attempts_to_delete.delete()
    logger.info(f'Deleted {count} ForgotPasswordAttempt objects')

Now Run the these commands in your terminal

# to Add
python manage.py crontab add
# to Show
python manage.py crontab show
# to Remove
python manage.py crontab remove

enter image description here

Emilio answered 1/7 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.