Hello,
Is there a way to get the complete path of a function?
Example:
Let's say I have a function defined inside "Scripts > DB > "FunctionName".
So, When an error occurs within FunctionName, I want to log "Scripts.DB.FunctionName" as the originator of the error.
Right now I am using "inspect.currentframe()" method of inspect library but this only gives me the name of the function without the path of the script file in which the function exists.
inspect.currentframe() returns FunctionName but I want "Scripts.DB.FunctionName".
Thanks,
Ajay
I'm not sure I understand what you want...
Let's say you have a script called Foo
which contains a function called bar
.
bar
raises an error, which you catch from some other functions.
You want to log the full path of bar
from that except
clause, is that it ?
you can use
func.__code__.co_filename
to get the path of the module where the function is, then append the function name to it
func.__name__
I use something like this
class errorHandler():
''' decorator to wrap functions with a generic error handler '''
def handleError(self, fn, values, trace):
# Format the failed call into the same format that it would written in code
try: fnPath = '%s.%s' % (fn.func_code.co_filename.split(':')[1].replace('>',''), fn.__name__)
except: fnPath = fn.__name__
argsFmt = ','.join(['%r' % x for x in values['args']])
kwargsFmt = ','.join(['%s=%r' % (k,v) for k,v in values['kwargs'].items()])
callString = '%s(%s)' % (fnPath, ','.join(filter(None,(argsFmt,kwargsFmt))))
# do something with the failed function path here
def __call__(self, fn):
# returns the decorator itself, which accepts a function and returns another function
# wraps ensures that the name and docstring of 'fn' is preserved in 'wrapper'
@functools.wraps(fn)
def wrapper(*args, **kwargs):
# the wrapper passes all parameters to the function being decorated
try:
return fn(*args, **kwargs)
except (Throwable, Exception) as e:
self.handleError(fn, locals(), traceback.format_exc())
return {'ErrMsg':e}
return wrapper
# decorator to apply the error handler wrapper to any function we want
@errorHandler()
def someFunction():
return value
3 Likes