Welcome to pysimplelog V. 4.0.0 documentation!¶
This is a pythonic simple yet complete system logger. It allows logging simultaneously to two streams, the first one is the system standard output by default and the second one is designated to be set to a file. In addition, pysimplelog is text colouring and attributes enabled when the stream allows it.
Installation guide:¶
pysimplelog is a pure python 2.7.x module that needs no particular installation. One can either fork pysimplelog’s github repository and copy the package to python’s site-packages or use pip as the following:
pip install pysimplelog
-
pysimplelog.
get_version
()¶ Get pysimplelog’s version number.
Get pysimplelog’s author’s name.
-
pysimplelog.
get_email
()¶ Get pysimplelog’s author’s email.
-
pysimplelog.
get_doc
()¶ Get pysimplelog’s official online documentation link.
-
pysimplelog.
get_repository
()¶ Get pysimplelog’s official online repository link.
-
pysimplelog.
get_pypi
()¶ Get pysimplelog pypi’s link.
Usage¶
# import python 2.7.x 3.x.y compatible print function from __future__ import print_function # import Logger from pysimplelog import Logger # initialize l=Logger("log test") # change log file basename from simplelog to mylog l.set_log_file_basename("mylog") # change log file extension from .log to .pylog l.set_log_file_extension("pylog") # Add new log types. l.add_log_type("super critical", name="SUPER CRITICAL", level=200, color='red', attributes=["bold","underline"]) l.add_log_type("wrong", name="info", color='magenta', attributes=["strike through"]) l.add_log_type("important", name="info", color='black', highlight="orange", attributes=["bold"]) # update error log type l.update_log_type(logType='error', color='pink', attributes=['underline','bold']) # print logger print(l, end="\n\n") # test logging l.info("I am info, called using my shortcut method.") l.log("info", "I am info, called using log method.") l.warn("I am warn, called using my shortcut method.") l.log("warn", "I am warn, called using log method.") l.error("I am error, called using my shortcut method.") l.log("error", "I am error, called using log method.") l.critical("I am critical, called using my shortcut method.") l.log("critical", "I am critical, called using log method.") l.debug("I am debug, called using my shortcut method.") l.log("debug", "I am debug, called using log method.") l.log("super critical", "I am super critical, called using log method because I have no shortcut method.") l.log("wrong", "I am wrong, called using log method because I have no shortcut method.") l.log("important", "I am important, called using log method because I have no shortcut method.") # print last logged messages print("") print("Last logged messages are:") print("=========================") print(l.lastLoggedMessage) print(l.lastLoggedDebug) print(l.lastLoggedInfo) print(l.lastLoggedWarning) print(l.lastLoggedError) print(l.lastLoggedCritical) # log data print("") print("Log random data and traceback stack:") print("====================================") l.info("Check out this data", data=list(range(10))) print("") # log error with traceback import traceback try: 1/range(10) except Exception as err: l.error('%s (is this python ?)'%err, tback=traceback.extract_stack())
output¶
Logger (Version 4.0.0) log type |log name |level |std flag |file flag | ---------------|---------------|----------|----------|----------| wrong |info |0.0 |True |True | debug |DEBUG |0.0 |True |True | important |info |0.0 |True |True | info |INFO |10.0 |True |True | warn |WARNING |20.0 |True |True | error |ERROR |30.0 |True |True | critical |CRITICAL |100.0 |True |True | super critical |SUPER CRITICAL |200.0 |True |True | 2018-09-07 16:07:58 - log test <INFO> I am info, called using my shortcut method. 2018-09-07 16:07:58 - log test <INFO> I am info, called using log method. 2018-09-07 16:07:58 - log test <WARNING> I am warn, called using my shortcut method. 2018-09-07 16:07:58 - log test <WARNING> I am warn, called using log method. 2018-09-07 16:07:58 - log test <ERROR> I am error, called using my shortcut method. 2018-09-07 16:07:58 - log test <ERROR> I am error, called using log method. 2018-09-07 16:07:58 - log test <CRITICAL> I am critical, called using my shortcut method. 2018-09-07 16:07:58 - log test <CRITICAL> I critical, called using log method. 2018-09-07 16:07:58 - log test <DEBUG> I am debug, called using my shortcut method. 2018-09-07 16:07:58 - log test <DEBUG> I am debug, called using log method. 2018-09-07 16:07:58 - log test <SUPER CRITICAL> I am super critical, called using log method because I have no shortcut method.2018-09-07 16:07:58 - log test <info> I am wrong, called using log method because I have no shortcut method.2015-11-18 14:25:08 - log test <info> I am important, called using log method because I have no shortcut method. Last logged messages are: ========================= I am important, called using log method because I have no shortcut method. I am debug, called using log method. I am info, called using log method. I am warn, called using log method. I am error, called using log method. I am critical, called using log method. Log random data and traceback stack: ==================================== 2018-09-07 16:07:58 - log testCheck out this data [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 2015-11-18 14:25:08 - log test <ERROR> unsupported operand type(s) for /: 'int' and 'list' (is this python ?) File "<stdin>", line 4, in <module>
-
class
pysimplelog.SimpleLog.
Logger
(name='logger', flush=True, logToStdout=True, stdout=None, logToFile=True, logFile=None, logFileBasename='simplelog', logFileExtension='log', logFileMaxSize=10, logFileFirstNumber=0, logFileRoll=None, stdoutMinLevel=None, stdoutMaxLevel=None, fileMinLevel=None, fileMaxLevel=None, logTypes=None, timezone=None, *args, **kwargs) This is simplelog main Logger class definition.
A logging is constituted of a header a message and a footer. In the current implementation the footer is empty and the header is as the following:
date time - loggerName <logTypeName>
In order to change any of the header or the footer, ‘_get_header’ and ‘_get_footer’ methods must be overloaded.
When used in a python application, it is advisable to use Logger singleton implementation and not Logger itself. if no overloading is needed one can simply import the singleton as the following:
from pysimplelog import SingleLogger as Logger
A new Logger instanciates with the following logType list (logTypes <NAME>: level)
debug <DEBUG>: 0
info <INFO>: 10
warn <WARNING>: 20
error <ERROR>: 30
critical <CRITICAL>: 100
Recommended overloading implementation, this is how it could be done:
from pysimplelog import SingleLogger as LOG class Logger(LOG): # *args and **kwargs can be replace by fixed arguments def custom_init(self, *args, **kwargs): # hereinafter any further instanciation can be coded
In case overloading __init__ is needed, this is how it could be done:
from pysimplelog import SingleLogger as LOG class Logger(LOG): # custom_init will still be called in super(Logger, self).__init__(*args, **kwargs) def __init__(self, *args, **kwargs): if self._isInitialized: return super(Logger, self).__init__(*args, **kwargs) # hereinafter any further instanciation can be coded
- Parameters
name (string): The logger name.
flush (boolean): Whether to always flush the logging streams.
logToStdout (boolean): Whether to log to the standard output stream.
stdout (None, stream): The standard output stream. If None, system standard output will be set automatically. Otherwise any stream with read and write methods can be passed
logToFile (boolean): Whether to log to to file.
logFile (None, string): the full log file path including directory basename and extension. If this is given, all of logFileBasename and logFileExtension will be discarded. logfile is equivalent to logFileBasename.logFileExtension
logFileBasename (string): Logging file directory path and file basename. A logging file full name is set as logFileBasename.logFileExtension
logFileExtension (string): Logging file extension. A logging file full name is set as logFileBasename.logFileExtension
logFileMaxSize (None, number): The maximum size in Megabytes of a logging file. Once exceeded, another logging file as logFileBasename_N.logFileExtension will be created. Where N is an automatically incremented number. If None or a negative number is given, the logging file will grow indefinitely
logFileFirstNumber (None, integer): first log file number ‘N’ in logFileBasename_N.logFileExtension. If None is given then first log file will be logFileBasename.logFileExtension and ince logFileMaxSize is reached second log file will be logFileBasename_0.logFileExtension and so on and so forth. If number is given it must be an integer >=0
logFileRoll (None, intger): If given, it sets the maximum number of log files to write. Exceeding the number will result in deleting previous ones. This also insures always increasing files numbering.
stdoutMinLevel(None, number): The minimum logging to system standard output level. If None, standard output minimum level checking is left out.
stdoutMaxLevel(None, number): The maximum logging to system standard output level. If None, standard output maximum level checking is left out.
fileMinLevel(None, number): The minimum logging to file level. If None, file minimum level checking is left out.
fileMaxLevel(None, number): The maximum logging to file level. If None, file maximum level checking is left out.
logTypes (None, dict): Used to create and update existing log types upon initialization. Given dictionary keys are logType (new or existing) and values can be None or a dictionary of kwargs to call update_log_type upon. This argument will be called after custom_init
timezone (None, str): Logging time timezone. If provided pytz must be installed and it must be the timezone name. If not provided, the machine default timezone will be used.
- *args: This is used to send non-keyworded variable length argument
list to custom initialize. args will be parsed and used in custom_init method.
- **kwargs: This allows passing keyworded variable length of
arguments to custom_init method. kwargs can be anything other than __init__ arguments.
-
property
lastLogged
Get a dictionary of last logged messages. Keys are log types and values are the the last messages.
-
property
lastLoggedMessage
Get last logged message of any type. Retuns None if no message was logged.
-
property
lastLoggedDebug
Get last logged message of type ‘debug’. Retuns None if no message was logged.
-
property
lastLoggedInfo
Get last logged message of type ‘info’. Retuns None if no message was logged.
-
property
lastLoggedWarning
Get last logged message of type ‘warn’. Retuns None if no message was logged.
-
property
lastLoggedError
Get last logged message of type ‘error’. Retuns None if no message was logged.
-
property
lastLoggedCritical
Get last logged message of type ‘critical’. Retuns None if no message was logged.
-
property
logTypes
list of all defined log types.
-
property
logLevels
dictionary copy of all defined log types levels.
-
property
logTypeFileFlags
dictionary copy of all defined log types logging to a file flags.
-
property
logTypeStdoutFlags
dictionary copy of all defined log types logging to Standard output flags.
-
property
stdoutMinLevel
Standard output minimum logging level.
-
property
stdoutMaxLevel
Standard output maximum logging level.
-
property
fileMinLevel
file logging minimum level.
-
property
fileMaxLevel
file logging maximum level.
-
property
forcedStdoutLevels
dictionary copy of forced flags of logging to standard output.
-
property
forcedFileLevels
dictionary copy of forced flags of logging to file.
-
property
logTypeNames
dictionary copy of all defined log types logging names.
-
property
logTypeLevels
dictionary copy of all defined log types levels showing when logging.
-
property
logTypeFormats
dictionary copy of all defined log types format showing when logging.
-
property
name
logger name.
-
property
logToStdout
log to stdout flag.
-
property
logFileRoll
Log file roll parameter.
-
property
logToFile
log to file flag.
-
property
logFileName
currently used log file name.
-
property
logFileBasename
log file basename.
-
property
logFileExtension
log file extension.
-
property
logFileMaxSize
maximum allowed logfile size in megabytes.
-
property
logFileFirstNumber
log file first number
-
property
timezone
The timezone if given
-
set_timezone
(timezone) Set logging timezone
- Parameters
timezone (None, str): Logging time timezone. If provided pytz must be installed and it must be the timezone name. If not provided, the machine default timezone will be used
-
is_logType
(logType) Get whether given logType is defined or not
- Parameters
logType (string): A defined logging type.
- Result
result (boolean): Whether given logType is defined or not
-
update
(**kwargs) Update logger general parameters using key value pairs. Updatable parameters are name, flush, stdout, logToStdout, logFileRoll, logToFile, logFileMaxSize, stdoutMinLevel, stdoutMaxLevel, fileMinLevel, fileMaxLevel and logFileFirstNumber.
-
property
parameters
get a dictionary of logger general parameters. The same dictionary can be used to update another logger instance using update method
-
custom_init
(*args, **kwargs) Custom initialize abstract method. This method will be called at the end of initialzation. This method needs to be overloaded to custom initialize Logger instances.
- Parameters
*args (): This is used to send non-keyworded variable length argument list to custom initialize.
**kwargs (): This is keyworded variable length of arguments. kwargs can be anything other than __init__ arguments.
-
set_name
(name) Set the logger name.
- Parameters
name (string): The logger name.
-
set_flush
(flush) Set the logger flush flag.
- Parameters
flush (boolean): Whether to always flush the logging streams.
-
set_stdout
(stream=None) Set the logger standard output stream.
- Parameters
stdout (None, stream): The standard output stream. If None, system standard output will be set automatically. Otherwise any stream with read and write methods can be passed
-
set_log_to_stdout_flag
(logToStdout) Set the logging to the defined standard output flag. When set to False, no logging to standard output will happen regardless of a logType standard output flag.
- Parameters
logToStdout (boolean): Whether to log to the standard output stream.
-
set_log_to_file_flag
(logToFile) Set the logging to a file general flag. When set to False, no logging to file will happen regardless of a logType file flag.
- Parameters
logToFile (boolean): Whether to log to to file.
-
set_log_type_flags
(logType, stdoutFlag, fileFlag) Set a defined log type flags.
- Parameters
logType (string): A defined logging type.
stdoutFlag (boolean): Whether to log to the standard output stream.
fileFlag (boolean): Whether to log to to file.
-
set_log_file_roll
(logFileRoll) Set roll parameter to determine the maximum number of log files allowed. Beyond the maximum, older will be removed.
- Parameters
logFileRoll (None, intger): If given, it sets the maximum number of log files to write. Exceeding the number will result in deleting older files. This also insures always increasing files numbering. Log files will be identified in increasing N order of logFileBasename_N.logFileExtension pattern. Be careful setting this parameter as old log files will be permanently deleted if the number of files exceeds the value of logFileRoll
-
set_log_file
(logfile) Set the log file full path including directory path basename and extension.
- Parameters
logFile (string): the full log file path including basename and extension. If this is given, all of logFileBasename and logFileExtension will be discarded. logfile is equivalent to logFileBasename.logFileExtension
-
set_log_file_extension
(logFileExtension) Set the log file extension.
- Parameters
logFileExtension (string): Logging file extension. A logging file full name is set as logFileBasename.logFileExtension
-
set_log_file_basename
(logFileBasename) Set the log file basename.
- Parameters
logFileBasename (string): Logging file directory path and file basename. A logging file full name is set as logFileBasename.logFileExtension
-
set_log_file_maximum_size
(logFileMaxSize) Set the log file maximum size in megabytes
- Parameters
logFileMaxSize (None, number): The maximum size in Megabytes of a logging file. Once exceeded, another logging file as logFileBasename_N.logFileExtension will be created. Where N is an automatically incremented number. If None or a negative number is given, the logging file will grow indefinitely
-
set_log_file_first_number
(logFileFirstNumber) Set log file first number
- Parameters
logFileFirstNumber (None, integer): first log file number ‘N’ in logFileBasename_N.logFileExtension. If None is given then first log file will be logFileBasename.logFileExtension and ince logFileMaxSize is reached second log file will be logFileBasename_0.logFileExtension and so on and so forth. If number is given it must be an integer >=0
-
set_minimum_level
(level=0, stdoutFlag=True, fileFlag=True) Set the minimum logging level. All levels below the minimum will be ignored at logging.
- Parameters
level (None, number, str): The minimum level of logging. If None, minimum level checking is left out. If str, it must be a defined logtype and therefore the minimum level would be the level of this logtype.
stdoutFlag (boolean): Whether to apply this minimum level to standard output logging.
fileFlag (boolean): Whether to apply this minimum level to file logging.
-
set_maximum_level
(level=0, stdoutFlag=True, fileFlag=True) Set the maximum logging level. All levels above the maximum will be ignored at logging.
- Parameters
level (None, number, str): The maximum level of logging. If None, maximum level checking is left out. If str, it must be a defined logtype and therefore the maximum level would be the level of this logtype.
stdoutFlag (boolean): Whether to apply this maximum level to standard output logging.
fileFlag (boolean): Whether to apply this maximum level to file logging.
-
force_log_type_stdout_flag
(logType, flag) Force a logtype standard output logging flag despite minimum and maximum logging level boundaries.
- Parameters
logType (string): A defined logging type.
flag (None boolean): The standard output logging flag. If None, logtype existing forced flag is released.
-
force_log_type_file_flag
(logType, flag) Force a logtype file logging flag despite minimum and maximum logging level boundaries.
- Parameters
logType (string): A defined logging type.
flag (None, boolean): The file logging flag. If None, logtype existing forced flag is released.
-
force_log_type_flags
(logType, stdoutFlag, fileFlag) Force a logtype logging flags.
- Parameters
logType (string): A defined logging type.
stdoutFlag (None, boolean): The standard output logging flag. If None, logtype stdoutFlag forcing is released.
fileFlag (None, boolean): The file logging flag. If None, logtype fileFlag forcing is released.
-
set_log_type_name
(logType, name) Set a logtype name.
- Parameters
logType (string): A defined logging type.
name (string): The logtype new name.
-
set_log_type_level
(logType, level) Set a logtype logging level.
- Parameters
logType (string): A defined logging type.
level (number): The level of logging.
-
remove_log_type
(logType, _assert=False) Remove a logtype.
- Parameters
logType (string): The logtype.
_assert (boolean): Raise an assertion error if logType is not defined.
-
add_log_type
(logType, name=None, level=0, stdoutFlag=None, fileFlag=None, color=None, highlight=None, attributes=None) Add a new logtype.
- Parameters
logType (string): The logtype.
name (None, string): The logtype name. If None, name will be set to logtype.
level (number): The level of logging.
stdoutFlag (None, boolean): Force standard output logging flag. If None, flag will be set according to minimum and maximum levels.
fileFlag (None, boolean): Force file logging flag. If None, flag will be set according to minimum and maximum levels.
color (None, string): The logging text color. The defined colors are:
black , red , green , orange , blue , magenta , cyan , grey , dark grey , light red , light green , yellow , light blue , pink , light cyan
highlight (None, string): The logging text highlight color. The defined highlights are:
black , red , green , orange , blue , magenta , cyan , grey
attributes (None, string): The logging text attribute. The defined attributes are:
bold , underline , blink , invisible , strike through
N.B logging color, highlight and attributes are not allowed on all types of streams.
-
update_log_type
(logType, name=None, level=None, stdoutFlag=None, fileFlag=None, color=None, highlight=None, attributes=None) update a logtype.
- Parameters
logType (string): The logtype.
name (None, string): The logtype name. If None, name will be set to logtype.
level (number): The level of logging.
stdoutFlag (None, boolean): Force standard output logging flag. If None, flag will be set according to minimum and maximum levels.
fileFlag (None, boolean): Force file logging flag. If None, flag will be set according to minimum and maximum levels.
color (None, string): The logging text color. The defined colors are:
black , red , green , orange , blue , magenta , cyan , grey , dark grey , light red , light green , yellow , light blue , pink , light cyan
highlight (None, string): The logging text highlight color. The defined highlights are:
black , red , green , orange , blue , magenta , cyan , grey
attributes (None, string): The logging text attribute. The defined attributes are:
bold , underline , blink , invisible , strike through
N.B logging color, highlight and attributes are not allowed on all types of streams.
-
is_enabled_for_stdout
(logType) Get whether given logtype is enabled for standard output logging. When a logType is not enabled, calling for log will return without logging. This method will check general standard output logging flag and given logType standard output flag. For a logType to log it must have both flags set to True
- Parameters
logType (string): A defined logging type.
- Returns
enabled (bool): whehter enabled or not.
-
is_enabled_for_file
(logType) Get whether given logtype is enabled for file logging. When a logType is not enabled, calling for log will return without logging. This method will check general file logging flag and given logType file flag. For a logType to log it must have both flags set to True
- Parameters
logType (string): A defined logging type.
- Returns
enabled (bool): whehter enabled or not.
-
log
(logType, message, data=None, tback=None) log a message of a certain logtype.
- Parameters
logType (string): A defined logging type.
message (string): Any message to log.
data (None, object): Any type of data to print and/or write to log file after log message
tback (None, str, list): Stack traceback to print and/or write to log file. In general, this should be traceback.extract_stack
- Returns
message (string): the logged message
-
force_log
(logType, message, data=None, tback=None, stdout=True, file=True) Force logging a message of a certain logtype whether logtype level is allowed or not.
- Parameters
logType (string): A defined logging type.
message (string): Any message to log.
tback (None, str, list): Stack traceback to print and/or write to log file. In general, this should be traceback.extract_stack
stdout (boolean): Whether to force logging to standard output.
file (boolean): Whether to force logging to file.
- Returns
message (string): the logged message
-
flush
() Flush all streams.
-
info
(message, *args, **kwargs) alias to message at information level
-
information
(message, *args, **kwargs) alias to message at information level
-
warn
(message, *args, **kwargs) alias to message at warning level
-
warning
(message, *args, **kwargs) alias to message at warning level
-
error
(message, *args, **kwargs) alias to message at error level
-
critical
(message, *args, **kwargs) alias to message at critical level
-
debug
(message, *args, **kwargs) alias to message at debug level
-
class
pysimplelog.SimpleLog.
SingleLogger
(*args, **kwargs) This is singleton implementation of Logger class.