Login

LogTrace

Author:
twoolie
Posted:
November 6, 2010
Language:
Python
Version:
Not specified
Score:
1 (after 1 ratings)

This small decorator will trace the execution of your code every time it enters or exits a decorated function (by thread) and will insert appropriate indent into the log file along with exception information.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#Setup Your Log
import logging
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
log = logging

#paste this somewhere accessible in your code
def LogTrace(func=None, redact=[]):
    import threading
    import traceback
    def wrapper(func):
        def decorator(*args, **kwargs):
            if not hasattr(LogTrace, 'local'): LogTrace.local = threading.local()
            tl = LogTrace.local
            if not hasattr(tl, 'log_indent'): tl.log_indent=0
            funcname = func.__module__ + "." + func.__name__
            margs = [str("'%s'"%arg if isinstance(arg, str) else arg) for arg in [("********" if i in redact else arg) for i, arg in enumerate(args)]] #list all positional arguments
            margs.extend(["%s=%s"%(key, str("'%s'"%val if isinstance(val, str) else val)) for key, val in [(key, ("********" if key in redact else val)) for key, val in kwargs.items()]]) #list all keyword arguments
            try:
                log.debug("\t"*tl.log_indent + "Entering %s(%s)" % (funcname, ", ".join(margs)))
                tl.log_indent+=1
                retval = func(*args, **kwargs)
                tl.log_indent-=1
                log.debug("\t"*tl.log_indent + "Leaving %s = %s" % (funcname, retval))
                return retval
            except Exception as e:
                tl.log_indent-=1
                file = traceback.extract_tb()[-1][0]
                line = traceback.extract_tb()[-1][1]
                clsfunc = e.__class__.__name__
                log.error("\t"*tl.log_indent + "Encountered error in %s: %s(%s) [%s:%i]" % (funcname, clsfunc, e.message, file, line))
                raise e
        return decorator
    if func:
        return wrapper(func)
    else:
        return wrapper

#decorate your functions to be traced
@LogTrace
def WhatDoesThisFunctionDo():
   pass

#if some information should be redacted from the log, add it's position and name to the list
@LogTrace(redact=[2,'password',3,'secret')
def MySensitiveFunction(param1, param2, password, secret):
    pass

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.