Add examples.

This commit is contained in:
Dave Shawley 2015-06-08 13:20:03 -04:00
parent 6b04a86fda
commit f9959a52c3
4 changed files with 118 additions and 29 deletions

View file

@ -24,30 +24,32 @@ Requirements
Example
-------
This examples demonstrates how to use ``sprockets.logging`` by ...
This examples demonstrates the most basic usage of ``sprockets.logging``
.. code-block:: python
import logging
import sys
import sprockets.logging
formatter = logging.Formatter('%(levelname)s %(message)s {%(context)s}')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
handler.addFilter(sprockets.logging.ContextFilter(properties=['context']))
logging.Logger.root.addHandler(handler)
# Outputs: INFO Hi there {}
logging.Logger.root.setLevel(logging.DEBUG)
# Outputs: INFO Hi there {None}
logging.info('Hi there')
# Outputs: INFO No KeyError {bah}
logging.info('No KeyError', extra={'context': 'bah'})
# Outputs: INFO Now with context! {foo}
adapted = logging.LoggerAdapter(logging.Logger.root, extra={'context': 'foo'})
adapter.info('Now with context!')
adapted.info('Now with context!')
Source
------

View file

@ -3,29 +3,17 @@ Examples
Simple Usage
------------
The following snippet uses :class:`sprockets.logging.filters.ContextFilter`
The following snippet uses :class:`sprockets.logging.ContextFilter`
to insert context information into a message using a
:class:`logging.LoggerAdapter` instance.
.. code-block:: python
.. literalinclude:: ../examples/simple.py
import logging
import sys
Dictionary-based Configuration
------------------------------
This package begins to shine if you use the dictionary-based logging
configuration offered by :func:`logging.config.dictConfig`. You can insert
the custom filter and format string into the logging infrastructure and
insert context easily with :class:`logging.LoggerAdapter`.
import sprockets.logging
formatter = logging.Formatter('%(levelname)s %(message)s {%(context)s}')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
handler.addFilter(sprockets.logging.ContextFilter(properties=['context']))
logging.Logger.root.addHandler(handler)
# Outputs: INFO Hi there {}
logging.info('Hi there')
# Outputs: INFO No KeyError {bah}
logging.info('No KeyError', extra={'context': 'bah'})
# Outputs: INFO Now with context! {foo}
adapted = logging.LoggerAdapter(logging.Logger.root, extra={'context': 'foo'})
adapter.info('Now with context!')
.. literalinclude:: ../examples/tornado-app.py

22
examples/simple.py Normal file
View file

@ -0,0 +1,22 @@
import logging
import sys
import sprockets.logging
formatter = logging.Formatter('%(levelname)s %(message)s {%(context)s}')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
handler.addFilter(sprockets.logging.ContextFilter(properties=['context']))
logging.Logger.root.addHandler(handler)
logging.Logger.root.setLevel(logging.DEBUG)
# Outputs: INFO Hi there {None}
logging.info('Hi there')
# Outputs: INFO No KeyError {bah}
logging.info('No KeyError', extra={'context': 'bah'})
# Outputs: INFO Now with context! {foo}
adapted = logging.LoggerAdapter(logging.Logger.root, extra={'context': 'foo'})
adapted.info('Now with context!')

77
examples/tornado-app.py Normal file
View file

@ -0,0 +1,77 @@
import logging.config
import signal
import uuid
from tornado import ioloop, web
import sprockets.logging
LOG_CONFIG = {
'version': 1,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'stream': 'ext://sys.stdout',
'formatter': 'simple',
'filters': ['context'],
},
},
'formatters': {
'simple': {
'class': 'logging.Formatter',
'format': '%(levelname)s %(name)s: %(message)s [%(context)s]',
},
},
'filters': {
'context': {
'()': 'sprockets.logging.ContextFilter',
'properties': ['context'],
},
},
'loggers': {
'tornado': {
'level': 'DEBUG',
},
},
'root': {
'handlers': ['console'],
'level': 'DEBUG',
},
'incremental': False,
}
class RequestHandler(web.RequestHandler):
def __init__(self, *args, **kwargs):
self.parent_log = kwargs.pop('parent_log')
super(RequestHandler, self).__init__(*args, **kwargs)
def prepare(self):
uniq_id = self.request.headers.get('X-UniqID', uuid.uuid4().hex)
self.logger = logging.LoggerAdapter(
self.parent_log.getChild('RequestHandler'),
extra={'context': uniq_id})
def get(self, object_id):
self.logger.debug('fetchin %s', object_id)
self.set_status(200)
return self.finish()
def sig_handler(signo, frame):
logging.info('caught signal %d, stopping IO loop', signo)
iol = ioloop.IOLoop.instance()
iol.add_callback_from_signal(iol.stop)
if __name__ == '__main__':
logging.config.dictConfig(LOG_CONFIG)
logger = logging.getLogger('app')
app = web.Application([
web.url('/(?P<object_id>\w+)', RequestHandler,
kwargs={'parent_log': logger}),
])
app.listen(8000)
signal.signal(signal.SIGINT, sig_handler)
signal.signal(signal.SIGTERM, sig_handler)
ioloop.IOLoop.instance().start()
logger.info('IO loop stopped, exiting')