Commit dfd1d075 authored by Martin Matějek's avatar Martin Matějek

Refactoring of module logging

parent ac5c1846
......@@ -2,6 +2,7 @@
import argparse
import json
import logging
import os
import sys
......@@ -25,6 +26,8 @@ COLORS = {
'default': '\033[39m',
}
logger = logging.getLogger("notification-system-cli")
def create_argparser():
"""Create new argument parser"""
......@@ -92,6 +95,19 @@ def print_notification(notification):
print("Metadata: {}".format(notification['metadata']))
# work-in-progress!
def setup_logging():
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('notify-cli.log')
fh.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(filename)s:%(lineno)s - %(levelname)s - %(funcName)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
def process_args(parser, args):
"""Call module interface based on args"""
if args.config:
......@@ -158,6 +174,7 @@ def process_args(parser, args):
def main():
setup_logging()
parser = create_argparser()
args = parser.parse_args()
......
import os.path
import logging
from .config import config
from .exceptions import (
......@@ -8,10 +9,11 @@ from .exceptions import (
NotificationNotDismissibleException
)
from .pluginstorage import PluginStorage
from .logger import logger
from .notificationstorage import NotificationStorage
from .notification import Notification
logger = logging.getLogger(__name__)
class Api:
"""Public interface of module"""
......
import configparser
import logging
logger = logging.getLogger(__name__)
class Config:
......@@ -12,7 +15,6 @@ class Config:
self.conf.set("settings", "persistent_dir", "/srv")
self.conf.set("settings", "plugin_dir", "plugins")
self.conf.set("settings", "templates_dir", "templates")
self.conf.set("settings", "logfile", "notifylib.log")
self.conf.set("settings", "cmd_timeout", "10")
def load_config(self, filename):
......@@ -20,7 +22,7 @@ class Config:
with open(filename, 'r') as f:
self.conf.read_file(f)
except FileNotFoundError:
print("Failed to open config file '{}'".format(filename))
logger.warning("Failed to open config file '{}'".format(filename))
# TODO: handle configparser exceptions
def get(self, section, key):
......
import logging
from .config import config
# TODO: logger config file
logger = logging.getLogger("notifylib")
# just use DEBUG level for now...
logger.setLevel(logging.DEBUG)
# log to file for now...
fh = logging.FileHandler(config.get("settings", "logfile"))
fh.setLevel(logging.DEBUG)
#formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
formatter = logging.Formatter('%(filename)s:%(lineno)s - %(levelname)s - %(funcName)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
# TODO: log to syslog
import json
import logging
import uuid
from datetime import datetime
......@@ -7,10 +8,11 @@ from types import SimpleNamespace
from .config import config
from .exceptions import CreateNotificationError, NotificationTemplatingError
from .logger import logger
from .notificationskeleton import NotificationSkeleton
from .supervisor import Supervisor
logger = logging.getLogger(__name__)
class Notification:
ATTRS = ['notif_id', 'timestamp', 'skeleton', 'persistent', 'timeout', 'severity', 'data', 'fallback', 'valid', 'explicit_dismiss', 'default_action']
......
import os
import logging
from datetime import datetime
from functools import lru_cache
from .exceptions import RemoveFailedException
from .logger import logger
from .notification import Notification
logger = logging.getLogger(__name__)
class NotificationStorage:
"""In-memory notification storage that serialize and deserialize them"""
......
import logging
import pathlib
import yaml
from .logger import logger
logger = logging.getLogger(__name__)
class Plugin:
......
import os
import logging
from functools import lru_cache
from .plugin import Plugin
from .logger import logger
from .notificationskeleton import NotificationSkeleton
logger = logging.getLogger(__name__)
class PluginStorage:
"""Storage for plugins"""
......
from .logger import logger
import logging
logger = logging.getLogger(__name__)
class Sorting:
......
import logging.handlers
import logging
import os
import shlex
import signal
import subprocess
import sys
logger = logging.getLogger(__name__)
class Supervisor:
def __init__(self):
......@@ -13,23 +15,6 @@ class Supervisor:
self.cmd_args = None
self.timeout = None
# create separate logger for new process
self.logger = None
self.init_logger()
def init_logger(self):
self.logger = logging.getLogger('notifylib')
self.logger.setLevel(logging.DEBUG)
syslog_handler = logging.handlers.SysLogHandler(address='/dev/log')
syslog_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)s %(message)s')
syslog_handler.setFormatter(formatter)
self.logger.addHandler(syslog_handler)
def fork(self):
"""Double fork process"""
try:
......@@ -37,7 +22,7 @@ class Supervisor:
if pid > 0:
return
except OSError as e:
self.logger.error("fork #1 failed: %d (%s)", e.errno, e.strerror)
logger.error("fork #1 failed: %d (%s)", e.errno, e.strerror)
sys.exit(1)
os.setsid()
......@@ -47,16 +32,16 @@ class Supervisor:
if pid > 0:
sys.exit(0)
except OSError as e:
self.logger.error("fork #2 failed: %d (%s)", e.errno, e.strerror)
logger.error("fork #2 failed: %d (%s)", e.errno, e.strerror)
sys.exit(1)
self.run_proc()
exit_code = self.join()
self.logger.info("Process exited with exit code %s", exit_code)
logger.info("Process exited with exit code %s", exit_code)
if exit_code != 0:
self.logger.info("stdout: %s", self.process.stdout.readline())
self.logger.warning("stderr: %s", self.process.stderr.readline())
logger.info("stdout: %s", self.process.stdout.readline())
logger.warning("stderr: %s", self.process.stderr.readline())
sys.exit(0)
......@@ -74,10 +59,10 @@ class Supervisor:
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except ValueError as e:
self.logger.error("Failed to parse command: %s", e)
logger.error("Failed to parse command: %s", e)
sys.exit(1)
except FileNotFoundError:
self.logger.error("Couldn't execute '%s'. Executable '%s' not found", self.cmd, shlex.split(self.cmd)[0])
logger.error("Couldn't execute '%s'. Executable '%s' not found", self.cmd, shlex.split(self.cmd)[0])
sys.exit(1)
def run(self, cmd, cmd_args, timeout):
......@@ -97,5 +82,5 @@ class Supervisor:
return exit_code
def timeout_handler(self, signum, frame):
self.logger.info("Terminating process due to timeout")
logger.info("Terminating process due to timeout")
self.process.terminate()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment