Ejemplo n.º 1
0
def setup_logging(config: Dict[str, Any]) -> None:
    """
    Process -v/--verbose, --logfile options
    """
    # Log level
    verbosity = config['verbosity']
    logging.root.addHandler(bufferHandler)

    logfile = config.get('logfile')

    if logfile:
        s = logfile.split(':')
        if s[0] == 'syslog':
            # Address can be either a string (socket filename) for Unix domain socket or
            # a tuple (hostname, port) for UDP socket.
            # Address can be omitted (i.e. simple 'syslog' used as the value of
            # config['logfilename']), which defaults to '/dev/log', applicable for most
            # of the systems.
            address = (s[1], int(s[2])) if len(s) > 2 else s[1] if len(s) > 1 else '/dev/log'
            handler_sl = get_existing_handlers(SysLogHandler)
            if handler_sl:
                logging.root.removeHandler(handler_sl)
            handler_sl = SysLogHandler(address=address)
            # No datetime field for logging into syslog, to allow syslog
            # to perform reduction of repeating messages if this is set in the
            # syslog config. The messages should be equal for this.
            handler_sl.setFormatter(Formatter('%(name)s - %(levelname)s - %(message)s'))
            logging.root.addHandler(handler_sl)
        elif s[0] == 'journald':
            try:
                from systemd.journal import JournaldLogHandler
            except ImportError:
                raise OperationalException("You need the systemd python package be installed in "
                                           "order to use logging to journald.")
            handler_jd = get_existing_handlers(JournaldLogHandler)
            if handler_jd:
                logging.root.removeHandler(handler_jd)
            handler_jd = JournaldLogHandler()
            # No datetime field for logging into journald, to allow syslog
            # to perform reduction of repeating messages if this is set in the
            # syslog config. The messages should be equal for this.
            handler_jd.setFormatter(Formatter('%(name)s - %(levelname)s - %(message)s'))
            logging.root.addHandler(handler_jd)
        else:
            handler_rf = get_existing_handlers(RotatingFileHandler)
            if handler_rf:
                logging.root.removeHandler(handler_rf)
            handler_rf = RotatingFileHandler(logfile,
                                             maxBytes=1024 * 1024 * 10,  # 10Mb
                                             backupCount=10)
            handler_rf.setFormatter(Formatter(LOGFORMAT))
            logging.root.addHandler(handler_rf)

    logging.root.setLevel(logging.INFO if verbosity < 1 else logging.DEBUG)
    _set_loggers(verbosity, config.get('api_server', {}).get('verbosity', 'info'))

    logger.info('Verbosity set to %s', verbosity)
Ejemplo n.º 2
0
def setup_logging(config: Dict[str, Any]) -> None:
    """
    Process -v/--verbose, --logfile options
    """
    # Log level
    verbosity = config['verbosity']

    # Log to stderr
    log_handlers: List[logging.Handler] = [logging.StreamHandler(sys.stderr)]

    logfile = config.get('logfile')
    if logfile:
        s = logfile.split(':')
        if s[0] == 'syslog':
            # Address can be either a string (socket filename) for Unix domain socket or
            # a tuple (hostname, port) for UDP socket.
            # Address can be omitted (i.e. simple 'syslog' used as the value of
            # config['logfilename']), which defaults to '/dev/log', applicable for most
            # of the systems.
            address = (s[1], int(
                s[2])) if len(s) > 2 else s[1] if len(s) > 1 else '/dev/log'
            handler = SysLogHandler(address=address)
            # No datetime field for logging into syslog, to allow syslog
            # to perform reduction of repeating messages if this is set in the
            # syslog config. The messages should be equal for this.
            handler.setFormatter(
                Formatter('%(name)s - %(levelname)s - %(message)s'))
            log_handlers.append(handler)
        elif s[0] == 'journald':
            try:
                from systemd.journal import JournaldLogHandler
            except ImportError:
                raise OperationalException(
                    "You need the systemd python package be installed in "
                    "order to use logging to journald.")
            handler = JournaldLogHandler()
            # No datetime field for logging into journald, to allow syslog
            # to perform reduction of repeating messages if this is set in the
            # syslog config. The messages should be equal for this.
            handler.setFormatter(
                Formatter('%(name)s - %(levelname)s - %(message)s'))
            log_handlers.append(handler)
        else:
            log_handlers.append(
                RotatingFileHandler(
                    logfile,
                    maxBytes=1024 * 1024,  # 1Mb
                    backupCount=10))

    logging.basicConfig(
        level=logging.INFO if verbosity < 1 else logging.DEBUG,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=log_handlers)
    _set_loggers(verbosity)
    logger.info('Verbosity set to %s', verbosity)
Ejemplo n.º 3
0
def get_logger(name):
    logger = logging.getLogger(name)
    if platform == 'linux':
        from systemd.journal import JournaldLogHandler
        journald_handler = JournaldLogHandler()
        journald_handler.setFormatter(
            logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
        logger.addHandler(journald_handler)
    else:
        logging.basicConfig(
            level=logging.DEBUG,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logger.setLevel(logging.INFO)
    return logger
Ejemplo n.º 4
0
    def __init__(self):
        # Getting an instance of the logger object this module will use
        self.__logger = logging.getLogger(self.__class__.__name__)

        # Instantiating the JournaldLogHandler to hook into systemd
        journald_handler = JournaldLogHandler()

        # Setting a formatter to include the level name
        journald_handler.setFormatter(
            logging.Formatter('[%(levelname)s] %(message)s'))

        # Adding the journald handler to the current logger
        self.__logger.addHandler(journald_handler)

        # Setting the logging level
        self.__logger.setLevel(logging.INFO)
Ejemplo n.º 5
0
def getLogger(config: dict=None):

    isUseJournald = config.get("journald")
    handler = logging.StreamHandler()
    if isUseJournald:
        try:
            from systemd.journal import JournaldLogHandler
            handler = JournaldLogHandler()
        except:
            print("systemd not installed giveup using journald. Using StreamHandler stdout/stderr as fallback.")
            pass

    logger = logging.getLogger()
    formatter = logging.Formatter(
        '%(asctime)s - %(levelname)s %(filename)s(%(lineno)d) %(funcName)s(): \t %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(config.get('log_level'))

    return logger
Ejemplo n.º 6
0
    def __init__(self):
        # Getting an instance of the logger object this module will use
        self.__logger = logging.getLogger(self.__class__.__name__)

        # Instantiating the JournaldLogHandler to hook into systemd
        journald_handler = JournaldLogHandler()

        # Setting a formatter to include the level name
        journald_handler.setFormatter(
            logging.Formatter('[%(levelname)s] %(message)s'))

        # Adding the journald handler to the current logger
        self.__logger.addHandler(journald_handler)

        # Setting the logging level
        self.__logger.setLevel(logging.INFO)

        # Setting global values related to the application
        # Getting current working directory
        util.settings.application_path = os.getcwd()
Ejemplo n.º 7
0
def setup_logger(logfile, loglevel=20):  # INFO loglevel

    # Add a logger
    logger = logging.getLogger(LOGGER_NAME)
    # instantiate the JournaldLogHandler to hook into systemd
    journald_handler = JournaldLogHandler()
    # set a formatter to include the level name
    journald_handler.setFormatter(
        logging.Formatter('[%(levelname)s] %(message)s'))

    # instantiate the FileHandler
    file_handler = logging.FileHandler(logfile)
    file_handler.setFormatter(
        logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'))

    # add the journald handler to the current logger
    logger.addHandler(journald_handler)
    logger.addHandler(file_handler)

    logger.setLevel(loglevel)
    logger.info("Started Agent Log")
Ejemplo n.º 8
0
    def __init__(self):
        # Getting an instance of the logger object this module will use
        self.__logger = logging.getLogger(self.__class__.__name__)

        # Instantiating the JournaldLogHandler to hook into systemd
        journald_handler = JournaldLogHandler()

        # Setting a formatter to include the level name
        journald_handler.setFormatter(
            logging.Formatter('[%(levelname)s] %(message)s'))

        # Adding the journald handler to the current logger
        self.__logger.addHandler(journald_handler)

        # Setting the logging level
        self.__logger.setLevel(logging.INFO)

        # Setting global values related to the application
        self.__conf_file_path = '{application_path}/{conf_file}'.format(
            application_path=application_path, conf_file=CONF_FILE)
        self.__logger.info(
            "Configuration file should be located at {conf_file_path}".format(
                conf_file_path=self.__conf_file_path))
        print(
            "Configuration file should be located at {conf_file_path}".format(
                conf_file_path=self.__conf_file_path))

        self.__user_settings = []
        # Reading configuration file (kayordomo.yaml)
        if os.path.exists(self.__conf_file_path):
            conf_file = open(self.__conf_file_path)
            self.__user_settings = yaml.load(conf_file, Loader=yaml.FullLoader)

            conf_file.close()
        else:
            self.__logger.info("Warning: There is no configuration file...")
            print("Warning: There is no configuration file...")
Ejemplo n.º 9
0
#   return lib.KeyPressCallback(key, duration)


# command callback
def command_callback(cmd):
    return lib.CommandCallback(cmd)


def exitfunction(signum, frame):
    sys.exit()


if __name__ == '__main__':
    signal.signal(signal.SIGTERM, exitfunction)
    logger = logging.getLogger("CECCOM")
    journald_handler = JournaldLogHandler()
    journald_handler.setFormatter(
        logging.Formatter('[%(levelname)s] %(message)s'))
    logger.addHandler(journald_handler)
    logger.setLevel(logging.DEBUG)
    # initialise libCEC
    cecqueue = queue.Queue()
    exception = False
    bosecomobj = serialcom.bosecom('/dev/ttyAMA0', 50, cecqueue, logger)
    lib = ceccom(cecqueue, bosecomobj, logger)
    lib.SetLogCallback(log_callback)
    # Somehow this function isn't working
    # lib.SetKeyPressCallback(key_press_callback)
    lib.SetCommandCallback(command_callback)
    lib.daemon = True
    bosecomobj.daemon = True
Ejemplo n.º 10
0
#import syslog
import datetime
import json
import select
from kodijson import Kodi

from libby.remote import udpRemote
import paho.mqtt.client as mqtt  #import the client1

import resources_rc

import logging
logger = logging.getLogger("FLURZENTRALE")
try:
    from systemd.journal import JournaldLogHandler
    logger.addHandler(JournaldLogHandler())
    logger.info("Logging to systemdi this time")
except:
    fh = logging.FileHandler(path.expanduser("~/fz.log"))
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    fh.setFormatter(formatter)
    logger.addHandler(fh)
    logger.setLevel(logging.INFO)
    logger.info("No systemd logger detected, logging to file instead")
#logger.setLevel(logging.DEBUG)
logger.setLevel(logging.INFO)

garagn_tcp_addr = 'garagn'
garagn_tcp_port = 80
Ejemplo n.º 11
0
import subprocess
import psutil
import time
import logging
import requests
import json
import threading
from systemd.journal import JournaldLogHandler

log = logging.getLogger('centry')
log.addHandler(JournaldLogHandler())
log.setLevel(logging.INFO)

class WatcherThread(threading.Thread):
    def __init__(self, config):
        threading.Thread.__init__(self)
        self.configure(config)
        if config["enable"] == True:
            self._running = True
        else:
            self._running = False

    def configure(self, config):
        self.minFreeSpace = config["minFreeSpace"]
        self.increaseStep = config["increaseStep"]
        self.checkInterval = config["checkInterval"]
        self.EC2volumeId = config["EC2VolumeId"]
        self.EC2rootDrive = config["EC2rootDrive"]
        self.EC2rootPart = config["EC2rootPart"]
        self.EC2rootPartNum = config["EC2rootPartNum"]
    
Ejemplo n.º 12
0
 def create_logger(self):
     self.log = logging.getLogger('app_logger')
     self.log.propagate = False
     self.log.setLevel(logging.DEBUG)
     self.log.addHandler(JournaldLogHandler())
def main():
    """Run main function."""
    run_setup_commands()
    FAPP.run(host='127.0.0.1', port=FLASK_PORT, debug=DEBUG)


if __name__ == '__main__':
    # logging.basicConfig()
    LOG = logging.getLogger('allports-listening')

    PARSER = argparse.ArgumentParser()
    PARSER.add_argument(
        '-l',
        '--logger',
        help='type of logger',
        choices=['stdout', 'systemd'],
        default='stdout',
        type=str,
    )
    ARGS = PARSER.parse_args()
    if ARGS.logger == 'systemd':
        HANDLER = JournaldLogHandler()
    else:
        HANDLER = logging.StreamHandler(sys.stdout)
    HANDLER.setFormatter(logging.Formatter('[%(levelname)s] %(message)s'))
    LOG.addHandler(HANDLER)
    LOG.setLevel(logging.INFO)
    logging.getLogger('werkzeug').setLevel(logging.WARN)
    main()