Lggr - Python Logging For Humans
Have you ever tried to do anything with the python logging module?
I have. I didn't like it at all. The API was very confusing. Instead of dealing with all of its intricacies, I decided to roll my own.
I've been inspired by dabeaz's presentation on coroutines and Kenneth Reitz's presentation on better python libraries.
Install
pip install lggr
How does it work?
Create a logger object.
import lggr
mylggr = lggr.Lggr()
Add a coroutine (or any function or object with send
and close
methods) to consume log messages. lggr
includes some default ones:
lggr.Printer()
writes to stdoutlggr.StderrPrinter()
writes to stderrlggr.Printer(filepath)
opens a file atfilepath
and writes to that.lggr.SocketWriter(host, port)
writes to a network socketlggr.Emailer(recipients)
sends emailslggr.GMailer(recipients, gmail_username, gmail_password, subject="optional")
also sends emails, but does it from Gmail which is way sexier than doing it from your own server.
You can choose to add different coroutines to different levels of logging. Maybe you want to receive emails for all of your critical messages, but only print to stderr for everything else.
mylggr.add(mylggr.ALL, lggr.Printer()) # mylggr.ALL is a shortcut to add a coroutine to all levels
mylggr.add(mylggr.CRITICAL, lggr.Emailer("[email protected]"))
Do some logging.
mylggr.info("Hello, world!")
mylggr.warning("Something seems to have gone {desc}", {"desc":"amuck!"})
mylggr.critical("Someone {} us {} the {}!", "set", "up", "bomb")
mylggr.close() # stop logging
What kind of information can I log?
Anything you want. Log messages are created using str.format
, so you can really create anything you want. The default format includes access to the following variables:
asctime
= time as a string (fromtime.asctime()
)code
= the exact code that called the logging functioncodecontext
= surrounding 10 lines surroundingcode
defaultfmt
= the default format of a log messageexcinfo
= execution information, either passed in orsys.info()
filename
= filename the logging function was called from (test.py
)funcname
= the function namelevelname
= level of logging as a string ("INFO"
)levelno
= level of logging as an integer (0
)lineno
= the line numberlogmessage
= the user's formatted messagemessagefmt
= the format string to be used to create the log messagemodule
= module the logging function was called from (in this case,None
)pathname
= path to the file that the logging function was called from (~/test.py
)process
= current process idprocessname
= name of the current process, ifmultiprocessing
is availablestackinfo
= stack information, created if the optionalinc_stackinfo
argument isTrue
(it defaults toFalse
if not explicitly passed) or the logging function is called with instance functionscritical
,debug
, orerror
.threadid
= the thread id, if thethreading
module is availablethreadname
= the thread name, if thethreading
module is availabletime
= time as seconds from epoch (fromtime.time()
)
If you want to use any extra information, simply pass in a dict with the named argument extra
:
>>> mylggr.config['defaultfmt'] = '{name} sez: {logmessage}'
>>> mylggr.info("This is the {}", "message", extra={"name":"Peter"})
Peter sez: This is the message
Something to be careful about: internally, lggr uses the older (2.0+) python format
syntax to be compatible with older versions. As of 2.7, you can call '{} {} {}'.format(1, 2, 3)
,
but this will break for earlier versions. When making calls to lggr, make sure that you use the
correct syntax for your version of Python. If your program will run on multiple different versions,
then it would probably best to use the older style ('{0} {1} {2}'.format(1, 2, 3)
).
stackinfo
example
A stackinfo
is cool because it lets you do really helpful tracebacks to where exactly your logging function is being called. For example, with some Lggr mylggr, I could run the following:
mylggr.config['defaultfmt'] = '{asctime} ({levelname}) {logmessage}\nIn {pathname}, line {lineno}:\n{codecontext}'
def outer(a):
def inner(b):
def final(c):
mylggr.critical("Easy as {}, {}, {}!", a, b, c)
return final
return inner
outer(1)(2)(3)
output:
Sun Nov 11 14:43:38 2012 (CRITICAL) Easy as a, b, c!
In bin/test.py, line 29:
| old = mylggr.config['defaultfmt']
| mylggr.config['defaultfmt'] = '{asctime} ({levelname}) {logmessage}\nIn {pathname}, line {lineno}:\n{codecontext}'
| def outer(a):
| def inner(b):
| def final(c):
> mylggr.critical("Easy as {}, {}, {}!", a, b, c)
| return final
| return inner
|
| outer(1)(2)(3)
Is it robust?
Not yet. It's definitely still in the early days, so use at your own risk. I wouldn't put this into production right now, but it's been working fine for my toy projects. Please submit any bugs you find to the github tracker!
Also, for the risk-averse, it ignores all errors when calling the .log(...)
method. So if you seriously mess up, the worst thing that can happen is that you won't see a log message. For the less risk-averse, this can be overridden when the Lggr
object is created.
What's next?
I'm still working on text-sending and IRC/IM-writing log functions - maybe one of you could help?
Also, I've sort of ignored the Unicode problem entirely. That needs to change.
I'd also like to add serialization / loading of both Lggr
objects and their configurations, for easier saving / loading.