[Twisted-Python] [ANN] structlog – bring context & structure to your logs without boilerplate
Hi folks,
today, I’ve release the 0.2.0 of my structlog project whose ambition is no less than changing the way we log in Python. :)
And since it sports dedicated support for Twisted http://www.structlog.org/en/latest/twisted.html (but is not limited to it, it wraps *any* logger), I’d like to introduce you to it.
Basically, its premise is that events happen in a context and you want to log out both effortlessly. Nowadays logs are usually consumed by parsers anyway, so regular, easily parsable logs are a good thing™.
This is a nice example of a Twisted application showing off a bit what structlog is capable of:
import sys
import uuid
import structlog
import twisted
from twisted.internet import protocol, reactor
logger = structlog.getLogger()
class Counter(object):
i = 0
def inc(self):
self.i += 1
def __repr__(self):
return str(self.i)
class Echo(protocol.Protocol):
def connectionMade(self):
self._counter = Counter()
self._log = logger.new(
connection_id=str(uuid.uuid4()),
peer=self.transport.getPeer().host,
count=self._counter,
)
def dataReceived(self, data):
self._counter.inc()
log = self._log.bind(data=data)
self.transport.write(data)
log.msg('echoed data!')
if __name__ == "__main__":
structlog.configure(
processors=[structlog.twisted.EventAdapter()],
logger_factory=structlog.twisted.LoggerFactory(),
)
twisted.python.log.startLogging(sys.stderr)
reactor.listenTCP(1234, protocol.Factory.forProtocol(Echo))
reactor.run()
It will give you an output like:
2013-09-17 17:40:23+0200 [-] Log opened.
2013-09-17 17:40:23+0200 [-] Factory starting on 1234
2013-09-17 17:40:23+0200 [-] Starting factory
participants (1)
-
Hynek Schlawack