Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplifies logging #61

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 12 additions & 17 deletions src/rng2doc/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,10 @@
"""

# Standard Library
import logging
import os
import logging
import sys
import time
from logging.config import dictConfig
from pkg_resources import resource_filename

# Third Party Libraries
Expand All @@ -35,12 +34,10 @@

# Local imports
from . import __version__
from .common import DEFAULT_LOGGING_DICT, LOGLEVELS, errorcode
from .log import setup_logging
from .common import LOGLEVELS, errorcode
from .rng import parse

#: Use __package__, not __name__ here to set overall LOGging level:
LOG = logging.getLogger(__package__)


def parsecli(cliargs=None):
"""Parse CLI arguments with docopt
Expand All @@ -53,9 +50,6 @@ def parsecli(cliargs=None):
version = "%s %s" % (__package__, __version__)
args = docopt(__doc__,
argv=cliargs, version=version)
dictConfig(DEFAULT_LOGGING_DICT)
LOG.setLevel(LOGLEVELS.get(args['-v'], logging.DEBUG))

return args


Expand Down Expand Up @@ -114,12 +108,13 @@ def main(cliargs=None):
"""
try:
args = parsecli(cliargs)
logger = setup_logging(LOGLEVELS.get(args['-v'], logging.DEBUG))
if args['--timing']:
t_perf = time.perf_counter()
t_proc = time.process_time()
LOG.info('%s version: %s', __package__, __version__)
LOG.debug('Python version: %s', sys.version.split()[0])
LOG.debug("CLI result: %s", args)
logger.info('%s version: %s', __package__, __version__)
logger.debug('Python version: %s', sys.version.split()[0])
logger.debug("CLI result: %s", args)
checkargs(args)
result = parse(args['RNGFILE'])
output(result, args['--output'], args["--output-format"])
Expand All @@ -129,24 +124,24 @@ def main(cliargs=None):
timing_msg = "{:7} (timing): {} perf, {} proc"
timing_msg = timing_msg.format(__package__, elapsed_time_perf, elapsed_time_proc)
print(timing_msg, file=sys.stderr)
LOG.info("Done.")
logger.info("Done.")
return 0

except DocoptExit as error:
LOG.fatal("Need a RELAX NG file.")
logger.fatal("Need a RELAX NG file.")
printable_usage(__doc__)
return errorcode(error)

except FileNotFoundError as error:
LOG.fatal("File not found '%s'", error)
logger.fatal("File not found '%s'", error)
return errorcode(error)

except etree.XMLSyntaxError as error:
LOG.fatal("Failed to parse the XML input file '%s'", error)
logger.fatal("Failed to parse the XML input file '%s'", error)
return errorcode(error)

except RuntimeError as error:
LOG.fatal("Something failed '%s'", error)
logger.fatal("Something failed '%s'", error)
return 1

except KeyboardInterrupt as error:
Expand Down
59 changes: 1 addition & 58 deletions src/rng2doc/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,7 @@
from docopt import DocoptExit
from lxml.etree import QName, XMLSyntaxError

from logging import (CRITICAL, # isort:skip
DEBUG,
ERROR,
FATAL,
INFO,
NOTSET,
WARN,
WARNING,
)
from logging import DEBUG, INFO, WARNING


# Error codes
Expand Down Expand Up @@ -116,52 +108,3 @@ def errorcode(error):
1: INFO,
2: DEBUG,
}

#: Map log numbers to log names
LOGNAMES = {NOTSET: 'NOTSET', # 0
None: 'NOTSET',
DEBUG: 'DEBUG', # 10
INFO: 'INFO', # 20
WARN: 'WARNING', # 30
WARNING: 'WARNING', # 30
ERROR: 'ERROR', # 40
CRITICAL: 'CRITICAL', # 50
FATAL: 'CRITICAL', # 50
}

#: Default logging dict for :class:`logging.config.dictConfig`:
DEFAULT_LOGGING_DICT = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
# See https://docs.python.org/3.5/library/logging.html#logrecord-attributes
'format': '[%(levelname)s] %(name)s::%(funcName)s: %(message)s'
},
'myformatter': {
'()': 'rng2doc.log.CustomConsoleFormatter',
'format': '[%(levelname)s] %(message)s',
},
},
'handlers': {
'default': {
'level': 'NOTSET',
'formatter': 'standard',
'class': 'logging.StreamHandler',
# 'stream': 'ext://sys.stderr',
},
'myhandler': {
'level': 'NOTSET',
'formatter': 'myformatter',
'class': 'logging.StreamHandler',
# 'stream': 'ext://sys.stderr',
},
},
'loggers': {
__package__: {
'handlers': ['myhandler', ], # 'default'
'level': 'INFO',
'propagate': True
}
}
}
35 changes: 10 additions & 25 deletions src/rng2doc/log.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,18 @@
"""Logging module

"""
Logging Module
"""

# Standard Library
import logging

# Local imports
from .common import DEFAULT_LOGGING_DICT

#: the default logging format
DEFAULT_FORMAT = DEFAULT_LOGGING_DICT['formatters']['standard']['format']

#: a very simple format
SIMPLE_FORMAT = DEFAULT_LOGGING_DICT['formatters']['myformatter']['format']
logger = logging.getLogger("rng2doc")


class CustomConsoleFormatter(logging.Formatter):
"""
Modify the way DEBUG messages are displayed.
"""
# Lists all different formats
FORMATS = {logging.INFO: logging.Formatter(SIMPLE_FORMAT),
logging.WARNING: logging.Formatter(SIMPLE_FORMAT),
logging.ERROR: logging.Formatter(SIMPLE_FORMAT),
logging.FATAL: logging.Formatter(SIMPLE_FORMAT),
'DEFAULT': logging.Formatter(DEFAULT_FORMAT),
}
def setup_logging(level):
global logger

def format(self, record):
"Format the specified record as text."
fmt = self.FORMATS.get(record.levelno, self.FORMATS['DEFAULT'])
return fmt.format(record)
logger.setLevel(level)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('[%(levelname)s] %(message)s'))
logger.addHandler(handler)
return logger
6 changes: 2 additions & 4 deletions src/rng2doc/rng.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
"""

# Standard Library
import logging
from pkg_resources import resource_filename

# Third Party Libraries
Expand All @@ -11,11 +10,10 @@

# Local imports
from .common import NSMAP, RNG_ELEMENT, RNG_REF, RNG_VALUE
from .log import logger
from .transforms.svg import SVG
from .transforms.xml import XML

LOG = logging.getLogger(__name__)


def transform(node, output, **kwargs):
"""General transformation of RELAX NG
Expand Down Expand Up @@ -118,7 +116,7 @@ def parse(rngfile):
:return: The ElementTree of the new XML document
:rtype: etree.ElementTree
"""
LOG.info("Process RNG file %r...", rngfile)
logger.info("Process RNG file %r...", rngfile)

# Remove all blank lines, which makes the output later much more beautiful.
xmlparser = etree.XMLParser(remove_blank_text=True, remove_comments=True)
Expand Down
6 changes: 0 additions & 6 deletions src/rng2doc/transforms/svg.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
"""Transform dictionary and functions for SVG
"""

# Standard Library
import logging

# Third Party Libraries
import pydot

Expand All @@ -26,8 +22,6 @@
RNG_VALUE,
RNG_ZERO_OR_MORE)

LOG = logging.getLogger(__name__)


def transform_element_svg(node, **kwargs):
"""Transforms a RELAX NG element into a graphviz node.
Expand Down
6 changes: 0 additions & 6 deletions src/rng2doc/transforms/xml.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
"""Transform dictionary and functions for XML
"""

# Standard Library
import logging

# Third Party Libraries
from lxml import etree

Expand All @@ -19,8 +15,6 @@
RNG_TEXT,
RNG_VALUE)

LOG = logging.getLogger(__name__)


def find_namespace(node):
"""Finds the namespace for a node.
Expand Down