Logging convenience routines.
Project description
Logging convenience routines.
The logging package is very useful, but a little painful to use. This package provides low impact logging setup and some extremely useful if unconventional context hooks for logging.
The default logging verbosity output format has different defaults based on whether an output log file is a tty and whether the environment variable $DEBUG is set, and to what.
On terminals warnings and errors get ANSI colouring.
A mode is available that uses cs.upd.
Some examples:
Program initialisation::
from cs.logutils import setup_logging
def main(argv):
cmd = os.path.basename(argv.pop(0))
setup_logging(cmd)
Basic logging from anywhere::
from cs.logutils import info, warning, error
[...]
def some_function(...):
[...]
error("nastiness found! bad value=%r", bad_value)
Function add_logfile(filename, logger=None, mode='a', encoding=None, delay=False, format=None, no_prefix=False)
Add a FileHandler logging to the specified filename;
return the chosen logger and the new handler.
Parameters:
logger: if supplied and not None, add the FileHandler to that Logger, otherwise to the root Logger. Ifloggeris a string, calllogging.getLogger(logger)to obtain the logger.mode,encodinganddelay: passed to the logging.FileHandler initialiser.format: used to override the handler's default format.no_prefix: if true, do not put the Pfx context onto the front of the message.
Function critical(msg, *args, **kwargs)
Emit a log at logging.CRITICAL level with the current Pfx prefix.
Function D(msg, *args)
Print formatted debug string straight to sys.stderr if D_mode is true, bypassing the logging modules entirely. A quick'n'dirty debug tool.
Function debug(msg, *args, **kwargs)
Emit a log at logging.DEBUG level with the current Pfx prefix.
Function error(msg, *args, **kwargs)
Emit a log at logging.ERROR level with the current Pfx prefix.
Function exception(msg, *args)
Emit an exception log with the current Pfx prefix.
Function ftrace(func)
Decorator to trace a function if module.DEBUG is true.
Function ifdebug()
Test the logging_level against logging.DEBUG.
Function infer_logging_level(env_debug=None, environ=None, verbose=None)
Infer a logging level from the env_debug, which by default
comes from the environment variable $DEBUG.
Usually default to logging.WARNING, but if sys.stderr is a terminal, default to logging.INFO.
Parse the environment variable $DEBUG as a comma separated list of flags.
Examine the in sequence flags to affect the logging level:
numeric < 1:logging.WARNINGnumeric >= 1 and < 2:logging.INFOnumeric >= 2:logging.DEBUG"DEBUG":logging.DEBUG"INFO":logging.INFO"WARNING":logging.WARNING"ERROR":logging.ERROR
Return an object with the following attributes:
.level: A logging level..flags: All the words from $DEBUG as separated by commas and uppercased..module_names: Module names to be debugged..function_names: Functions to be traced in the for "module_name.func_name()".
Function info(msg, *args, **kwargs)
Emit a log at logging.INFO level with the current Pfx prefix.
Function log(level, msg, *args, **kwargs)
Emit a log at the specified level with the current Pfx prefix.
Function logException(exc_type, exc_value, exc_tb)
Replacement for sys.excepthook that reports via the cs.logutils logging wrappers.
Class LogTime
LogTime is a content manager that logs the elapsed time of the enclosed code. After the run, the field .elapsed contains the elapsed time in seconds.
Function logTo(filename, logger=None, mode='a', encoding=None, delay=False, format=None, no_prefix=False)
Add a FileHandler logging to the specified filename;
return the chosen logger and the new handler.
Parameters:
logger: if supplied and not None, add the FileHandler to that Logger, otherwise to the root Logger. Ifloggeris a string, calllogging.getLogger(logger)to obtain the logger.mode,encodinganddelay: passed to the logging.FileHandler initialiser.format: used to override the handler's default format.no_prefix: if true, do not put the Pfx context onto the front of the message.
Class NullHandler
MRO: logging.Handler, logging.Filterer
A Handler which discards its requests.
Function OBSOLETE(func)
Decorator for obsolete functions.
Use:
@OBSOLETE
def f(...):
This emits a warning log message before calling the decorated function.
Class PfxFormatter
MRO: logging.Formatter
A Formatter subclass that has access to the program's cmd and Pfx state.
Function setup_logging(cmd_name=None, main_log=None, format=None, level=None, flags=None, upd_mode=None, ansi_mode=None, trace_mode=None, module_names=None, function_names=None, verbose=None)
Arrange basic logging setup for conventional UNIX command line error messaging; return an object with informative attributes.
Parameters:
cmd_name: program name, default frombasename(sys.argv[0]). Side-effect: setscs.pfx.cmdto this value.main_log: default logging system. If None, the main log will go to sys.stderr; ifmain_logis a string, is it used as a filename to open in append mode; otherwise main_log should be a stream suitable for use withlogging.StreamHandler(). The resulting log handler is added to theloggingroot logger.format: the message format formain_log. IfNone, useDEFAULT_PFX_FORMAT_TTYwhenmain_logis a tty or FIFO, otherwiseDEFAULT_PFX_FORMAT.level:main_loglogging level. If None, infer a level from the environment usinginfer_logging_level().flags: a string containing debugging flags separated by commas. IfNone, infer the flags from the environment usinginfer_logging_level(). The following flags have meaning:D: set cs.logutils.D_mode to True;TDUMP: attach a signal handler to SIGHUP to do a thread stack dump;TRACE: enable various noisy tracing facilities;UPD,NOUPD: set the default forupd_modeto True or False respectively.upd_mode: a Boolean to activate cs.upd as themain_logmethod; ifNone, set it toTrueifflagscontains 'UPD', otherwise toFalseifflagscontains 'NOUPD', otherwise set it toFalse(was from main_log.isatty()). A true value causes the root logger to usecs.updfor logging.ansi_mode: ifNone, set it frommain_log.isatty(). A true value causes the root logger to colour certain logging levels using ANSI terminal sequences (currently only ifcs.updis used).trace_mode: ifNone, set it according to the presence of 'TRACE' in flags. Otherwise iftrace_modeis true, set the globaltrace_leveltologging_level; otherwise it defaults tologging.DEBUG.verbose: ifNone, then if stderr is a tty then the log level isINFOotherwiseWARNING. Otherwise, ifverboseis true then the log level isINFOotherwiseWARNING.
Function status(msg, *args, **kwargs)
Write a message to the terminal's status line.
Parameters:
msg: message stringargs: if not empty, the message is %-formatted withargsfile: optional keyword argument specifying the output file. Default:sys.stderr.
Hack: if there is no status line use the xterm title bar sequence :-(
Function trace(msg, *args, **kwargs)
Emit a log message at trace_level with the current Pfx prefix.
Function upd(msg, *args)
If we're using an UpdHandler, update the status line otherwise write an info message.
Class UpdHandler
MRO: logging.StreamHandler, logging.Handler, logging.Filterer
A StreamHandler subclass whose .emit method
uses a cs.upd.Upd for transcription.
Function warning(msg, *args, **kwargs)
Emit a log at logging.WARNING level with the current Pfx prefix.
Function with_log(filename, **kw)
Context manager to add a Logger to the output logs temporarily.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
File details
Details for the file cs.logutils-20190220.tar.gz.
File metadata
- Download URL: cs.logutils-20190220.tar.gz
- Upload date:
- Size: 9.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/1.11.0 pkginfo/1.4.2 requests/2.18.4 setuptools/40.0.0 requests-toolbelt/0.8.0 tqdm/4.23.0 CPython/3.6.8
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6775d5cb43019fcaba94e223942252ec7ceed784fa7f3f1008bc496b9b04f486
|
|
| MD5 |
e5c25c4803f576cfad63d5f938565f04
|
|
| BLAKE2b-256 |
7b89d38a23d316dbafe3640cdf6e226aeb301a2b4045be0005146c905d579231
|