pax_global_header00006660000000000000000000000064121241022470014505gustar00rootroot0000000000000052 comment=e81fb4dea2077f6e9e873d07db831bbf931df174 pystatsd-2.0.1/000077500000000000000000000000001212410224700133605ustar00rootroot00000000000000pystatsd-2.0.1/.gitignore000066400000000000000000000000521212410224700153450ustar00rootroot00000000000000*.pyc *.egg-info build dist .tox .coveragepystatsd-2.0.1/.travis.yml000066400000000000000000000002311212410224700154650ustar00rootroot00000000000000language: python python: - "2.5" - "2.6" - "2.7" - "3.2" - "3.3" - "pypy" install: pip install -r requirements.txt --use-mirrors script: nosetests pystatsd-2.0.1/AUTHORS000066400000000000000000000003141212410224700144260ustar00rootroot00000000000000Lead Developer: - James Socol Contributors: - Jeff Balogh - Andy McKay - Daniel Holz - Kyle Conroy pystatsd-2.0.1/CHANGES000066400000000000000000000020051212410224700143500ustar00rootroot00000000000000Statsd Changelog ================ Version 2.0.1 ------------- - Fix install with Django 1.5 in the environment. Version 2.0 ----------- - Add Pipeline subclass for batching. - Added an _after method subclasses can use to change behavior. - Add support for gauge deltas. Version 1.0 ----------- - Clean up tests and requirements. - Encode socket data in ASCII. - Tag v1. Version 0.5.1 ------------- - Stop supporting IPv6. StatsD doesn't support it, and it breaks things. - incr, decr, and gauge now support floating point values. Version 0.5.0 ------------- - Add support for gauges. - Add real docs and hook up ReadTheDocs. - Add support for environment var configuration. Version 0.4.0 ------------- - Look up IP addresses once per client instance. - Support IPv6. Version 0.3.0 ------------- - Improve StatsClient.timer. - Remove nasty threadlocal stuff. - Return result of StatsClient.timer. Version 0.2.0 ------------- - Optional prefix for all stats. - Introduce StatsClient.timer context decorator. pystatsd-2.0.1/LICENSE000066400000000000000000000020401212410224700143610ustar00rootroot00000000000000Copyright (c) 2012, James Socol Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. pystatsd-2.0.1/MANIFEST.in000066400000000000000000000001411212410224700151120ustar00rootroot00000000000000include AUTHORS CHANGES LICENSE MANIFEST.in README.rst include setup.py recursive-include docs * pystatsd-2.0.1/README.rst000066400000000000000000000024161212410224700150520ustar00rootroot00000000000000====================== A Python statsd client ====================== .. image:: https://travis-ci.org/jsocol/pystatsd.png?branch=master :target: https://travis-ci.org/jsocol/pystatsd :alt: Travis-CI build status statsd_ is a friendly front-end to Graphite_. This is a Python client for the statsd daemon. Quickly, to use:: >>> import statsd >>> c = statsd.StatsClient('localhost', 8125) >>> c.incr('foo') # Increment the 'foo' counter. >>> c.timing('stats.timed', 320) # Record a 320ms 'stats.timed'. You can also add a prefix to all your stats:: >>> import statsd >>> c = statsd.StatsClient('localhost', 8125, prefix='foo') >>> c.incr('bar') # Will be 'foo.bar' in statsd/graphite. Installing ========== The easiest way to install statsd is with pip! You can install from PyPI:: $ pip install statsd Or GitHub:: $ pip install -e git+https://github.com/jsocol/pystatsd#egg=statsd Or from source:: $ git clone https://github.com/jsocol/pystatsd $ cd statsd $ python setup.py install Docs ==== There are lots of docs in the ``docs/`` directory and on ReadTheDocs_. .. _statsd: https://github.com/etsy/statsd .. _Graphite: http://graphite.wikidot.com/ .. _ReadTheDocs: http://statsd.readthedocs.org/en/latest/index.html pystatsd-2.0.1/docs/000077500000000000000000000000001212410224700143105ustar00rootroot00000000000000pystatsd-2.0.1/docs/Makefile000066400000000000000000000127241212410224700157560ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/PythonStatsD.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/PythonStatsD.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/PythonStatsD" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/PythonStatsD" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." pystatsd-2.0.1/docs/conf.py000066400000000000000000000173661212410224700156240ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Python StatsD documentation build configuration file, created by # sphinx-quickstart on Mon Apr 9 15:47:23 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.pngmath', 'sphinx.ext.mathjax', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Python StatsD' copyright = u'2012, James Socol' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '2.0' # The full version, including alpha/beta/rc tags. release = '2.0.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'PythonStatsDdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'PythonStatsD.tex', u'Python StatsD Documentation', u'James Socol', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pythonstatsd', u'Python StatsD Documentation', [u'James Socol'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'PythonStatsD', u'Python StatsD Documentation', u'James Socol', 'PythonStatsD', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' pystatsd-2.0.1/docs/configure.rst000066400000000000000000000050451212410224700170270ustar00rootroot00000000000000.. _configuring-chapter: ================== Configuring Statsd ================== It's easy to configure and use Statsd at runtime, but there are also two shortcuts available. Runtime ======= If you are running the statsd_ server locally and on the default port, it's extremely easy:: from statsd import StatsClient statsd = StatsClient() statsd.incr('foo') There are three arguments to configure your ``StatsClient`` instance. They, and their defaults, are:: from statsd import StatsClient statsd = StatsClient(host='localhost', port=8125, prefix=None) ``host`` is the host running the statsd server. It will support any kind of name or IP address you might use. ``port`` is the statsd server port. The default for both server and client is ``8125``. ``prefix`` helps distinguish multiple applications or environments using the same statsd server. It will be prepended to all stats, automatically. For example:: from statsd import StatsClient foo_stats = StatsClient(prefix='foo') bar_stats = StatsClient(prefix='bar') foo_stats.incr('baz') bar_stats.incr('baz') will produce two different stats, ``foo.baz`` and ``bar.baz``. Without the ``prefix`` argument, or with the same ``prefix``, two ``StatsClient`` instances will update the same stats. In Django ========= If you are using Statsd in a Django_ application, you can configure a default ``StatsClient`` in the Django settings. All of these settings are optional. Here are the settings and their defaults:: STATSD_HOST = 'localhost' STATSD_PORT = 8125 STATSD_PREFIX = None You can use the default ``StatsClient`` simply:: from statsd import statsd statsd.incr('foo') This instance will use the settings, if provided by Django. If no Django settings can be imported, it won't be available. From the Environment ==================== Statsd isn't only useful in Django or on the web. A default instance will also be available if you configure at least two environment variables. These do not have defaults. You can set these variables in the environment:: STATSD_HOST STATSD_PORT STATSD_PREFIX and then in your Python application, you can simply do:: from statsd import statsd statsd.incr('foo') .. note:: To make this default instance available, you will need to set at least ``STATSD_HOST`` and ``STATSD_PORT``, even if using the default values of ``localhost`` and ``8125``. .. _statsd: https://github.com/etsy/statsd .. _Django: https://www.djangoproject.com/ pystatsd-2.0.1/docs/contributing.rst000066400000000000000000000050411212410224700175510ustar00rootroot00000000000000.. _contributing-chapter: ============ Contributing ============ I happily accept patches if they make sense for the project and work well. If you aren't sure if I'll merge a patch upstream, please open an issue_ and describe it. Patches should meet the following criteria before I'll merge them: * All existing tests must pass. * Bugfixes and new features must include new tests or asserts. * Must not introduce any PEP8 or PyFlakes violations. I recommend doing all development in a virtualenv_, though this is really up to you. It would be great if new or changed features had documentation and included updates to the ``CHANGES`` file, but it's not totally necessary. Running Tests ============= To run the tests, you just need ``nose`` and ``mock``. These can be installed with ``pip``:: $ mkvirtualenv statsd $ pip install -r requirements.txt $ nosetests You can also run the tests with tox:: $ tox Tox will run the tests in Pythons 2.5, 2.6, 2.7, 3.2, 3.3, and PyPy, if they're available. Writing Tests ============= New features or bug fixes should include tests that fail without the relevant code changes and pass with them. For example, if there is a bug in the ``StatsClient._send`` method, a new test should demonstrate the incorrect behavior by failing, and the associated changes should fix it. The failure can be a FAILURE or an ERROR. Tests and the code to fix them should be in the same commit. Bisecting should not stumble over any otherwise known failures. .. note:: Pull requests that only contain tests to demonstrate bugs are welcome, but they will be squashed with code changes to fix them. PEP8 and PyFlakes ================= The development requirements (``requirements.txt``) include the ``flake8`` tool. It is easy to run:: $ flake8 statsd/ ``flake8`` should not raise any issues or warnings. .. note:: The docs directory includes a Sphinx-generated conf.py that has several violations. That's fine, don't worry about it. Documentation ============= The documentation lives in the ``docs/`` directory and is automatically built and pushed to ReadTheDocs_. If you change or add a feature, and want to update the docs, that would be great. New features may need a new chapter. You can follow the examples already there, and be sure to add a reference to ``docs/index.rst``. Changes or very small additions may just need a new heading in an existing chapter. .. _issue: https://github.com/jsocol/pystatsd/issues .. _virtualenv: http://www.virtualenv.org/ .. _ReadTheDocs: http://statsd.readthedocs.org/ pystatsd-2.0.1/docs/index.rst000066400000000000000000000030611212410224700161510ustar00rootroot00000000000000.. Python StatsD documentation master file, created by sphinx-quickstart on Mon Apr 9 15:47:23 2012. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to Python StatsD's documentation! ========================================= .. image:: https://travis-ci.org/jsocol/pystatsd.png?branch=master :target: https://travis-ci.org/jsocol/pystatsd :alt: Travis-CI build status statsd_ is a friendly front-end to Graphite_. This is a Python client for the statsd daemon. Quickly, to use:: >>> import statsd >>> c = statsd.StatsClient('localhost', 8125) >>> c.incr('foo') # Increment the 'foo' counter. >>> c.timing('stats.timed', 320) # Record a 320ms 'stats.timed'. You can also add a prefix to all your stats:: >>> import statsd >>> c = statsd.StatsClient('localhost', 8125, prefix='foo') >>> c.incr('bar') # Will be 'foo.bar' in statsd/graphite. Installing ---------- The easiest way to install statsd is with pip! You can install from PyPI:: $ pip install statsd Or GitHub:: $ pip install -e git+https://github.com/jsocol/pystatsd#egg=statsd Or from source:: $ git clone https://github.com/jsocol/pystatsd $ cd statsd $ python setup.py install Contents -------- .. toctree:: :maxdepth: 2 configure.rst types.rst timing.rst pipeline.rst reference.rst contributing.rst Indices and tables ------------------ * :ref:`search` .. _statsd: https://github.com/etsy/statsd .. _Graphite: http://graphite.wikidot.com/ pystatsd-2.0.1/docs/make.bat000066400000000000000000000117641212410224700157260ustar00rootroot00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . set I18NSPHINXOPTS=%SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. texinfo to make Texinfo files echo. gettext to make PO message catalogs echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml if errorlevel 1 exit /b 1 echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp if errorlevel 1 exit /b 1 echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\PythonStatsD.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\PythonStatsD.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp if errorlevel 1 exit /b 1 echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub if errorlevel 1 exit /b 1 echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex if errorlevel 1 exit /b 1 echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text if errorlevel 1 exit /b 1 echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man if errorlevel 1 exit /b 1 echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "texinfo" ( %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo if errorlevel 1 exit /b 1 echo. echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. goto end ) if "%1" == "gettext" ( %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale if errorlevel 1 exit /b 1 echo. echo.Build finished. The message catalogs are in %BUILDDIR%/locale. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes if errorlevel 1 exit /b 1 echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck if errorlevel 1 exit /b 1 echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest if errorlevel 1 exit /b 1 echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end pystatsd-2.0.1/docs/pipeline.rst000066400000000000000000000023131212410224700166460ustar00rootroot00000000000000.. _pipeline-chapter: ========= Pipelines ========= The ``Pipeline`` class is a subclass of ``StatsClient`` that batches together several stats before sending. It implements the entire client interface, plus a ``send()`` method. ``Pipeline`` objects should be created with ``StatsClient().pipeline()``:: client = StatsClient() pipe = client.pipeline() pipe.incr('foo') pipe.decr('bar') pipe.timing('baz', 520) pipe.send() No stats will be sent until ``send()`` is called, at which point they will be packed into as few UDP packets as possible. As a Context Manager ==================== ``Pipeline`` objects can also be used as context managers:: with StatsClient().pipeline() as pipe: pipe.incr('foo') pipe.decr('bar') ``pipe.send()`` will be called automatically when the managed block exits. Thread Safety ============= While ``StatsClient`` instances are considered thread-safe (or at least as thread-safe as the standard library's ``socket.send`` is), ``Pipeline`` instances **are not thread-safe**. Storing stats for later creates at least two important race conditions in a multi-threaded environment. You should create one ``Pipeline`` per-thread, if necessary. pystatsd-2.0.1/docs/reference.rst000066400000000000000000000100101212410224700167700ustar00rootroot00000000000000.. _reference-chapter: ============= API Reference ============= The ``StatsClient`` provides accessors for all the types of data the statsd_ server supports. .. note:: Each public API method supports a ``rate`` parameter, but statsd doesn't always use it the same way. See the :ref:`types-chapter` for more information. .. _StatsClient: ``StatsClient`` =============== :: StatsClient(host='localhost', port=8125, prefix=None) Create a new ``StatsClient`` instance with the appropriate connection and prefix information. * ``host``: the hostname or IPv4 address of the statsd_ server. * ``port``: the port of the statsd server. * ``prefix``: a prefix to distinguish and group stats from an application or environment. .. _incr: ``incr`` ======== :: StatsClient().incr(stat, count=1, rate=1) Increment a :ref:`counter `. * ``stat``: the name of the counter to increment. * ``count``: the amount to increment by. Typically an integer. May be negative, but see also :ref:`decr`. * ``rate``: a sample rate, a float between 0 and 1. Will only send data this percentage of the time. The statsd server will take the sample rate into account for counters. .. _decr: ``decr`` ======== :: StatsClient().decr(stat, count=1, rate=1) Decrement a :ref:`counter `. * ``stat``: the name of the counter to decrement. * ``count``: the amount to decrement by. Typically an integer. May be negative but that will have the impact of incrementing the counter. See also :ref:`incr`. * ``rate``: a sample rate, a float between 0 and 1. Will only send data this percentage of the time. The statsd server will take the sample rate into account for counters. .. _timing: ``timing`` ========== :: StatsClient().timing(stat, delta, rate=1) Record :ref:`timer ` information. * ``stat``: the name of the timer to use. * ``delta``: the number of milliseconds whatever action took. Should always be milliseconds. * ``rate``: a sample rate, a float between 0 and 1. Will only send data this percentage of the time. The statsd server does *not* take the sample rate into account for timers. .. _timer: ``timer`` ========= :: with StatsClient().timer(stat, rate=1): pass :: @StatsClient().timer(stat, rate=1) def foo(): pass Automatically record timing information for a managed block or function call. See also the :ref:`chapter on timing `. * ``stat``: the name of the timer to use. * ``rate``: a sample rate, a float between 0 and 1. Will only send data this percentage of the time. The statsd server does *not* take the sample rate into account for timers. .. _gauge: ``gauge`` ========= :: StatsClient().gauge(stat, value, rate=1, delta=False) Set a :ref:`gauge ` value. * ``stat``: the name of the gauge to set. * ``value``: the current value of the gauge. * ``rate``: a sample rate, a float between 0 and 1. Will only send data this percentage of the time. The statsd server does *not* take the sample rate into account for gauges. Use with care. * ``delta``: whether or not to consider this a delta value or an absolute value. See the :ref:`gauge ` type for more detail. .. note:: Gauges were added to the statsd server in commit 0ed78be_. If you try to use this method with an older version of the server, the data will not be recorded. .. _pipeline: ``pipeline`` ============ :: StatsClient().pipeline() Returns a :ref:`Pipeline ` object for collecting several stats. Can also be used as a context manager:: with StatsClient().pipeline() as pipe: pipe.incr('foo') .. _pipeline-send: ``send`` ======== :: pipe = StatsClient().pipeline() pipe.incr('foo') pipe.send() Causes a :ref:`Pipeline ` object to send all batched stats. .. note:: This method is not implemented on the base StatsClient class. .. _statsd: https://github.com/etsy/statsd .. _0ed78be: https://github.com/etsy/statsd/commit/0ed78be7 pystatsd-2.0.1/docs/timing.rst000066400000000000000000000032061212410224700163320ustar00rootroot00000000000000.. _timing-chapter: ============ Using Timers ============ :ref:`Timers ` are an incredibly powerful tool for tracking application performance. Statsd provides a number of ways to use them to instrument your code. Calling ``timing`` manually =========================== The simplest way to use a timer is to record the time yourself and send it manually, using the :ref:`timing` method:: import time from statsd import StatsClient statsd = StatsClient() start = time.time() time.sleep(3) # You must convert to milliseconds: dt = int((time.time() - start) * 1000) statsd.timing('slept', dt) Using a context manager ======================= Each ``StatsClient`` instance contains a :ref:`timer` attribute that can be used as a context manager or a decorator. When used as a context manager, it will automatically report the time taken for the inner block:: from statsd import StatsClient statsd = StatsClient() with statsd.timer('foo'): # This block will be timed. for i in xrange(0, 100000): i ** 2 # The timing is sent immediately when the managed block exits. Using a decorator ================= The ``timer`` attribute can also be used as a function decorator. Every time the decorated function is called, the time it took to execute will be sent to the statsd server. :: from statsd import StatsClient statsd = StatsClient() @statsd.timer('myfunc') def myfunc(a, b): """Calculate the most complicated thing a and b can do.""" # Timing information will be sent every time the function is called. myfunc(1, 2) myfunc(3, 7) pystatsd-2.0.1/docs/types.rst000066400000000000000000000113711212410224700162110ustar00rootroot00000000000000.. _types-chapter: ========== Data Types ========== The statsd_ server supports a number of different data types, and performs different aggregation on each of them. The three main types are *counters*, *timers*, and *gauges*. The statsd server collects and aggregates in 30 second intervals before flushing to Graphite_. Graphite usually stores the most recent data in 1-minute averaged buckets, so when you're looking at a graph, for each stat you are typically seing the average value over that minute. .. _counter-type: Counters ======== *Counters* are the most basic and default type. They are treated as a count of a type of event per second, and are, in Graphite_, typically averaged over one minute. That is, when looking at a graph, you are usually seeing the average number of events per second during a one-minute period. The statsd server collects counters under the ``stats`` prefix. Counters are managed with the :ref:`incr` and :ref:`decr` methods of ``StatsClient``:: from statsd import StatsClient statsd = StatsClient() statsd.incr('some.event') You can increment a counter by more than one by passing a second parameter:: statsd.incr('some.other.event', 10) You can also use the ``rate`` parameter to produce sampled data. The statsd server will take the sample rate into account, and the ``StatsClient`` will only send data ``rate`` percent of the time. This can help the statsd server stay responsive with extremely busy applications. ``rate`` is a float between 0 and 1:: # Increment this counter 10% of the time. statsd.incr('some.third.event', rate=0.1) Because the statsd server is aware of the sampling, it will still show you the true average rate per second. You can also decrement counters. The ``decr`` method takes the same arguments as ``incr``:: statsd.decr('some.other.event') # Decrease the counter by 5, 15% sample. statsd.decr('some.third.event', 5, rate=0.15) .. _timer-type: Timers ====== *Timers* are meant to track how long something took. They are an invaluable tool for tracking application performance. The statsd server collects all timers under the ``stats.timers`` prefix, and will calculate the lower bound, mean, 90th percentile, upper bound, and count of each timer for each period (by the time you see it in Graphite, that's usually per minute). * The *lower bound* is the lowest value statsd saw for that stat during that time period. * The *mean* is the average of all values statsd saw for that stat during that time period. * The *90th percentile* is a value *x* such that 90% of all the values statsd saw for that stat during that time period are below *x*, and 10% are above. This is a great number to try to optimize. * The *upper bound* is the highest value statsd saw for that stat during that time period. * The *count* is the number of timings statsd saw for that stat during that time period. It is not averaged. The statsd server only operates in millisecond timings. Everything should be converted to milliseconds. The ``rate`` parameter will sample the data being sent to the statsd server, but in this case it doesn't make sense for the statsd server to take it into account (except possibly for the *count* value, but then it would be lying about how much data it averaged). See the :ref:`timing documentation ` for more detail on using timers with Statsd. .. _gauge-type: Gauges ====== *Gauges* are a constant data type. They are not subject to averaging, and they don't change unless you change them. That is, once you set a gauge value, it will be a flat line on the graph until you change it again. Gauges are useful for things that are already averaged, or don't need to reset periodically. System load, for example, could be graphed with a gauge. You might use ``incr`` to count the number of logins to a system, but a gauge to track how many active WebSocket connections you have. The statsd server collects gauges under the ``stats.gauges`` prefix. The :ref:`gauge` method also support the ``rate`` parameter to sample data back to the statsd server, but use it with care, especially with gauges that may not be updated very often. Gauge Deltas ------------ Gauges may be *updated* (as opposed to *set*) by setting the ``delta`` keyword argument to ``True``. For example:: statsd.gauge('foo', 70) # Set the 'foo' gauge to 70. statsd.gauge('foo', 1, delta=True) # Set 'foo' to 71. statsd.gauge('foo', -3, delta=True) # Set 'foo' to 68. .. note:: Support for gauge deltas was added to the server in 3eecd18_. You will need to be running at least that version for the ``delta`` kwarg to have any effect. .. _statsd: https://github.com/etsy/statsd .. _Graphite: http://graphite.wikidot.com/ .. _3eecd18: https://github.com/etsy/statsd/commit/3eecd18 pystatsd-2.0.1/requirements.txt000066400000000000000000000000461212410224700166440ustar00rootroot00000000000000mock==1.0.1 nose==1.2.1 flake8==1.7.0 pystatsd-2.0.1/setup.py000066400000000000000000000026621212410224700151000ustar00rootroot00000000000000import os import re from setuptools import find_packages, setup VERSIONFILE = os.path.join('statsd', '_version.py') VSRE = r'^__version__ = [\'"]([^\'"]*)[\'"]' def get_version(): verstrline = open(VERSIONFILE, "rt").read() mo = re.search(VSRE, verstrline, re.M) if mo: return mo.group(1) else: raise RuntimeError( "Unable to find version string in %s." % VERSIONFILE) setup( name='statsd', version=get_version(), description='A simple statsd client.', long_description=open('README.rst').read(), author='James Socol', author_email='james@mozilla.com', url='https://github.com/jsocol/pystatsd', license='MIT', packages=find_packages(), include_package_data=True, package_data={'': ['README.rst']}, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries :: Python Modules', ] ) pystatsd-2.0.1/statsd/000077500000000000000000000000001212410224700146625ustar00rootroot00000000000000pystatsd-2.0.1/statsd/__init__.py000066400000000000000000000015541212410224700170000ustar00rootroot00000000000000from __future__ import absolute_import import os import socket try: from django.conf import settings except ImportError: settings = None from .client import StatsClient from ._version import __version__ __all__ = ['StatsClient', 'statsd'] statsd = None if settings: try: host = getattr(settings, 'STATSD_HOST', 'localhost') port = getattr(settings, 'STATSD_PORT', 8125) prefix = getattr(settings, 'STATSD_PREFIX', None) statsd = StatsClient(host, port, prefix) except (socket.error, socket.gaierror, ImportError): pass elif 'STATSD_HOST' in os.environ: try: host = os.environ['STATSD_HOST'] port = int(os.environ['STATSD_PORT']) prefix = os.environ.get('STATSD_PREFIX') statsd = StatsClient(host, port, prefix) except (socket.error, socket.gaierror, KeyError): pass pystatsd-2.0.1/statsd/_version.py000066400000000000000000000000261212410224700170560ustar00rootroot00000000000000__version__ = '2.0.1' pystatsd-2.0.1/statsd/client.py000066400000000000000000000065751212410224700165270ustar00rootroot00000000000000from __future__ import with_statement from functools import wraps import random import socket import time __all__ = ['StatsClient'] class Timer(object): """A context manager/decorator for statsd.timing().""" def __init__(self, client, stat, rate=1): self.client = client self.stat = stat self.rate = rate self.ms = None def __call__(self, f): @wraps(f) def wrapper(*args, **kw): with self: return f(*args, **kw) return wrapper def __enter__(self): self.start = time.time() return self def __exit__(self, typ, value, tb): dt = time.time() - self.start self.ms = int(round(1000 * dt)) # Convert to ms. self.client.timing(self.stat, self.ms, self.rate) class StatsClient(object): """A client for statsd.""" def __init__(self, host='localhost', port=8125, prefix=None): """Create a new client.""" self._addr = (socket.gethostbyname(host), port) self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self._prefix = prefix def _after(self, data): self._send(data) def pipeline(self): return Pipeline(self) def timer(self, stat, rate=1): return Timer(self, stat, rate) def timing(self, stat, delta, rate=1): """Send new timing information. `delta` is in milliseconds.""" data = self._prepare(stat, '%d|ms' % delta, rate) if data is not None: self._after(data) def incr(self, stat, count=1, rate=1): """Increment a stat by `count`.""" data = self._prepare(stat, '%s|c' % count, rate) if data is not None: self._after(data) def decr(self, stat, count=1, rate=1): """Decrement a stat by `count`.""" self.incr(stat, -count, rate) def gauge(self, stat, value, rate=1, delta=False): """Set a gauge value.""" if delta: value = '%+g|g' % value else: value = '%g|g' % value data = self._prepare(stat, value, rate) if data is not None: self._after(data) def _prepare(self, stat, value, rate=1): if rate < 1: if random.random() < rate: value = '%s|@%s' % (value, rate) else: return if self._prefix: stat = '%s.%s' % (self._prefix, stat) data = '%s:%s' % (stat, value) return data def _send(self, data): """Send data to statsd.""" try: self._sock.sendto(data.encode('ascii'), self._addr) except socket.error: # No time for love, Dr. Jones! pass class Pipeline(StatsClient): def __init__(self, client): self._client = client self._prefix = client._prefix self._stats = [] def _after(self, data): self._stats.append(data) def __enter__(self): return self def __exit__(self, typ, value, tb): self.send() def send(self): # Use pop(0) to preserve the order of the stats. data = self._stats.pop(0) while self._stats: stat = self._stats.pop(0) if len(stat) + len(data) + 1 >= 512: self._client._send(data) data = stat else: data += '\n' + stat if data: self._client._send(data) pystatsd-2.0.1/statsd/tests.py000066400000000000000000000164061212410224700164050ustar00rootroot00000000000000from __future__ import with_statement import random import re import socket import mock from nose.tools import eq_ from statsd import StatsClient ADDR = (socket.gethostbyname('localhost'), 8125) def _client(prefix=None): sc = StatsClient(host=ADDR[0], port=ADDR[1], prefix=prefix) sc._sock = mock.Mock() return sc def _sock_check(cl, count, val): eq_(cl._sock.sendto.call_count, count) if val: val = val.encode('ascii') eq_(cl._sock.sendto.call_args, ((val, ADDR), {})) else: eq_(cl._sock.sendto.call_args, None) class assert_raises(object): """A context manager that asserts a given exception was raised. >>> with assert_raises(TypeError): ... raise TypeError >>> with assert_raises(TypeError): ... raise ValueError AssertionError: ValueError not in ['TypeError'] >>> with assert_raises(TypeError): ... pass AssertionError: No exception raised. Or you can specify any of a number of exceptions: >>> with assert_raises(TypeError, ValueError): ... raise ValueError >>> with assert_raises(TypeError, ValueError): ... raise KeyError AssertionError: KeyError not in ['TypeError', 'ValueError'] You can also get the exception back later: >>> with assert_raises(TypeError) as cm: ... raise TypeError('bad type!') >>> cm.exception TypeError('bad type!') >>> cm.exc_type TypeError >>> cm.traceback Lowercase name because that it's a class is an implementation detail. """ def __init__(self, *exc_cls): self.exc_cls = exc_cls def __enter__(self): # For access to the exception later. return self def __exit__(self, typ, value, tb): assert typ, 'No exception raised.' assert typ in self.exc_cls, '%s not in %s' % ( typ.__name__, [e.__name__ for e in self.exc_cls]) self.exc_type = typ self.exception = value self.traceback = tb # Swallow expected exceptions. return True @mock.patch.object(random, 'random', lambda: -1) def test_incr(): sc = _client() sc.incr('foo') _sock_check(sc, 1, 'foo:1|c') sc.incr('foo', 10) _sock_check(sc, 2, 'foo:10|c') sc.incr('foo', 1.2) _sock_check(sc, 3, 'foo:1.2|c') sc.incr('foo', 10, rate=0.5) _sock_check(sc, 4, 'foo:10|c|@0.5') @mock.patch.object(random, 'random', lambda: -1) def test_decr(): sc = _client() sc.decr('foo') _sock_check(sc, 1, 'foo:-1|c') sc.decr('foo', 10) _sock_check(sc, 2, 'foo:-10|c') sc.decr('foo', 1.2) _sock_check(sc, 3, 'foo:-1.2|c') sc.decr('foo', 1, rate=0.5) _sock_check(sc, 4, 'foo:-1|c|@0.5') @mock.patch.object(random, 'random', lambda: -1) def test_gauge(): sc = _client() sc.gauge('foo', 30) _sock_check(sc, 1, 'foo:30|g') sc.gauge('foo', 1.2) _sock_check(sc, 2, 'foo:1.2|g') sc.gauge('foo', 70, rate=0.5) _sock_check(sc, 3, 'foo:70|g|@0.5') def test_gauge_delta(): sc = _client() sc.gauge('foo', 12, delta=True) _sock_check(sc, 1, 'foo:+12|g') sc.gauge('foo', -13, delta=True) _sock_check(sc, 2, 'foo:-13|g') sc.gauge('foo', 1.2, delta=True) _sock_check(sc, 3, 'foo:+1.2|g') sc.gauge('foo', -1.3, delta=True) _sock_check(sc, 4, 'foo:-1.3|g') @mock.patch.object(random, 'random', lambda: -1) def test_timing(): sc = _client() sc.timing('foo', 100) _sock_check(sc, 1, 'foo:100|ms') sc.timing('foo', 350) _sock_check(sc, 2, 'foo:350|ms') sc.timing('foo', 100, rate=0.5) _sock_check(sc, 3, 'foo:100|ms|@0.5') def test_prepare(): sc = _client(None) tests = ( ('foo:1|c', ('foo', '1|c', 1)), ('bar:50|ms|@0.5', ('bar', '50|ms', 0.5)), ('baz:23|g', ('baz', '23|g', 1)), ) def _check(o, s, v, r): with mock.patch.object(random, 'random', lambda: -1): eq_(o, sc._prepare(s, v, r)) for o, (s, v, r) in tests: yield _check, o, s, v, r def test_prefix(): sc = _client('foo') sc.incr('bar') _sock_check(sc, 1, 'foo.bar:1|c') def _timer_check(cl, count, start, end): eq_(cl._sock.sendto.call_count, count) value = cl._sock.sendto.call_args[0][0].decode('ascii') exp = re.compile('^%s:\d+|%s$' % (start, end)) assert exp.match(value) def test_timer_manager(): """StatsClient.timer is a context manager.""" sc = _client() with sc.timer('foo'): pass _timer_check(sc, 1, 'foo', 'ms') def test_timer_decorator(): """StatsClient.timer is a decorator.""" sc = _client() @sc.timer('bar') def bar(): pass bar() _timer_check(sc, 1, 'bar', 'ms') def test_timer_capture(): """You can capture the output of StatsClient.timer.""" sc = _client() with sc.timer('woo') as result: eq_(result.ms, None) assert isinstance(result.ms, int) @mock.patch.object(random, 'random', lambda: -1) def test_timer_context_rate(): sc = _client() with sc.timer('foo', rate=0.5): pass _timer_check(sc, 1, 'foo', 'ms|@0.5') @mock.patch.object(random, 'random', lambda: -1) def test_timer_decorator_rate(): sc = _client() @sc.timer('bar', rate=0.1) def bar(): pass bar() _timer_check(sc, 1, 'bar', 'ms|@0.1') def test_timer_context_exceptions(): """Exceptions within a managed block should get logged and propagate.""" sc = _client() with assert_raises(socket.timeout): with sc.timer('foo'): raise socket.timeout() _timer_check(sc, 1, 'foo', 'ms') def test_timer_decorator_exceptions(): """Exceptions from wrapped methods should get logged and propagate.""" sc = _client() @sc.timer('foo') def foo(): raise ValueError() with assert_raises(ValueError): foo() _timer_check(sc, 1, 'foo', 'ms') def test_pipeline(): sc = _client() pipe = sc.pipeline() pipe.incr('foo') pipe.decr('bar') pipe.timing('baz', 320) pipe.send() _sock_check(sc, 1, 'foo:1|c\nbar:-1|c\nbaz:320|ms') def test_pipeline_manager(): sc = _client() with sc.pipeline() as pipe: pipe.incr('foo') pipe.decr('bar') pipe.gauge('baz', 15) _sock_check(sc, 1, 'foo:1|c\nbar:-1|c\nbaz:15|g') def test_pipeline_timer_manager(): sc = _client() with sc.pipeline() as pipe: with pipe.timer('foo'): pass _timer_check(sc, 1, 'foo', 'ms') def test_pipeline_timer_decorator(): sc = _client() with sc.pipeline() as pipe: @pipe.timer('foo') def foo(): pass foo() _timer_check(sc, 1, 'foo', 'ms') def test_pipeline_empty(): """Pipelines should be empty after a send() call.""" sc = _client() with sc.pipeline() as pipe: pipe.incr('foo') eq_(1, len(pipe._stats)) eq_(0, len(pipe._stats)) def test_pipeline_packet_size(): """Pipelines shouldn't send packets larger than 512 bytes.""" sc = _client() pipe = sc.pipeline() for x in range(32): # 32 * 16 = 512, so this will need 2 packets. pipe.incr('sixteen_char_str') pipe.send() eq_(2, sc._sock.sendto.call_count) assert len(sc._sock.sendto.call_args_list[0][0][0]) <= 512 assert len(sc._sock.sendto.call_args_list[1][0][0]) <= 512 pystatsd-2.0.1/tox.ini000066400000000000000000000002751212410224700146770ustar00rootroot00000000000000[tox] envlist = py25,py26,py27,pypy,py32,py33 [testenv] deps= mock==1.0.1 nose==1.2.1 coverage==3.5.2 commands= nosetests statsd --with-coverage --cover-package=statsd []