Package: logpie
logpieA versatile logging framework.Simple, efficient, and configurable logging framework to manage and streamline your application logs.Installation:python -m pip install [--upgrade] logpieKey Features:Supports both file-based and console logging.Allows chronological organization of log files by year and month.Automatic log file cycling based on file size.Thread-safe operations for reliable logging.Customize your logs with configurable formatters.Can prefix log files with dates for easy tracking.Usage:# -*- coding: UTF-8 -*-fromlogpieimportLoggerlog=Logger("my_logger")if__name__=='__main__':log.debug("Testing debug messages...")log.info("Testing info messages...")log.warning("Testing warning messages...")log.error("Testing error messages...")log.critical("Testing critical messages...")Components:classlogpie.LoggerParameters:ParameterTypeDefaultDescriptionnamestrlogpieThe name of the logger. The name of the logger cannot be changed after instantiation!levelLevelNOTSETThe severity level for this logger.handlersHandlerStreamHandlerA handler or a tuple of handlers for this logger.Methods:nameA property that returns the name of the logger.NOTE:Cannot be changed after instantiation!levelA property that returns the severity level used by the logger.level.setterSets the attributelevelof the logger tovalue.
All other messages with severity level less than thisvaluewill be ignored.
By default, the logger is instantiated with severity levelNOTSET(0) and therefore all messages are logged.Available levels:DEBUGINFOWARNINGERRORCRITICALhandlersA property that returns the handlers used by the logger.handlers.setterSets the logging handlers for the logger.Available handlers:StreamHandlerFileHandleradd_handler(value: Handler)Add a handler to the logger.remove_handler(value: Handler)Remove a handler from the logger.has_handlersCheck if the logger instance has any handlers.close()Close the handlers of the logger and release the resources.debug(msg: str, *args, **kwargs)Log amsg % argswith levelDEBUG.
To add exception info to the message use theexc_infokeyword argument with a True value.Example:log.debug("Testing '%s' messages!","DEBUG",exc_info=True)orlog.debug("Testing '%(level)s' messages!",{"level":"DEBUG"},exc_info=True)info(msg: str, *args, **kwargs)Log amsg % argswith levelINFO.
To add exception info to the message use theexc_infokeyword argument with a True value.Example:log.info("Testing '%s' messages!","INFO",exc_info=True)orlog.info("Testing '%(level)s' messages!",{"level":"INFO"},exc_info=True)warning(msg: str, *args, **kwargs)Log amsg % argswith levelWARNING.
To add exception info to the message use theexc_infokeyword argument with a True value.Example:log.warning("Testing '%s' messages!","WARNING",exc_info=True)orlog.warning("Testing '%(level)s' messages!",{"level":"WARNING"},exc_info=True)error(msg: str, *args, **kwargs)Log amsg % argswith levelERROR.
To add exception info to the message use theexc_infokeyword argument with a True value.Example:try:raiseTypeError("Type error occurred!")exceptTypeError:log.error("Action failed!",exc_info=True)ortry:raiseTypeError("Type error occurred!")exceptTypeErrorastype_error:log.error("Action failed!",exc_info=type_error)critical(msg: str, *args, **kwargs)Log amsg % argswith levelCRITICAL.
To add exception info to the message use theexc_infokeyword argument with a True value.Example:try:raiseTypeError("Critical error occurred!")exceptTypeError:log.critical("Action failed!",exc_info=True)ortry:raiseTypeError("Critical error occurred!")exceptTypeErrorascritical_error:log.critical("Action failed!",exc_info=critical_error)Handlers:By default, the logger streams all messages to the console outputsys.stdoutusing theStreamHandler()handler.
To log messages into a file we must use theFileHandler()handler.To use a different handler or more:fromlogpieimportLogger,StreamHandler,FileHandlerconsole=StreamHandler()file=FileHandler("my_log_file.log")log=Logger("my_logger",handlers=(console,file))if__name__=='__main__':log.debug("Logging debug messages!")classlogpie.StreamHandlerParameters:ParameterTypeDefaultDescriptionformatterFormatterNoneFormatter object used to format the log messages.handleTextIONoneThe handle used to output the messages to the console.Methods:handleA property that returns the handle in use.handle.setterSet the handle used by the handler.emit(row: Row)Emit a log row.
This method acquires the thread lock and passes the log row formatted as
a string to thewrite()method.write(message: str)Write the logmessageusing the givenhandle.classlogpie.FileHandlerParameters:ParameterTypeDefaultDescriptionfilenamestrNoneName of the file to write logs into.modestraMode of file opening:afor appending andwfor truncating the file.encodingstrUTF-8Encoding of the file.max_sizeint(1024 ** 2) * 4(4 MB)Maximum size of the log file, in bytes. Ifcycleis enabled, when the file reaches the maximum size, the handler will switch to another file by incrementing the index with1.cycleboolFalseWhether to cycle files when maximum size is reached. When the file reaches the maximum size, the handler will switch to another file by incrementing the index with1.chronologicalboolFalseWhether to sort files chronologically.date_prefixboolFalseWhether to add date prefix to filename.date_awareboolFalseWhether to use date awareness to the log file. Ifdate_prefixis enabled this will enforce the current date to be used rather than the date when the handler was created.formatterFormatterNoneFormatter object to format the logs.Whenchronologicalis enabled, the folder tree is by default structured as follows:.
└─logs
    └─year (ex: 2022)
        └─month (ex: january)
            ├─2022-08-01_logpie.1.log
            ├─2022-08-01_logpie.2.log
            └─2022-08-01_logpie.3.logMethods:emit(row: Row)Emit a log row.
This method acquires the thread lock and passes the logrowformatted as
a string to thewrite()method.write(message: str)Write a logmessageinto the file.classlogpie.FormatterThe log rows are formatted with the help of theFormatterclass.Example:fromlogpieimportLogger,FileHandler,Formatter# here we're also adding a new field (e.g. 'ip') used by the 'extra' keyword arguments.my_formatter=Formatter(row="${timestamp}- ${ip}- ${level}- ${source}: ${message}",timestamp="[%Y-%m-%d%H:%M:%S.%f]",stack="<${file}, ${line}, ${code}>",)my_handler=FileHandler("my_log_file.log",formatter=my_formatter)log=Logger("my_logger",handlers=my_handler)if__name__=='__main__':# here we are passing the 'ip' keyword argument for the 'extra' fieldlog.debug("Testing 'DEBUG' messages!",ip="192.168.1.100")Parameters:ParameterTypeDefaultDescriptionrowstr'${timestamp} - ${level} - ${source}: ${message}'The row formatting template. This template uses thestring.Templatestyle with placeholders (e.g.${field}).timestr'[%Y-%m-%d %H:%M:%S.%f]'The timestamp formatting template. This template uses thedatetime.strftime()style (e.g.%Y-%m-%d %H:%M:%S.%f).stackstr'<${file}, ${line}, ${code}>'The stack info formatting template. This template uses thestring.Templatestyle with placeholders (e.g.${field}).Methods:as_string(row: Row)Format a given row into a string based on predefined templates.