diff --git a/python_boilerplate/common/trace.py b/python_boilerplate/common/trace.py new file mode 100644 index 0000000..b5125f5 --- /dev/null +++ b/python_boilerplate/common/trace.py @@ -0,0 +1,22 @@ +import inspect +import json +from typing import Callable + +from python_boilerplate.configuration.thread_pool_configuration import executor +from python_boilerplate.repository.model.trace_log import TraceLog + + +def trace(func: Callable): + def wrapped(*arg, **kwarg): + function_arguments = {"arg": arg, "kwarg": kwarg} + trace_log = TraceLog( + called_by=inspect.stack()[1][3], + function_qualified_name=func.__qualname__, + function_arguments=json.dumps( + function_arguments, default=lambda x: x.__dict__ + ), + ) + executor.submit(lambda x: x.save(), trace_log) + return func(*arg, **kwarg) + + return wrapped diff --git a/python_boilerplate/repository/model/trace_log.py b/python_boilerplate/repository/model/trace_log.py new file mode 100644 index 0000000..f9e922b --- /dev/null +++ b/python_boilerplate/repository/model/trace_log.py @@ -0,0 +1,26 @@ +import threading +from datetime import datetime + +from peewee import CharField, DateTimeField, TextField + +from python_boilerplate.common.common_function import get_login_user +from python_boilerplate.common.orm import peewee_table +from python_boilerplate.repository.model.base_model import BaseModel + + +@peewee_table +class TraceLog(BaseModel): + # called_by is inspect.stack()[1][3] + called_by = CharField(max_length=200, null=False, index=True) + function_qualified_name = CharField(max_length=200, null=False, index=True) + function_arguments = TextField(null=True) + thread = CharField( + max_length=100, null=False, default=threading.current_thread().name, index=True + ) + start_time = DateTimeField(null=False, default=datetime.now) + + # common 4 fields + created_by = CharField(max_length=50, null=False, default=get_login_user) + created_time = DateTimeField(null=False, default=datetime.now) + modified_by = CharField(max_length=50, null=False, default=get_login_user) + modified_time = DateTimeField(null=False, default=datetime.now)