Skip to content

Instantly share code, notes, and snippets.

@hirokazumiyaji
Last active August 29, 2015 14:28
Show Gist options
  • Save hirokazumiyaji/e7c000855b505707f29d to your computer and use it in GitHub Desktop.
Save hirokazumiyaji/e7c000855b505707f29d to your computer and use it in GitHub Desktop.
Python cProfile/pstats output json format
# coding: utf-8
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pstats
class StatsLogger(object):
def __init__(self, stats):
self._logger = logging.getLogger(__name__)
self._stats = stats
def debug(self):
self._logger.debug(self.format_data())
def warn(self):
self._logger.warn(self.format_data())
def info(self):
self._logger.info(self.format_data())
def error(self):
self._logger.error(self.format_data())
def critical(self):
self._logger.critical(self.format_data())
def format_data(self):
_, list = self._stats.get_print_list(100)
details = []
for func in list:
cc, nc, tt, ct, callers = self.stats[func]
details.append( {
'ncalls': nc,
'tottime': tt,
'tottime percall': 0 if cc == 0 else tt / cc,
'cumtime': ct,
'cumtime percall': 0 if cc == 0 else ct / cc ,
'filename:lineno(function)': func,
})
return {
'function call': self._stats.total_calls,
'seconds': self._stats.total_tt,
'details': [
],
}
class Stats(pstats.Stats):
@property
def logger(self):
if hasattr(self, '_logger'):
return self._logger
_logger = StatsLogger(self)
setattr(self, '_logger', _logger)
return _logger
# import cProfile
# import profile
#
# p = cProfile.Profile()
# p.enable()
# func()
# stats = profile.Stats(p)
# stats.logger().debug()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment