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
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
try:
level = int(symbolic_level)
@ -20,13 +20,13 @@ def parse_logging(symbolic_level: str, symbolic_target: str) -> Tuple[int, Union
except ValueError:
pass
if symbolic_target == 'stderr':
target: Union[str, io.TextIOWrapper] = sys.stderr
target: logging.Handler = logging.StreamHandler(sys.stderr)
elif symbolic_target == 'stdout':
target = sys.stdout
target = logging.StreamHandler(sys.stdout)
elif symbolic_target == 'none':
target = None
target = logging.NullHandler()
else:
target = os.path.abspath(os.path.expanduser(symbolic_target))
target = logging.FileHandler(os.path.abspath(os.path.expanduser(symbolic_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
'templateroot': '/var/matemat/templates',
# Log level
'loglevel': logging.INFO,
'log_level': logging.INFO,
# Log target: An IO stream (stderr, stdout, ...) or a filename
'logtarget': sys.stderr,
'log_handler': 'stderr',
# Variables passed to pagelets
'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['port'] = int(parser['Matemat'].get('Port', config['port']))
config['staticroot'] = parser['Matemat'].get('StaticPath', os.path.expanduser(config['staticroot']))
config['loglevel'], config['logtarget'] =\
parse_logging(parser['Matemat'].get('LogLevel', config['loglevel']),
parser['Matemat'].get('LogTarget', config['logtarget']))
config['log_level'], config['log_handler'] =\
parse_logging(parser['Matemat'].get('LogLevel', config['log_level']),
parser['Matemat'].get('LogTarget', config['log_handler']))
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

View file

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