Updated files to flake8 standard
Files have been changed to ensure they abid flake8 defined rules that have not been identified as ignored. Files mostly pass flake8 rules.
This commit is contained in:
parent
c0eff133a9
commit
3fe521bcf5
|
|
@ -5,7 +5,7 @@ from typing import TextIO, Union
|
|||
from collections import namedtuple
|
||||
|
||||
from .utils import common
|
||||
from .utils.printfmt import *
|
||||
from .utils import printfmt
|
||||
|
||||
|
||||
class Logger: ... # class delcaration
|
||||
|
|
@ -61,7 +61,6 @@ class Logger: # class redeclaration & initialisation
|
|||
## create instance attribute as read-only for log location
|
||||
log = None
|
||||
|
||||
|
||||
def __new__(cls, *, out_f: str = ...) -> Logger:
|
||||
"""Construct a new instance of the class and initialise it.
|
||||
|
||||
|
|
@ -81,19 +80,18 @@ class Logger: # class redeclaration & initialisation
|
|||
## public attribute for the currect log location
|
||||
cls.log = cls.__DEFAULT_OUT_FILE = \
|
||||
os.path.realpath(out_f).strip('"')
|
||||
|
||||
|
||||
cls.__loginfo = None # default the namedtuple to None on first instance
|
||||
|
||||
cls.printLog2File("----[New instance of script has been started]----",
|
||||
file=cls.__DEFAULT_OUT_FILE, mode='w')
|
||||
|
||||
return cls.__instance__
|
||||
|
||||
return cls.__instance__
|
||||
|
||||
@classmethod
|
||||
def debug(cls, *value: object, sep: Union[str, None] = None,
|
||||
end: Union[str, None] = None, wrapping: bool = True,
|
||||
strace: bool = True) -> Logger:
|
||||
end: Union[str, None] = None, wrapping: bool = True,
|
||||
strace: bool = True) -> Logger:
|
||||
"""Pseudolog for writing to log file with level `LogLevel.DEBUG`.
|
||||
|
||||
Method is invoked on a `Logger` instance and will directly write
|
||||
|
|
@ -107,19 +105,17 @@ class Logger: # class redeclaration & initialisation
|
|||
Logger.printLog2File(*value, sep=sep, end=end,
|
||||
wrapping=wrapping, strace=strace)
|
||||
|
||||
|
||||
Logger.__stdpipe = sys.stderr
|
||||
cls.__loginfo: namedtuple = Logger.__LOG_INFO_TUPLE(
|
||||
Logger.__IS_STDERR_REDIR, LogLevel.DEBUG, value, sep, end
|
||||
Logger.__IS_STDERR_REDIR, common.LogLevel.DEBUG, value, sep, end
|
||||
)
|
||||
|
||||
return cls
|
||||
|
||||
return cls
|
||||
|
||||
@classmethod
|
||||
def warn(cls, *value: object, sep: Union[str, None] = None,
|
||||
end: Union[str, None] = None, wrapping: bool = True,
|
||||
strace: bool = True) -> Logger:
|
||||
end: Union[str, None] = None, wrapping: bool = True,
|
||||
strace: bool = True) -> Logger:
|
||||
"""Pseudolog for writing to log file with level `LogLevel.WARN`.
|
||||
|
||||
Method is invoked on a `Logger` instance and will directly write
|
||||
|
|
@ -130,21 +126,20 @@ class Logger: # class redeclaration & initialisation
|
|||
method can be invoked directly afterwards (or later) to write
|
||||
the same message to the console.
|
||||
"""
|
||||
Logger.printLog2File(*value, level=LogLevel.WARN, sep=sep,
|
||||
Logger.printLog2File(*value, level=common.LogLevel.WARN, sep=sep,
|
||||
end=end, wrapping=wrapping, strace=strace)
|
||||
|
||||
Logger.__stdpipe = sys.stderr
|
||||
cls.__loginfo: namedtuple = Logger.__LOG_INFO_TUPLE(
|
||||
Logger.__IS_STDERR_REDIR, LogLevel.WARN, value, sep, end
|
||||
Logger.__IS_STDERR_REDIR, common.LogLevel.WARN, value, sep, end
|
||||
)
|
||||
|
||||
return cls
|
||||
|
||||
return cls
|
||||
|
||||
@classmethod
|
||||
def error(cls, *value: object, sep: Union[str, None] = None,
|
||||
end: Union[str, None] = None, wrapping: bool = True,
|
||||
strace: bool = True) -> Logger:
|
||||
end: Union[str, None] = None, wrapping: bool = True,
|
||||
strace: bool = True) -> Logger:
|
||||
"""Pseudolog for writing to log file with level `LogLevel.ERROR`.
|
||||
|
||||
Method is invoked on a `Logger` instance and will directly write
|
||||
|
|
@ -155,17 +150,16 @@ class Logger: # class redeclaration & initialisation
|
|||
method can be invoked directly afterwards (or later) to write
|
||||
the same message to the console.
|
||||
"""
|
||||
Logger.printLog2File(*value, level=LogLevel.ERROR, sep=sep,
|
||||
Logger.printLog2File(*value, level=common.LogLevel.ERROR, sep=sep,
|
||||
end=end, wrapping=wrapping, strace=strace)
|
||||
|
||||
Logger.__stdpipe = sys.stderr
|
||||
cls.__loginfo: namedtuple = Logger.__LOG_INFO_TUPLE(
|
||||
Logger.__IS_STDERR_REDIR, LogLevel.ERROR, value, sep, end
|
||||
Logger.__IS_STDERR_REDIR, common.LogLevel.ERROR, value, sep, end
|
||||
)
|
||||
|
||||
return cls
|
||||
|
||||
|
||||
@staticmethod
|
||||
def withConsole() -> None:
|
||||
"""Write the last message logged to a file to the console as
|
||||
|
|
@ -181,18 +175,17 @@ class Logger: # class redeclaration & initialisation
|
|||
information regarding the formatting of the message is directly
|
||||
associated to the formatting used when writing to a log file.
|
||||
"""
|
||||
if not Logger.__loginfo is None:
|
||||
if Logger.__loginfo is not None:
|
||||
Logger.__printLog__(Logger.__loginfo.isatty,
|
||||
Logger.__loginfo.lv, Logger.__loginfo.msg,
|
||||
Logger.__loginfo.sep, Logger.__loginfo.end)
|
||||
|
||||
|
||||
@staticmethod
|
||||
def printLog2File(*value: object,
|
||||
level: Union[LogLevel, int] = LogLevel.DEBUG, mode: str = 'a',
|
||||
file: Union[TextIOWrapper, str] = ..., sep: Union[str, None] = None,
|
||||
end: Union[str, None] = None, wrapping: bool = True,
|
||||
strace: bool = True, header: bool = True) -> None:
|
||||
level: Union[common.LogLevel, int] = common.LogLevel.DEBUG,
|
||||
mode: str = 'a', file: Union[TextIOWrapper, str] = ...,
|
||||
sep: Union[str, None] = None, end: Union[str, None] = None,
|
||||
wrapping: bool = True, strace: bool = True, header: bool = True) -> None:
|
||||
"""Wrapper method over the built-in `print()` function defined
|
||||
using 3.x syntax. All Familiar functionality can be passed to
|
||||
the method as found when calling `print()`, but comes with added
|
||||
|
|
@ -241,16 +234,16 @@ class Logger: # class redeclaration & initialisation
|
|||
"""
|
||||
## handle if no file parameter was given
|
||||
if file is Ellipsis or not os.path.exists(file):
|
||||
file = Logger.__DEFAULT_OUT_FILE
|
||||
file = Logger.__DEFAULT_OUT_FILE
|
||||
|
||||
_frame = sys._getframe(2) if sys._getframe(1).f_code.co_name in \
|
||||
dir(Logger) else sys._getframe(1)
|
||||
## get the executing filename of where log was called
|
||||
_fname = _frame.f_code.co_filename.removeprefix(
|
||||
os.getcwd()).strip('\\\/')
|
||||
os.getcwd()).strip('\\/')
|
||||
## generate new header for log file and construct new message
|
||||
if header:
|
||||
msg = gen_log_header(level).format(
|
||||
msg = printfmt.gen_log_header(level).format(
|
||||
" ".join(value), CALLER="{0}:{1}[{2}]".format(
|
||||
_fname, _frame.f_code.co_name, _frame.f_lineno
|
||||
).replace("module", "global") if strace else "LOGGER"
|
||||
|
|
@ -260,9 +253,8 @@ class Logger: # class redeclaration & initialisation
|
|||
|
||||
# perform wrapping of message and indent wrapped lines
|
||||
if wrapping:
|
||||
msg = wrap(msg).replace('\n', '\n\t')
|
||||
msg = printfmt.wrap(msg).replace('\n', '\n\t')
|
||||
|
||||
|
||||
if isinstance(file, str):
|
||||
with open(file, mode, encoding="utf-8") as log:
|
||||
Logger.__stdpipe = log # pre-requisite to write PIPE to file
|
||||
|
|
@ -271,12 +263,12 @@ class Logger: # class redeclaration & initialisation
|
|||
Logger.__stdpipe = log
|
||||
Logger.__printLog__(False, level, (msg,), sep, end, False)
|
||||
|
||||
|
||||
@staticmethod
|
||||
def printLog(*value: object, level: Union[int, LogLevel] = LogLevel.NORMAL,
|
||||
sep: Union[str, None] = None, end: Union[str, None] = None,
|
||||
file: Union[TextIOWrapper, None] = None,
|
||||
flush: bool = True) -> None:
|
||||
def printLog(*value: object,
|
||||
level: Union[int, common.LogLevel] = common.LogLevel.NORMAL,
|
||||
sep: Union[str, None] = None, end: Union[str, None] = None,
|
||||
file: Union[TextIOWrapper, None] = None,
|
||||
flush: bool = True) -> None:
|
||||
"""Wrapper method over the built-in `print()` function defined
|
||||
using 3.x syntax. All Familiar functionality can be passed to
|
||||
the method as found when calling `print()`, but comes with added
|
||||
|
|
@ -320,7 +312,7 @@ class Logger: # class redeclaration & initialisation
|
|||
|
||||
## configure PIPE to STDERR if logging is high enough
|
||||
if file is None:
|
||||
if level >= LogLevel.DEBUG:
|
||||
if level >= common.LogLevel.DEBUG:
|
||||
Logger.__stdpipe = sys.stderr
|
||||
else:
|
||||
Logger.__stdpipe = sys.stdout
|
||||
|
|
@ -331,38 +323,36 @@ class Logger: # class redeclaration & initialisation
|
|||
else:
|
||||
Logger.printLog("Warning: logging function was called with a",
|
||||
"file specifier parameter which is not a valid option.",
|
||||
level=LogLevel.WARN)
|
||||
level=common.LogLevel.WARN)
|
||||
return
|
||||
|
||||
|
||||
## display message to console with appropriate colouring
|
||||
### :@NOTE: if there's a PIPE redirect, don't use colour
|
||||
### for that redirect PIPE
|
||||
|
||||
if level < LogLevel.WARN: ## handle output for STDOUT
|
||||
if level < common.LogLevel.WARN: # handle output for STDOUT
|
||||
Logger.__printLog__(Logger.__IS_STDOUT_REDIR, level, value,
|
||||
sep, end, flush)
|
||||
else: ## handle output for STDERR
|
||||
sep, end, flush)
|
||||
else: # handle output for STDERR
|
||||
Logger.__printLog__(Logger.__IS_STDERR_REDIR, level, value,
|
||||
sep, end, flush)
|
||||
|
||||
|
||||
@staticmethod
|
||||
def __printLog__(isatty: bool, lv: LogLevel, msg: object,
|
||||
s: Union[str, None] = None, e: Union[str, None] = None,
|
||||
flsh: bool = True) -> None:
|
||||
def __printLog__(isatty: bool, lv: common.LogLevel, msg: object,
|
||||
s: Union[str, None] = None, e: Union[str, None] = None,
|
||||
flsh: bool = True) -> None:
|
||||
"""Private helper method responsible for invoking the built-in
|
||||
`print` function with appropriate keyword arugments. Method
|
||||
identifies the PIPE used and provide text highlighting accordingly.
|
||||
"""
|
||||
## handle if we have a redirect
|
||||
if isatty and (Logger.__stdpipe is sys.stdout or \
|
||||
Logger.__stdpipe is sys.stderr):
|
||||
if isatty and (Logger.__stdpipe is sys.stdout
|
||||
or Logger.__stdpipe is sys.stderr):
|
||||
## write ANSI code to start coloured text
|
||||
print(log_as_col(lv), end="", file=Logger.__stdpipe, flush=flsh)
|
||||
print(printfmt.log_as_col(lv), end="", file=Logger.__stdpipe, flush=flsh)
|
||||
## unpack the object and pass to print
|
||||
print(*msg, sep=s, end="", file=Logger.__stdpipe, flush=flsh)
|
||||
## reset the colour sequence back to normal
|
||||
print(Colours.NORMAL, end=e, file=Logger.__stdpipe, flush=flsh)
|
||||
print(printfmt.Colours.NORMAL, end=e, file=Logger.__stdpipe, flush=flsh)
|
||||
else:
|
||||
print(*msg, sep=s, end=e, file=Logger.__stdpipe, flush=flsh)
|
||||
print(*msg, sep=s, end=e, file=Logger.__stdpipe, flush=flsh)
|
||||
|
|
@ -11,7 +11,7 @@ __REGEX_PAT = re.compile(r'^(.+)[\\]([^\\]+)\\*$') \
|
|||
|
||||
class LogLevel:
|
||||
"""Enumerator structure to map an integer against a log level.
|
||||
|
||||
|
||||
Higher `int` value means higher severity of level for logging.
|
||||
"""
|
||||
NORMAL = 0
|
||||
|
|
@ -20,17 +20,18 @@ class LogLevel:
|
|||
WARN = 3
|
||||
ERROR = 4
|
||||
|
||||
|
||||
def is_path_spec(path_spec: str) -> bool:
|
||||
"""Evaluate if a given string is a valid pathspec identifier.
|
||||
Pathspec evaluation is matched against the following regular
|
||||
expression patterns:
|
||||
```plaintext
|
||||
OS Pathspec
|
||||
NT: ^(.+)[\\]([^\\]+)\\*$
|
||||
Other: ^(.+)[\/]([^\/]+)$
|
||||
NT: ^(.+)[\\\\]([^\\\\]+)\\*$
|
||||
Other: ^(.+)[\\/]([^\\/]+)$
|
||||
OR
|
||||
Valid names of CWD subdirectories
|
||||
^[\w\d\-_]+$
|
||||
^[\\w\\d\\-_]+$
|
||||
```
|
||||
The following pathspecs are evaluated as valid pathspec identifiers
|
||||
(OS implicitly implied):
|
||||
|
|
@ -48,6 +49,6 @@ def is_path_spec(path_spec: str) -> bool:
|
|||
## perform a regex match to ensure that the given path is a
|
||||
## valid pathspec for the system.
|
||||
return bool(re.match(
|
||||
__REGEX_PAT, path_spec.strip(r"\"'")) or \
|
||||
re.match(r'^[\w\d\-_]+$', path_spec.strip(r"\"'"))
|
||||
__REGEX_PAT, path_spec.strip(r"\"'"))
|
||||
or re.match(r'^[\w\d\-_]+$', path_spec.strip(r"\"'"))
|
||||
)
|
||||
|
|
@ -28,8 +28,8 @@ def loglevel_as_str(level: Union[LogLevel, int]) -> str:
|
|||
"""
|
||||
## perform a lookup of each attribute of LogLevel and its associate
|
||||
## value, and search for the attribute that has the matching level
|
||||
## value passed to the function.
|
||||
_attrs = [_dir for _dir in dir(LogLevel) \
|
||||
## value passed to the function.
|
||||
_attrs = [_dir for _dir in dir(LogLevel)
|
||||
if not _dir.startswith('__')] # list of all attributes of LogLevel
|
||||
for _ in _attrs: # iterate over all attributes defined
|
||||
if getattr(LogLevel, _) == level: # if the level matches
|
||||
|
|
@ -59,6 +59,7 @@ def log_as_col(level: Union[int, LogLevel]) -> Colours:
|
|||
else:
|
||||
return Colours.NORMAL
|
||||
|
||||
|
||||
def gen_log_header(_type: Union[LogLevel, int, str]) -> str:
|
||||
"""Generate a header string for use of standardising log outputs.
|
||||
|
||||
|
|
@ -66,7 +67,7 @@ def gen_log_header(_type: Union[LogLevel, int, str]) -> str:
|
|||
```plaintext
|
||||
"[YYYY-MM-DDTHH:MM:SS+OFFSET] [{CALLER}] <LogLevel> {0}"
|
||||
```
|
||||
|
||||
|
||||
The first column defines the Date-Time following the ISO 8601 (long)
|
||||
standard timestamp format, whereby `T` is the separator between Date
|
||||
and Time. The `+OFFSET` is the number of hours ahead/behind UTC, the
|
||||
|
|
@ -93,7 +94,7 @@ def gen_log_header(_type: Union[LogLevel, int, str]) -> str:
|
|||
if not isinstance(_type, str):
|
||||
_type = loglevel_as_str(_type)
|
||||
|
||||
## return newly formatted log message header
|
||||
## return newly formatted log message header
|
||||
return __LOG_TMPL.format('{CALLER}', DATE=\
|
||||
time.strftime(__TIMESTAMP_FMT, time.localtime()),
|
||||
TYPE=_type) + "{0}"
|
||||
|
|
@ -109,4 +110,4 @@ def wrap(value: str, *, width: int = 120, tb_size: int = 4) -> str:
|
|||
`@Params`: value - `str`, width = 120 - `int`, tb_size = 4 - `int`
|
||||
`@Return`: `str`
|
||||
"""
|
||||
return "\n".join(textwrap.wrap(value, width=width, tabsize=tb_size))
|
||||
return "\n".join(textwrap.wrap(value, width=width, tabsize=tb_size))
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user