Login

LogTrace

Author:
twoolie
Posted:
November 6, 2010
Language:
Python
Version:
Not specified
Tags:
decorator logging hax trace
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. function tracing decorator by amitu 6 years, 4 months ago
  2. Capture Stack Trace Decorator by LorenDavie 5 years, 2 months ago
  3. Logging solution for mod_python/FCGI by mikeivanov 7 years, 10 months ago
  4. anonymous_required decorator by yetty 2 years ago
  5. Super User Conditional Page Exception Reporting by zbyte64 7 years ago

Comments

Please login first before commenting.