Package: herodotus-logger
HerodotusAn awesome enhanced python loggerExplore the docs »Examples·Report Bug·Request FeatureTable of ContentsAbout The ProjectThe history behind the projectThe naming conventionGetting StartedInstallationUsageBasic usage (no formatter)Use with a FormatterUsing the colorizerContributingLicenseContactAbout The ProjectThe history behind the projectThe Pythonloggingpackage
is a powerful tool for logging messages to various streams,
ranging from files to third-party services likeElasticsearch.However, there was a particular instance in a project
where I needed to log messages through multiple streams
with varying levels of severity.
To illustrate, I aimed to create a logger object
equipped with three handlers:
one for a rotating file, one for standard output (stdout), and one for Elasticsearch.My objective was to route each severity level to a specific stream.
Additionally, I intended to apply colorization to
the logs displayed in stdout, while omitting colorization for logs saved in the file.When I employed code similar to the following:importloggingimportsome_colorizer_functionmy_logger=logging.getLogger("my_logger")my_logger.debug(some_colorizer_function("some message with%s"),"args")It yielded a visually appealing colorized output on stdout.
However, when directed to Elasticsearch or written to a file,
the output appeared unattractive due to the presence of ANSI color symbols.
Consequently, I embarked on refining the logging package
and subsequently contemplated making these improvements available for public use.
If you're interested, I welcome you to contribute to this endeavor.The naming conventionHerodotusstands as an ancient Greek historian acclaimed as the "Father of History."
Renowned for penning the book "The Histories,"
he holds a position among the earliest contributors
to historical literature.
This opus spans an array of topics encompassing history, geography, cultures, civilizations, and conflicts.
Notably, he adeptly merged meticulous event accounts with captivating narratives.
His opus presents a fusion of historical scrutiny and cultural storytelling,
rendering him a pivotal influencer in the evolution of historical writing.Getting StartedI've also created a pypi package for this library. So you can easily use and install it with pip or clone the project.Installationpip install herodotus_logger --upgradeUsageBasic usageTo begin, it's essential to instantiate a logger object with a designated severity level.
This configuration dictates that the logger will transmit all severities equal to
or surpassing the specified level.
Further insight into severity numbers can be foundhere.
For instance, if a logger object is established with aWARNINGlevel,
it will refrain from dispatchingINFO,DEBUG, orNOTSETlevels to its associated handlers.importloggingfromherodotusimportloggerlg=logger.Logger(name="test_logger",level=logging.WARNING)You also should give it some handlers. You have two main options to do so:Use some basic provided handlers in theherodotus.handlerswhich are starting withEnhanced*Note that all provided handlers' arguments are as the main one.
They just accept some
more arguments I'll explain.Use any custom or other handlers which are of typeHandlerin python.importloggingfromsysimportstdoutfromherodotusimportloggerfromherodotusimporthandlerslg=logger.Logger(name="test_logger",level=logging.WARNING,handlers=[handlers.EnhancedStreamHandler(stream=stdout,level=logging.WARNING),handlers.EnhancedFileHandler(filename="logs/test_logfile.log",mode="a",encoding="utf-8",level=logging.CRITICAL)])You're all set! Lean back and simply instruct your logger object to start logging!Create thelogsdirectory:mkdirlogsCall theloggerlogs functions (ex debug, info,...)lg.logger.info("Hello")However, at this juncture, no action will transpire.
This outcome arises due to the fact that the log levellgis established aslogging.WARNING, while we endeavor to
initiate logging with the info level. Evidently, the hierarchy dictates thatlog.INFOholds a lesser value thanlog.WARNING.Let's try another one:lg.logger.warning("Hello")and the bash output is:2023-08-09T10:39:05|test_logger|WARNING|HelloHowever, no logs have been recorded in the log file,
and the rationale behind this outcome is evident.Let's run another example:lg.logger.critical("Hello")and the bash output is:2023-08-09T10:45:45|test_logger|CRITICAL|HelloConsequently, the log file located atlogs/test_logfile.logmirrors the identical output.Use strict levelsWhat should we do If we want strict logging levels. I mean that
I want to log to the streamJUSTthewarninglevel and not higher (ex.error.)
It's also simple. You can usestrict_levelparameter and set itTrue:importloggingfromsysimportstdoutfromherodotusimportloggerfromherodotusimporthandlerslg=logger.Logger(name="test_logger",level=logging.WARNING,formatter=logging.Formatter(datefmt="%Y-%m-%dT%H:%M:%S",fmt="%(asctime)s%(levelname)s:%(message)s"),handlers=[handlers.EnhancedStreamHandler(stream=sys.stdout,level=logging.ERROR,strict_level=True),handlers.EnhancedFileHandler(filename="logs/test_log.log",mode="a",encoding="utf-8",level=logging.WARNING,strict_level=True)])lg.logger.error("hello, world")If you don't set thestrict_levelparameter, you will see the log message
both in the stdout and the file. But with set it toTrueyou don't see the message
in the file.Use with a FormatterI define a default formatter for the logger as follow:self.formatter=formatterorlogging.Formatter(datefmt="%Y-%m-%dT%H:%M:%S",fmt="%(asctime)s|%(name)s|%(levelname)s|%(message)s")But you can change it when you create the logger:importloggingfromsysimportstdoutfromherodotusimportloggerfromherodotusimporthandlerslg=logger.Logger(name="test_logger",level=logging.WARNING,formatter=logging.Formatter(datefmt="%Y-%m-%dT%H:%M:%S",fmt="%(asctime)s%(levelname)s:%(message)s"),handlers=[handlers.EnhancedStreamHandler(stream=stdout,level=logging.WARNING),handlers.EnhancedFileHandler(filename="logs/test_logfile.log",mode="a",encoding="utf-8",level=logging.CRITICAL)])The most important thing to note is that you can also set a different formatter for each handler.
However, if you don't specify a formatter for your handler,
the logger will fall back to using its own default formatter.importloggingfromsysimportstdoutfromherodotusimportloggerfromherodotusimporthandlerslg=logger.Logger(name="test_logger",level=logging.WARNING,formatter=logging.Formatter(datefmt="%Y-%m-%dT%H:%M:%S",fmt="%(asctime)s%(levelname)s:%(message)s"),handlers=[handlers.EnhancedStreamHandler(stream=stdout,level=logging.WARNING),handlers.EnhancedFileHandler(filename="logs/test_logfile.log",mode="a",encoding="utf-8",level=logging.CRITICAL,formatter=logging.Formatter(datefmt="%H:%M:%S",fmt="%(asctime)s:%(message)s"))])Using the colorizerIncorporating colors throughout undoubtedly provides a distinctive perspective,
and this holds true in the context of logging as well.
One approach is to leverage thecolored.
Additionally, I've included user-friendly functions that facilitate the inclusion of colors within your logs.Let's see some examples:importloggingfromsysimportstdoutfromherodotusimportloggerfromherodotusimporthandlersfromherodotus.utilsimportcolorizerlg=logger.Logger(name="test_logger",level=logging.WARNING,formatter=logging.Formatter(datefmt="%Y-%m-%dT%H:%M:%S",fmt="%(asctime)s%(levelname)s:%(message)s"),handlers=[handlers.EnhancedStreamHandler(stream=stdout,level=logging.WARNING)])lg.logger.critical(colorizer.colorize("Hello",foreground="green"))and the output will be something like this:You can also add styles (as noted in thecolored).
To do so, just pass your desired styles as a list to thecolorizefunction:lg.logger.critical(colorizer.colorize("Hello",foreground="green",styles=['bold','underline']))And the output will be something like this:But what happens if we add a file handler to a logger which uses thecolorizefunction? Let's see:importloggingfromsysimportstdoutfromherodotusimportloggerfromherodotusimporthandlersfromherodotus.utilsimportcolorizerlg=logger.Logger(name="test_logger",level=logging.WARNING,formatter=logging.Formatter(datefmt="%Y-%m-%dT%H:%M:%S",fmt="%(asctime)s%(levelname)s:%(message)s"),handlers=[handlers.EnhancedStreamHandler(stream=stdout,level=logging.WARNING),handlers.EnhancedFileHandler(filename="logs/test_logfile.log",mode="a",encoding="utf-8",level=logging.CRITICAL,formatter=logging.Formatter(datefmt="%H:%M:%S",fmt="%(asctime)s:%(message)s"))])lg.logger.critical(colorizer.colorize("Hello",foreground="green"))In the log file, you will probably see something like this (If you don't have any plugin or extension to convert ansii
chars to the colors):Finding the appearance unappealing?
Wondering what steps to take next?
No need to fret.
I've got a solution for you.You can make use of themsg_funcargument within each of theEnhanced*handlers.
This argument expects a function as its type,
so you should provide it with a suitable function.
As an illustration, I've authored adecolorizefunction
in theherodotus.utils.colorizepackage.
This function takes a string containing ANSI color codes and effectively eliminates them:handlers.EnhancedFileHandler(filename="logs/test_logfile.log",mode="a",encoding="utf-8",level=logging.CRITICAL,msg_func=colorizer.decolorize,formatter=logging.Formatter(datefmt="%H:%M:%S",fmt="%(asctime)s:%(message)s")lg.logger.critical(colorizer.colorize("Hello",foreground="green"))Finally, in the log file you will see something like this:See theopen issuesfor a full list of proposed features(
and known issues).ContributingContributions are what make the open source community such an amazing place to learn, inspire, and create. Any
contributions you make aregreatly appreciated.If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also
simply open an issue with the tag "enhancement."
Don't forget to give the project a star! Thanks again!Fork the ProjectCreate your Feature Branch (git checkout -b feature/AmazingFeature)Commit your Changes (git commit -m 'Add some AmazingFeature')Push to the Branch (git push origin feature/AmazingFeature)Open a Pull RequestLicenseDistributed under the MIT License. SeeLICENSE.txtfor more information.ContactEmad Helmi | Find me on Twitter@EmadHelmiOr send me Emails.emad.helmi@gmail.comMIT LicenseCopyright (c) [2023] [Herodotus]Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.