Skip to content

Instantly share code, notes, and snippets.

@charles-dyfis-net
Created September 6, 2011 21:13
Show Gist options
  • Save charles-dyfis-net/1198987 to your computer and use it in GitHub Desktop.
Save charles-dyfis-net/1198987 to your computer and use it in GitHub Desktop.
Example of instrumenting jinja2 to trace template components
import contextlib
@contextlib.contextmanager
def trace_to_stderr(name):
"""Trivial proof-of-concept for tracing template rendering"""
print >>sys.stderr, 'ENTER: %s' % (name,)
yield
print >>sys.stderr, 'EXIT: %s' % (name,)
class trace_decorator(object):
def __init__(self, contextmgr_type, item_type, item_name, *args, **kwargs):
self.contextmgr_type = contextmgr_type
self.args = (item_name, item_type) + args
self.kwargs = kwargs
def __call__(self, function):
@functools.wraps(function)
def wrapped(*args, **kwargs):
name = 'jinja2.%s' % ('.'.join((n.replace('.','_').replace('/','_') for n in self.args)))
with self.contextmgr_type(name):
return function(*args, **kwargs)
return wrapped
import os
if os.environ.get('ENABLE_TRACELYTICS'):
import oboe
trace_method = oboe.Context.profile_block
else:
trace_method = trace_to_stderr
block_decorator = functools.partial(trace_decorator, trace_method, 'block')
macro_decorator = functools.partial(trace_decorator, trace_method, 'macro')
macro_call_decorator = functools.partial(trace_decorator, trace_method, 'macro_call')
class TracedEnvironment(jinja2.Environment):
def __init__(self, **options):
if os.environ.get('ENABLE_TRACELYTICS'):
self.block_decorator = '%s.block_decorator' % __name__
self.macro_decorator = '%s.macro_decorator' % __name__
self.macro_call_decorator = '%s.macro_call_decorator' % __name__
jinja2.Environment.__init__(self, **options)
Copy link

ghost commented Nov 15, 2013

I can't get this to work with latest jinja2. I tried adapting it (I did figure out how it works...), but jinja2 doesn't seem to have a place to add the context objects.

I'll watch here to see if anyone else can get jinja2 tracing to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment