pax_global_header00006660000000000000000000000064123652525160014521gustar00rootroot0000000000000052 comment=26e90781c283ecb982610abd22aad0e2b1d6d2bf pystatsd-3.0.1/000077500000000000000000000000001236525251600133755ustar00rootroot00000000000000pystatsd-3.0.1/.gitignore000066400000000000000000000000751236525251600153670ustar00rootroot00000000000000*.pyc *.egg-info build dist .tox .coverage *.swp docs/_build pystatsd-3.0.1/.travis.yml000066400000000000000000000001421236525251600155030ustar00rootroot00000000000000language: python python: - "2.6" - "2.7" - "3.2" - "3.3" - "3.4" - "pypy" script: nosetests pystatsd-3.0.1/AUTHORS000066400000000000000000000003141236525251600144430ustar00rootroot00000000000000Lead Developer: - James Socol Contributors: - Jeff Balogh - Andy McKay - Daniel Holz - Kyle Conroy pystatsd-3.0.1/CHANGES000066400000000000000000000034051236525251600143720ustar00rootroot00000000000000Statsd Changelog ================ Version 3.0.1 ------------- - Make timers-as-decorators threadsafe. Version 3.0 ----------- - Moved default client instances out of __init__.py. Now find them in the `statsd.defaults.{django,env}` modules. Version 2.1.2 ------------- - Fix negative absolute (non-delta) gauges. - Improve test coverage. Version 2.1.1 ------------- - Fix issue with timers used as decorators. Version 2.1 ----------- - Add maxudpsize option for Pipelines. - Add methods to use Timer objects directly. Version 2.0.3 ------------- - Handle large numbers in gauges correctly. - Add `set` type. - Pipelines use parent client's _after method. Version 2.0.2 ------------- - Don't try to pop stats off an empty pipeline. - Fix installs with Django 1.5 on the PYTHONPATH. 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-3.0.1/LICENSE000066400000000000000000000020401236525251600143760ustar00rootroot00000000000000Copyright (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-3.0.1/MANIFEST.in000066400000000000000000000001411236525251600151270ustar00rootroot00000000000000include AUTHORS CHANGES LICENSE MANIFEST.in README.rst include setup.py recursive-include docs * pystatsd-3.0.1/README.rst000066400000000000000000000024221236525251600150640ustar00rootroot00000000000000====================== 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.readthedocs.org/ .. _ReadTheDocs: http://statsd.readthedocs.org/en/latest/index.html pystatsd-3.0.1/docs/000077500000000000000000000000001236525251600143255ustar00rootroot00000000000000pystatsd-3.0.1/docs/Makefile000066400000000000000000000127241236525251600157730ustar00rootroot00000000000000# 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-3.0.1/docs/conf.py000066400000000000000000000173641236525251600156370ustar00rootroot00000000000000# -*- 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'2014, 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 = '3.0' # The full version, including alpha/beta/rc tags. release = '3.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-3.0.1/docs/configure.rst000066400000000000000000000056521236525251600170500ustar00rootroot00000000000000.. _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, maxudpsize=512) ``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. .. versionadded:: 2.0.3 ``maxudpsize`` specifies the maximum packet size statsd will use. This is an advanced options and should not be changed unless you know what you are doing. Larger values then the default of 512 are generally deemed unsafe for use on the internet. On a controlled local network or when the statsd server is running on 127.0.0.1 larger values can decrease the number of UDP packets when pipelining many metrics. Use with care! 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 STATSD_MAXUDPSIZE = 512 You can use the default ``StatsClient`` simply:: from statsd.defaults.django import statsd statsd.incr('foo') From the Environment ==================== Statsd isn't only useful in Django or on the web. A default instance can also be configured via environment variables. Here are the environment variables and their defaults:: STATSD_HOST=localhost STATSD_PORT=8125 STATSD_PREFIX=None STATSD_MAXUDPSIZE=512 and then in your Python application, you can simply do:: from statsd.defaults.env import statsd statsd.incr('foo') .. note:: As of version 3.0, this default instance is always available, configured with the default values, unless overridden by the environment. .. _statsd: https://github.com/etsy/statsd .. _Django: https://www.djangoproject.com/ pystatsd-3.0.1/docs/contributing.rst000066400000000000000000000050461236525251600175730ustar00rootroot00000000000000.. _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, 3.4, 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-3.0.1/docs/index.rst000066400000000000000000000030651236525251600161720ustar00rootroot00000000000000.. 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.readthedocs.org/ pystatsd-3.0.1/docs/make.bat000066400000000000000000000117641236525251600157430ustar00rootroot00000000000000@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-3.0.1/docs/pipeline.rst000066400000000000000000000023131236525251600166630ustar00rootroot00000000000000.. _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-3.0.1/docs/reference.rst000066400000000000000000000136201236525251600170170ustar00rootroot00000000000000.. _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. .. _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. .. _set: ``set`` --------- :: StatsClient().set(stat, value, rate=1) Increment a :ref:`set ` value. * ``stat``: the name of the set to update. * ``value``: the unique value to count. * ``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 sets. Use with care. .. note:: Sets were added to the statsd server in commit 1c10cfc0ac_. If you try to use this method with an older version of the server, the data will not be recorded. .. _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 :: timer = StatsClient().timer('foo', rate=1) 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. .. warning:: Decorators are not thread-safe and may cause errors when decorated functions are called concurrently. Use context managers or raw timers instead. .. _timer-start: ``start`` --------- :: StatsClient().timer('foo').start() Causes a timer object to start counting. Called automatically when the object is used as a decorator or context manager. Returns the timer object for simplicity. .. _timer-stop: ``stop`` -------- :: timer = StatsClient().timer('foo').start() timer.stop() Causes the timer object to stop timing and send the results to statsd_. Can be called with ``send=False`` to prevent immediate sending immediately, and use ``send()``. Called automatically when the object is used as a decorator or context manager. Returns the timer object. If ``stop()`` is called before ``start()``, a ``RuntimeError`` is raised. .. _timer-send: ``send`` -------- :: timer = StatsClient().timer('foo').start() timer.stop(send=False) timer.send() Causes the timer to send any unsent data. If the data has already been sent, or has not yet been recorded, a ``RuntimeError`` is raised. .. note:: See the note abbout :ref:`timer objects and pipelines `. .. _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 .. _1c10cfc0ac: https://github.com/etsy/statsd/commit/1c10cfc0ac pystatsd-3.0.1/docs/timing.rst000066400000000000000000000064111236525251600163500ustar00rootroot00000000000000.. _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. There are four ways to use timers. 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 decorates your methods in a thread-safe manner. 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) Using a Timer object directly ============================= .. versionadded:: 2.1 :py:class:`statsd.client.Timer` objects function as context managers and as decorators, but they can also be used directly. (Flat is, after all, better than nested.) :: from statsd import StatsClient statsd = StatsClient() foo_timer = statsd.timer('foo') foo_timer.start() # Do something fun. foo_timer.stop() When :py:meth:`statsd.client.Timer.stop` is called, a :ref:`timing stat `_ will automatically be sent to StatsD. You can over ride this behavior with the ``send=False`` keyword argument to ``stop()``:: foo_timer.stop(send=False) foo_timer.send() Use :py:meth:`statsd.client.Timer.send` to send the stat when you're ready. .. _timer-direct-note: .. note:: This use of timers is compatible with :ref:`Pipelines `_ but be careful with the ``send()`` method. It *must* be called for the stat to be included when the Pipeline finally sends data, but ``send()`` will *not* immediately cause data to be sent in the context of a Pipeline. For example:: with statsd.pipeline() as pipe: foo_timer = pipe.timer('foo').start() # Do something... pipe.incr('bar') foo_timer.stop() # Will be sent when the managed block exits. with statsd.pipeline() as pipe: foo_timer = pipe.timer('foo').start() # Do something... pipe.incr('bar') foo_timer.stop(send=False) # Will not be sent. foo_timer.send() # Will be sent when the managed block exits. # Do something else... pystatsd-3.0.1/docs/types.rst000066400000000000000000000121041236525251600162210ustar00rootroot00000000000000.. _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. .. _set-type: Sets ====== *Sets* count the number of unique values passed to a key. For example, you could count the number of users accessing your system using: statsd.set('users', userid) If that method is called multiple times with the same userid in the same sample period, that userid will only be counted once. .. _statsd: https://github.com/etsy/statsd .. _Graphite: http://graphite.readthedocs.org .. _3eecd18: https://github.com/etsy/statsd/commit/3eecd18 pystatsd-3.0.1/requirements.txt000066400000000000000000000000461236525251600166610ustar00rootroot00000000000000mock==1.0.1 nose==1.2.1 flake8==1.7.0 pystatsd-3.0.1/setup.cfg000066400000000000000000000000341236525251600152130ustar00rootroot00000000000000[bdist_wheel] universal = 1 pystatsd-3.0.1/setup.py000066400000000000000000000023171236525251600151120ustar00rootroot00000000000000import os import re from setuptools import find_packages, setup setup( name='statsd', version='3.0.1', 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']}, test_suite='nose.collector', 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', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development :: Libraries :: Python Modules', ], ) pystatsd-3.0.1/statsd/000077500000000000000000000000001236525251600146775ustar00rootroot00000000000000pystatsd-3.0.1/statsd/__init__.py000066400000000000000000000002421236525251600170060ustar00rootroot00000000000000from __future__ import absolute_import from .client import StatsClient VERSION = (3, 0, 1) __version__ = '.'.join(map(str, VERSION)) __all__ = ['StatsClient'] pystatsd-3.0.1/statsd/client.py000066400000000000000000000113301236525251600165250ustar00rootroot00000000000000from __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 self._sent = False self._start_time = None def __call__(self, f): """Thread-safe timing function decorator.""" @wraps(f) def _wrapped(*args, **kwargs): start_time = time.time() try: return_value = f(*args, **kwargs) finally: elapsed_time_ms = int(round(1000 * (time.time() - start_time))) self.client.timing(self.stat, elapsed_time_ms, self.rate) return return_value return _wrapped def __enter__(self): return self.start() def __exit__(self, typ, value, tb): self.stop() def start(self): self.ms = None self._sent = False self._start_time = time.time() return self def stop(self, send=True): if self._start_time is None: raise RuntimeError('Timer has not started.') dt = time.time() - self._start_time self.ms = int(round(1000 * dt)) # Convert to milliseconds. if send: self.send() return self def send(self): if self.ms is None: raise RuntimeError('No data recorded.') if self._sent: raise RuntimeError('Already sent data.') self._sent = True 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, maxudpsize=512): """Create a new client.""" self._addr = (socket.gethostbyname(host), port) self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self._prefix = prefix self._maxudpsize = maxudpsize 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.""" self._send_stat(stat, '%d|ms' % delta, rate) def incr(self, stat, count=1, rate=1): """Increment a stat by `count`.""" self._send_stat(stat, '%s|c' % count, rate) 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 value < 0 and not delta: if rate < 1: if random.random() > rate: return with self.pipeline() as pipe: pipe._send_stat(stat, '0|g', 1) pipe._send_stat(stat, '%s|g' % value, 1) else: prefix = '+' if delta and value >= 0 else '' self._send_stat(stat, '%s%s|g' % (prefix, value), rate) def set(self, stat, value, rate=1): """Set a set value.""" self._send_stat(stat, '%s|s' % value, rate) def _send_stat(self, stat, value, rate): self._after(self._prepare(stat, value, rate)) def _prepare(self, stat, value, rate): if rate < 1: if random.random() > rate: return value = '%s|@%s' % (value, rate) if self._prefix: stat = '%s.%s' % (self._prefix, stat) return '%s:%s' % (stat, value) def _after(self, data): if data: self._send(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._maxudpsize = client._maxudpsize self._stats = [] def _after(self, data): if data is not None: 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. if not self._stats: return data = self._stats.pop(0) while self._stats: stat = self._stats.pop(0) if len(stat) + len(data) + 1 >= self._maxudpsize: self._client._after(data) data = stat else: data += '\n' + stat self._client._after(data) pystatsd-3.0.1/statsd/defaults/000077500000000000000000000000001236525251600165065ustar00rootroot00000000000000pystatsd-3.0.1/statsd/defaults/__init__.py000066400000000000000000000000761236525251600206220ustar00rootroot00000000000000HOST = 'localhost' PORT = 8125 PREFIX = None MAXUDPSIZE = 512 pystatsd-3.0.1/statsd/defaults/django.py000066400000000000000000000007541236525251600203300ustar00rootroot00000000000000from __future__ import absolute_import from django.conf import settings from statsd import defaults from statsd.client import StatsClient statsd = None if statsd is None: host = getattr(settings, 'STATSD_HOST', defaults.HOST) port = getattr(settings, 'STATSD_PORT', defaults.PORT) prefix = getattr(settings, 'STATSD_PREFIX', defaults.PREFIX) maxudpsize = getattr(settings, 'STATSD_MAXUDPSIZE', defaults.MAXUDPSIZE) statsd = StatsClient(host, port, prefix, maxudpsize) pystatsd-3.0.1/statsd/defaults/env.py000066400000000000000000000006771236525251600176620ustar00rootroot00000000000000from __future__ import absolute_import import os from statsd import defaults from statsd.client import StatsClient statsd = None if statsd is None: host = os.getenv('STATSD_HOST', defaults.HOST) port = int(os.getenv('STATSD_PORT', defaults.PORT)) prefix = os.getenv('STATSD_PREFIX', defaults.PREFIX) maxudpsize = int(os.getenv('STATSD_MAXUDPSIZE', defaults.MAXUDPSIZE)) statsd = StatsClient(host, port, prefix, maxudpsize) pystatsd-3.0.1/statsd/tests.py000066400000000000000000000260661236525251600164250ustar00rootroot00000000000000from __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=None): eq_(cl._sock.sendto.call_count, count) if val is not None: val = val.encode('ascii') eq_(cl._sock.sendto.call_args, ((val, ADDR), {})) 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(): tests = ( (12, '+12'), (-13, '-13'), (1.2, '+1.2'), (-1.3, '-1.3'), ) def _check(num, result): sc = _client() sc.gauge('foo', num, delta=True) _sock_check(sc, 1, 'foo:%s|g' % result) for num, result in tests: yield _check, num, result def test_gauge_absolute_negative(): sc = _client() sc.gauge('foo', -5, delta=False) _sock_check(sc, 1, 'foo:0|g\nfoo:-5|g') @mock.patch.object(random, 'random') def test_gauge_absolute_negative_rate(mock_random): sc = _client() mock_random.return_value = -1 sc.gauge('foo', -1, rate=0.5, delta=False) _sock_check(sc, 1, 'foo:0|g\nfoo:-1|g') mock_random.return_value = 2 sc.gauge('foo', -2, rate=0.5, delta=False) _sock_check(sc, 1, 'foo:0|g\nfoo:-1|g') # Should not have changed. @mock.patch.object(random, 'random', lambda: -1) def test_set(): sc = _client() sc.set('foo', 10) _sock_check(sc, 1, 'foo:10|s') sc.set('foo', 2.3) _sock_check(sc, 2, 'foo:2.3|s') sc.set('foo', 'bar') _sock_check(sc, 3, 'foo:bar|s') sc.set('foo', 2.3, 0.5) _sock_check(sc, 4, 'foo:2.3|s|@0.5') @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 thread-safe decorator.""" sc = _client() @sc.timer('foo') def foo(a, b): return [a, b] @sc.timer('bar') def bar(a, b): return [b, a] # make sure it works with more than one decorator, called multiple times, # and that parameters are handled correctly eq_([4, 2], foo(4, 2)) _timer_check(sc, 1, 'foo', 'ms') eq_([2, 4], bar(4, 2)) _timer_check(sc, 2, 'bar', 'ms') eq_([6, 5], bar(5, 6)) _timer_check(sc, 3, '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('foo', rate=0.1) def foo(a, b): return [b, a] @sc.timer('bar', rate=0.2) def bar(a, b=2, c=3): return [c, b, a] eq_([2, 4], foo(4, 2)) _timer_check(sc, 1, 'foo', 'ms|@0.1') eq_([3, 2, 5], bar(5)) _timer_check(sc, 2, 'bar', 'ms|@0.2') 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_timer_object(): sc = _client() t = sc.timer('foo').start() t.stop() _timer_check(sc, 1, 'foo', 'ms') def test_timer_object_no_send(): sc = _client() t = sc.timer('foo').start() t.stop(send=False) _sock_check(sc, 0) t.send() _timer_check(sc, 1, 'foo', 'ms') @mock.patch.object(random, 'random', lambda: -1) def test_timer_object_rate(): sc = _client() t = sc.timer('foo', rate=0.5) t.start() t.stop() _timer_check(sc, 1, 'foo', 'ms@0.5') def test_timer_object_no_send_twice(): sc = _client() t = sc.timer('foo').start() t.stop() with assert_raises(RuntimeError): t.send() def test_timer_send_without_stop(): sc = _client() with sc.timer('foo') as t: assert t.ms is None with assert_raises(RuntimeError): t.send() t = sc.timer('bar').start() assert t.ms is None with assert_raises(RuntimeError): t.send() def test_timer_object_stop_without_start(): sc = _client() with assert_raises(RuntimeError): sc.timer('foo').stop() 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_null(): """Ensure we don't error on an empty pipeline.""" sc = _client() pipe = sc.pipeline() pipe.send() _sock_check(sc, 0) 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_timer_object(): sc = _client() with sc.pipeline() as pipe: t = pipe.timer('foo').start() t.stop() _sock_check(sc, 0) _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 def test_pipeline_negative_absolute_gauge(): """Negative absolute gauges use an internal pipeline.""" sc = _client() with sc.pipeline() as pipe: pipe.gauge('foo', -10, delta=False) pipe.incr('bar') _sock_check(sc, 1, 'foo:0|g\nfoo:-10|g\nbar:1|c') def test_big_numbers(): num = 1234568901234 result = 'foo:1234568901234|%s' tests = ( # Explicitly create strings so we avoid the bug we're trying to test. ('gauge', 'g'), ('incr', 'c'), ('timing', 'ms'), ) def _check(method, suffix): sc = _client() getattr(sc, method)('foo', num) _sock_check(sc, 1, result % suffix) for method, suffix in tests: yield _check, method, suffix @mock.patch.object(random, 'random', lambda: 2) def test_rate_no_send(): sc = _client() sc.incr('foo', rate=0.5) _sock_check(sc, 0) def test_socket_error(): sc = _client() sc._sock.sendto.side_effect = socket.timeout() sc.incr('foo') _sock_check(sc, 1, 'foo:1|c') pystatsd-3.0.1/tox.ini000066400000000000000000000002751236525251600147140ustar00rootroot00000000000000[tox] envlist = py26,py27,pypy,py32,py33,py34 [testenv] deps= mock==1.0.1 nose==1.2.1 coverage==3.5.2 commands= nosetests statsd --with-coverage --cover-package=statsd []