[Answered ]-Writing a custom Django BaseCommand class that logs the command details

2👍

from commandlog.models import CommandLogEntry
class LoggedBaseCommand(Command):

    def handle(self, *args, **options):
        # 'started' ought to be automatic, 'ended' and 'success' not yet determined.
        c = CommandLogEntry(name = __file__)
        result = "FAIL"
        try:
            result = self.handle_and_log(*args, **options)
        except: 
            pass
        c.success = result
        c.ended = datetime.datetime.now()
        c.save()

    def handle_and_log(self, *args, **options):
        # All of your child classes use this.

You might have to fiddle with the __file__ entry, perhaps using re, to strip out paths and terminating ‘.py’, but since every command is predicated on its file name in the hierarchy, this ought to do the trick. Note that I assume failure, and only record success if the handle_and_log() function passes back a success string. (Changes to suit your needs). If it throws an exception, failure is recorded. Again, change to suit your needs (i.e. record the exception string).

Leave a comment