1
0
Fork 0
forked from s3lph/matemat

Slightly improved logging config.

This commit is contained in:
s3lph 2018-07-14 12:16:46 +02:00
parent 3382d23d85
commit a4967b1338
2 changed files with 21 additions and 30 deletions

View file

@ -8,7 +8,7 @@ import logging
from configparser import ConfigParser from configparser import ConfigParser
def parse_logging(symbolic_level: str, symbolic_target: str) -> Tuple[int, Union[str, io.TextIOWrapper]]: def parse_logging(symbolic_level: str, symbolic_target: str) -> Tuple[int, logging.Handler]:
level: int = logging.NOTSET level: int = logging.NOTSET
try: try:
level = int(symbolic_level) level = int(symbolic_level)
@ -20,13 +20,13 @@ def parse_logging(symbolic_level: str, symbolic_target: str) -> Tuple[int, Union
except ValueError: except ValueError:
pass pass
if symbolic_target == 'stderr': if symbolic_target == 'stderr':
target: Union[str, io.TextIOWrapper] = sys.stderr target: logging.Handler = logging.StreamHandler(sys.stderr)
elif symbolic_target == 'stdout': elif symbolic_target == 'stdout':
target = sys.stdout target = logging.StreamHandler(sys.stdout)
elif symbolic_target == 'none': elif symbolic_target == 'none':
target = None target = logging.NullHandler()
else: else:
target = os.path.abspath(os.path.expanduser(symbolic_target)) target = logging.FileHandler(os.path.abspath(os.path.expanduser(symbolic_target)))
return level, target return level, target
@ -48,9 +48,9 @@ def parse_config_file(paths: Union[str, Iterable[str]]) -> Dict[str, Any]:
# Root directory of Jinja2 templates # Root directory of Jinja2 templates
'templateroot': '/var/matemat/templates', 'templateroot': '/var/matemat/templates',
# Log level # Log level
'loglevel': logging.INFO, 'log_level': logging.INFO,
# Log target: An IO stream (stderr, stdout, ...) or a filename # Log target: An IO stream (stderr, stdout, ...) or a filename
'logtarget': sys.stderr, 'log_handler': 'stderr',
# Variables passed to pagelets # Variables passed to pagelets
'pagelet_variables': dict() 'pagelet_variables': dict()
} }
@ -76,9 +76,9 @@ def parse_config_file(paths: Union[str, Iterable[str]]) -> Dict[str, Any]:
config['listen'] = parser['Matemat'].get('Address', config['listen']) config['listen'] = parser['Matemat'].get('Address', config['listen'])
config['port'] = int(parser['Matemat'].get('Port', config['port'])) config['port'] = int(parser['Matemat'].get('Port', config['port']))
config['staticroot'] = parser['Matemat'].get('StaticPath', os.path.expanduser(config['staticroot'])) config['staticroot'] = parser['Matemat'].get('StaticPath', os.path.expanduser(config['staticroot']))
config['loglevel'], config['logtarget'] =\ config['log_level'], config['log_handler'] =\
parse_logging(parser['Matemat'].get('LogLevel', config['loglevel']), parse_logging(parser['Matemat'].get('LogLevel', config['log_level']),
parser['Matemat'].get('LogTarget', config['logtarget'])) parser['Matemat'].get('LogTarget', config['log_handler']))
config['templateroot'] = parser['Matemat'].get('TemplatePath', os.path.expanduser(config['templateroot'])) config['templateroot'] = parser['Matemat'].get('TemplatePath', os.path.expanduser(config['templateroot']))
# Read all values from the [Pagelets] section, if present. These values are passed to pagelet functions # Read all values from the [Pagelets] section, if present. These values are passed to pagelet functions

View file

@ -1,9 +1,7 @@
from typing import Any, Callable, Dict, Tuple, Type, Union from typing import Any, Callable, Dict, Tuple, Type, Union
from io import TextIOWrapper
import logging import logging
import sys
import os import os
import socket import socket
import mimetypes import mimetypes
@ -105,8 +103,8 @@ class MatematHTTPServer(HTTPServer):
staticroot: str, staticroot: str,
templateroot: str, templateroot: str,
pagelet_variables: Dict[str, str], pagelet_variables: Dict[str, str],
log_level: int = logging.INFO, log_level: int,
log_target: Union[str, TextIOWrapper] = sys.stderr, log_handler: logging.Handler,
bind_and_activate: bool = True) -> None: bind_and_activate: bool = True) -> None:
super().__init__(server_address, handler, bind_and_activate) super().__init__(server_address, handler, bind_and_activate)
# Resolve webroot directory # Resolve webroot directory
@ -122,16 +120,9 @@ class MatematHTTPServer(HTTPServer):
# Set up logger # Set up logger
self.logger: logging.Logger = logging.getLogger('matemat.webserver') self.logger: logging.Logger = logging.getLogger('matemat.webserver')
self.logger.setLevel(log_level) self.logger.setLevel(log_level)
# Set up log handler that logs to # Set up log handler
sh: logging.Handler = logging.StreamHandler(sys.stderr) log_handler.setFormatter(logging.Formatter('%(asctime)s @ %(name)s [%(levelname)s]: %(message)s'))
if log_target is None: self.logger.addHandler(log_handler)
sh: logging.Handler = logging.NullHandler()
elif isinstance(log_target, TextIOWrapper):
sh = logging.StreamHandler(log_target)
elif isinstance(log_target, str):
sh = logging.FileHandler(log_target)
sh.setFormatter(logging.Formatter('%(asctime)s @ %(name)s [%(levelname)s]: %(message)s'))
self.logger.addHandler(sh)
class MatematWebserver(object): class MatematWebserver(object):
@ -155,8 +146,8 @@ class MatematWebserver(object):
staticroot: str, staticroot: str,
templateroot: str, templateroot: str,
pagelet_variables: Dict[str, str], pagelet_variables: Dict[str, str],
loglevel: int, log_level: int,
logtarget: Union[str, TextIOWrapper]) -> None: log_handler: logging.Handler) -> None:
""" """
Instantiate a MatematWebserver. Instantiate a MatematWebserver.
@ -165,8 +156,8 @@ class MatematWebserver(object):
:param staticroot: Path to the static webroot directory. :param staticroot: Path to the static webroot directory.
:param templateroot: Path to the Jinja2 templates root directory. :param templateroot: Path to the Jinja2 templates root directory.
:param pagelet_variables: Dictionary of variables to pass to pagelet functions. :param pagelet_variables: Dictionary of variables to pass to pagelet functions.
:param loglevel: The log level, as defined in the builtin logging module. :param log_level: The log level, as defined in the builtin logging module.
:param logtarget: The logging target. :param log_handler: The logging handler.
""" """
# IPv4 address detection heuristic # IPv4 address detection heuristic
if ':' not in listen and '.' in listen: if ':' not in listen and '.' in listen:
@ -178,8 +169,8 @@ class MatematWebserver(object):
staticroot, staticroot,
templateroot, templateroot,
pagelet_variables, pagelet_variables,
loglevel, log_level,
logtarget) log_handler)
def start(self) -> None: def start(self) -> None:
""" """