Skip to content

Instantly share code, notes, and snippets.

@houming818
Last active August 5, 2017 08:09
Show Gist options
  • Save houming818/65271837109129df92c79f25963eb4e9 to your computer and use it in GitHub Desktop.
Save houming818/65271837109129df92c79f25963eb4e9 to your computer and use it in GitHub Desktop.
JournalMixin for django Model
class JournalMixin(object):
def __init__(self, *args, **kwargs):
super(JournalMixin, self).__init__(*args, **kwargs)
logger.error('__Init__ save journal')
old_save = getattr(self, 'save', None)
if old_save is not None:
def new_save(self, *args, **kwargs):
logger.error('new save journal')
try:
old_save.im_func(self, *args, **kwargs)
journal = {
'trace_id': self.trace_id,
'level': logging.DEBUG}
payload = serializers.serialize('json', [self])
payload = json.loads(payload[1:-1])
payload = {'event': 'save', 'status': 'OK',
'instance': payload}
journal.update({'payload': payload})
journal = Journal(**journal)
journal.save()
except Exception as e:
trace_id = getattr(self, 'trace_id', None)
if trace_id is None:
trace_id = getattr(self, 'id', None)
if trace_id is None:
trace_id = 'Unknown'
journal = {'trace_id': trace_id, 'level': logging.ERROR}
payload = serializers.serialize('json', [self])
payload = json.loads(payload[1:-1])
payload = {'event': 'save', 'status': 'FAIL',
'instance': payload}
journal.update({'payload': payload})
journal = Journal(**journal)
journal.save()
raise e
new_save = types.MethodType(new_save, self, self.__class__)
setattr(self, 'save', new_save)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment