Last active
August 5, 2017 08:09
-
-
Save houming818/65271837109129df92c79f25963eb4e9 to your computer and use it in GitHub Desktop.
JournalMixin for django Model
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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