Created
June 15, 2013 06:15
-
-
Save radix/5787124 to your computer and use it in GitHub Desktop.
coollog.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
class Logger(object): | |
def __init__(self, system): | |
self.system = system | |
def log(self, format=None, **keywords): | |
""" | |
@param **keywords: The most important stuff@ | |
@param format: If you want to specify your own format, do so. | |
@param event: If you specify an event, it will be formatted in angle | |
brackets at the beginning of the line. | |
""" | |
if format is None: | |
format = "" | |
if "event" in keywords: | |
event = keywords.pop("event") | |
format += "<%s> " % (event,) | |
format += ', '.join("{key}=%({key})s".format(key=key) | |
for key in sorted(keywords)) | |
log.msg(format=format, system=self.system, **keywords) | |
def extendSystem(self, segment): | |
return Logger(self.system + "." + segment) | |
@classmethod | |
def fromModule(klass): | |
""" | |
Use this if you don't want to have to specify system yourself. | |
""" | |
callerModule = sys._getframe(1).f_globals.get("__name__") | |
assert callerModule is not None | |
return Logger(callerModule) | |
from twisted.python import log | |
log.startLogging(sys.stdout) | |
# myapp/__init__.py | |
logger = Logger("myapp") | |
# myapp/main.py | |
# from myapp import logger | |
logger.log(event="startup") | |
# myapp/db.py | |
#from myapp import logger | |
logger = logger.extendSystem("db") | |
logger.log(event="compaction-error", user="radix", dbconn=1) | |
logger.log(format="I don't know what %(subject)s is doing with %(object)s", | |
subject=1, object=2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment