I found myself putting the same few lines of code at the top of every script or module that I wrote. It went something like this:
import logging MESSAGE_FORMAT = "%(asctime)s %(levelname)s:: %(message)s" DATE_FORMAT="%Y.%m.%d %T" logger = logging.getLogger(self.__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter(MESSAGE_FORMAT, DATE_FORMAT) ch = logging.StreamHandler() ch.setFormatter(formatter) logger.addHandler(ch)
Because the default simple logging provided by the standard library
logging package doesn't do everything I'd like. I prefer that messages contain the time that they were generated. I prefer that the default logging level is set to
INFO. I don't really care to see the log name in each log message.
When I built bigger applications I found myself putting this code in a
log.py file and
including it with the application source code. Then I wanted to change the log format. Which
meant editing quite a few copies of the same file. So I decided that was a bad idea and I
would turn my simple few lines of code into a Python module and publish it on PyPi.
That way I could include a single copy of the code in each of my modules or applications with
pip install command.
The last time I did some serious packaging work this all rather tricky but thanks to the most excellent work of the Python Packaging Authority publishing your own Python module is a breeze these days.
So say hello to
simple_log. It's available from PyPI now - https://pypi.python.org/pypi/simple-log/
It's designed to be a simple log module that can be incorporated in any Python application and used as simply as:
>>> from simple_log import get_log >>> log = get_log() >>> log.info('Information message') 2016.12.12 13:30:30 INFO:: Information message
No more worrying about streams and formatters just a nice simple way to get a log object and log messages from your code. The code is licensed under the MIT license so corrections, additions and praise are always welcome.