Skip to content

Instantly share code, notes, and snippets.

@lukasgraf
Created March 11, 2016 18:48
Show Gist options
  • Save lukasgraf/ffe5c41d2dcfe25bfa11 to your computer and use it in GitHub Desktop.
Save lukasgraf/ffe5c41d2dcfe25bfa11 to your computer and use it in GitHub Desktop.
Logging Demo
from log import setup_logger
class Communicator(object):
def __init__(self, logger=None):
if logger is None:
logger = setup_logger(__name__)
self.log = logger
def send(self, data):
self.log.info('Sending %s bytes of data' % len(data))
"""
Helper module to factor out setting up the logger and attaching a FileHandler.
"""
from logging import FileHandler
import logging
def setup_logger(name):
logger = logging.getLogger(name)
handler = FileHandler('%s.log' % name)
logger.addHandler(handler)
return logger
from svc_anonymous import func
from svc_bar import bar
from svc_foo import foo
import logging
# Add a StreamHandler for the root logger, so we get some console output in
# addition to file logging (for easy of testing). Also set the level for
# the root level to INFO so our messages don't get filtered.
logging.basicConfig(level=logging.INFO)
foo()
bar()
func()
from com import Communicator
def func():
# No logger being passed in
c = Communicator()
c.send('anonymous')
from com import Communicator
from log import setup_logger
logger = setup_logger(__name__)
def bar():
c = Communicator(logger)
c.send('bar')
from com import Communicator
from log import setup_logger
logger = setup_logger(__name__)
def foo():
c = Communicator(logger)
c.send('foo')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment