Beispiel #1
0
def get_logger(name=__name__, loglevel=logging.INFO, host='localhost'):
    socket_handler = handlers.SocketHandler(host,
                                            handlers.DEFAULT_TCP_LOGGING_PORT)
    rootLogger.addHandler(socket_handler)
    logging.info("Creating new logger {}".format(name))
    new_logger = logging.getLogger(name)
    new_logger.setLevel(loglevel)
    return new_logger
Beispiel #2
0
 def init_log(self, name, level, host, port, capacity=100):
     target = handlers.SocketHandler(host, port)
     if capacity > 0:
         hdlr = handlers.MemoryHandler(capacity, logging.ERROR, target)
     else:
         hdlr = target
     hdlr.setLevel(level)
     self.logger = logging.getLogger(name)
     self.logger.addHandler(hdlr)
     self.logger.setLevel(level)
Beispiel #3
0
def get_logger(name, level, host, port, capacity=1024):
    target = handlers.SocketHandler(host, port)
    if capacity > 0:
        hdlr = handlers.MemoryHandler(capacity, logging.ERROR, target)
    else:
        hdlr = target
    hdlr.setLevel(level)
    logger = logging.getLogger(name)
    logger.addHandler(hdlr)
    logger.setLevel(level)
    return logger
Beispiel #4
0
def getSocketLogger(name, level, host, port, memoryCapacity):
    target = handlers.SocketHandler(host, port)
    if memoryCapacity > 0:

        hdlr = handlers.MemoryHandler(
            memoryCapacity,
            logging.ERROR,  # 此参数是指遇到此级别时,马上flush
            target)
    else:
        hdlr = target

    hdlr.setLevel(level)
    logger = logging.getLogger(name)
    logger.addHandler(hdlr)
    logger.setLevel(level)
    return logger
Beispiel #5
0
def log_wrapper(cls,
                methods_to_log: tuple,
                log_mode='local',
                host=None,
                port=None):
    """
    :param cls: instance to be logged
    :param methods_to_log: methods of instance to be logged (both method name, parameters, time
                           of invoking will be logged)
    :param log_mode: 'local': log in local file (log.log)
                     'tcp' or 'udp': log to concrete host & port
    :param host: target host if log mode is 'tcp' or 'udp'
    :param port: port of target host if log mode is 'tcp' or 'udp'
    :return: wrapped instance
    """
    orig_cls = cls.__class__
    logger = logging.getLogger(orig_cls.__name__)
    if log_mode == 'tcp' or log_mode == 'udp':
        handler = log_handlers.SocketHandler(
            host=host,
            port=port) if log_mode == 'tcp' else log_handlers.DatagramHandler(
                host=host, port=port)
    else:
        if not os.path.exists(_log_file_name):
            if system() == 'Windows':
                open(_log_file_name, 'a').close()
            else:
                os.mknod(_log_file_name)
        handler = logging.FileHandler(_log_file_name, mode='r+')
    logger.addHandler(handler)

    orig_methods = [
        getattr(orig_cls, method) for method in methods_to_log
        if hasattr(orig_cls, method)
    ]

    logged_methods = [_log_wrapper(method, logger) for method in orig_methods]

    for method in logged_methods:
        setattr(orig_cls, method.__name__, method)

    # bind logger with instance, so as to close log-handler when db closes
    cls._logger = logger
    return cls
Beispiel #6
0
 def __init__(self, name, filehandler=False, sockethandler=True):
     level_relations = {
         'debug': logging.DEBUG,
         'info': logging.INFO,
         'warning': logging.WARNING,
         'error': logging.ERROR,
         'crit': logging.CRITICAL
     }  # 日志级别关系映射
     self.logger = logging.getLogger(name)
     self.logger.setLevel(level_relations[Log.baseLogLevel])
     format_log = logging.Formatter(Log.fmt)
     sh = logging.StreamHandler()
     sh.setFormatter(format_log)
     sh.setLevel(level_relations[Log.StreamHandlerlevel])
     self.logger.addHandler(sh)
     if sockethandler:
         sockhandler = handlers.SocketHandler(Log.severip,
                                              Log.socket_handler_port)
         sockhandler.setLevel(level_relations[Log.sockhandlerLevel])
         sockhandler.setFormatter(format_log)
         self.logger.addHandler(sockhandler)
     if filehandler:
         filename = '{}.log'.format(name)
         th = handlers.TimedRotatingFileHandler(
             filename=filename,
             when='D',
             backupCount=30,
             interval=1,
             encoding='utf-8')  # 往文件里写入#指定间隔时间自动生成文件的处理器
         # 实例化TimedRotatingFileHandler
         # interval是时间间隔,backupCount是备份文件的个数,如果超过这个个数,就会自动删除,when是间隔的时间单位,单位有以下几种:
         # S 秒
         # M 分
         # H 小时、
         # D 天、
         # W 每星期(interval==0时代表星期一)
         # midnight 每天凌晨
         th.setLevel(level_relations[Log.filehandlerlevel])
         th.setFormatter(format_log)
         self.logger.addHandler(th)
Beispiel #7
0
LOG_MAX_BYTES = py_configs.PY_LOGS_MAX_BYTES
LOG_FILE_COUNT = py_configs.PY_LOGS_MAX_FILE_COUNT
LOG_ADDRESS = py_configs.PY_LOGS_ADDRESS

formatter = logging.Formatter(LOG_FORMAT)
logger = logging.getLogger('IMAGER')
logger.setLevel(LOG_LEVEL)
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(LOG_LEVEL)
consoleHandler.setFormatter(formatter)
fileHandler = handlers.RotatingFileHandler(LOG_FILENAME,
                                           maxBytes=LOG_MAX_BYTES,
                                           backupCount=LOG_FILE_COUNT)
fileHandler.setLevel(LOG_LEVEL)
fileHandler.setFormatter(formatter)
socketHandler = handlers.SocketHandler(LOG_ADDRESS,
                                       handlers.DEFAULT_TCP_LOGGING_PORT)

logger.addHandler(socketHandler)
logger.addHandler(consoleHandler)
logger.addHandler(fileHandler)

THUMBNAIL_WIDTH = 1000
THUMBNAIL_HIGHT = 709
IMAGE_WAIT_TIMEOUT_CNT = 20

# image save folder
IMAGE_SAVE_PATH = "/mnt/ssd/imager/sensor"
RAW_DATA_FILENAME = "imager_data.bin"


class Imager(object):
Beispiel #8
0
                logger.warning(
                    "skipping environ '{}={}' because exception '{}'".format(
                        env_k, env_v, e))

        global_config["console_port_iterator"] = console_port_iterator
        global_config["console_thread"] = {}
        global_config["console_ports"] = {}
        if not global_config["http_console_host"]:
            global_config["http_console_host"] = global_config["http_host"]
            if global_config["http_host"] == "0.0.0.0":
                global_config["http_console_host"] = socket.gethostname()

        # Configure logging STEP 2
        if "log_host" in global_config:
            socket_handler = log_handlers.SocketHandler(
                global_config["log_socket_host"],
                global_config["log_socket_port"])
            socket_handler.setFormatter(log_formatter_complete)
            if global_config.get("log_socket_level") \
                    and global_config["log_socket_level"] != global_config["log_level"]:
                socket_handler.setLevel(global_config["log_socket_level"])
            logger.addHandler(socket_handler)

        if log_file:
            global_config['log_file'] = log_file
        elif global_config.get('log_file'):
            set_logging_file(global_config['log_file'])

        logger.setLevel(getattr(logging, global_config['log_level']))
        logger.critical(
            "Starting openmano server version: '%s %s' command: '%s'",
Beispiel #9
0
 def __call__(self, state_machine_list, noimpl_flag, log_filename=None):
     """
     Initialization of Python qf module and
     startup of all state machine threads.
     """
     global IMPL, ACTIVE
     # Log to stdout only.
     self.__logger_output_handler = logging.StreamHandler(sys.stdout)
     # Connect to timeline GUI if it is running
     self.__logger_output_socket = None
     if self.__timeline_process is not None:
         self.__logger_output_socket = handlers.SocketHandler('localhost', 7777)
     #
     if log_filename != None:
         self.__logger_file_handler = logging.FileHandler(log_filename)
     self.__logger_output_handler.setLevel(logging.INFO)
     # Include only message in output.
     #logger_formatter = logging.Formatter('%(thread)d:%(name)s %(message)s')
     logger_formatter = logging.Formatter('%(message)s')
     self.__logger_output_handler.setFormatter(logger_formatter)
     #
     #print "sys.modules:", sorted(sys.modules.keys())
     smsToActivate = list()
     for active in self.__active_modules:
         names = map(lambda x: x + "Active", state_machine_list)
         if (len(state_machine_list)==0) or (active in names)==True:
             smsToActivate.append(active)
             # Get actual module here.
             mod = self.__active_modules_dict[active]
             # Enable logger as info messages only.
             mod.LOGGER.setLevel(logging.INFO)
             mod.LOGGER.addHandler(self.__logger_output_handler)
             if log_filename !=None:
                 print "Attaching log file handler: %s\n" % log_filename
                 mod.LOGGER.addHandler(self.__logger_file_handler)
             #
             # Add socket handler for timeline GUI.
             #
             if self.__timeline_process is not None:
                 mod.LOGGER.addHandler(self.__logger_output_socket)
     #
     # Instantiate and activate all StateMachines and impls first in
     # separate loops to avoid dependency on order of logger setup, and to
     # allow ACTIVE and IMPL dicts to be printed out before SM activation.
     submImplsToFind = dict()
     for active in smsToActivate:
         sm_name = active.split("Active")[0]
         sm_name_impl = sm_name + "Impl"
         # Instance any Impl module and active object, excluding submachines
         if active in self.__submachines_dict.keys():
             if sm_name_impl in self.__impl_modules_dict.keys():
                 # No instancing; gather submachine impl for access via IMPL
                 submImplsToFind[sm_name] = active
         else:  # Active is NOT a submachine
             mod = self.__active_modules_dict[active]
             if sm_name_impl in self.__impl_modules_dict.keys():
                 mod_impl = self.__impl_modules_dict[sm_name_impl]
                 # Instance active object with impl instance here
                 impl = mod_impl.__dict__[sm_name_impl]()
                 s = mod.__dict__[active](impl)
                 IMPL[sm_name] = impl
             else:
                 # Instance active object here without impl object
                 s = mod.__dict__[active]()
             # Build global of active objects keyed on state machine name.
             ACTIVE[sm_name] = s
     #
     # Find submachine Impls within the ACTIVE objects
     # TODO only able to find submachines one-level down!
     for subm_name in submImplsToFind.keys():
         substate_name = self.__submachines_dict[submImplsToFind[subm_name]]
         for sm_name in ACTIVE.keys():
             mod = ACTIVE[sm_name]
             try:
                 mod_impl = eval("mod._%sActive__%sImpl" % (sm_name, substate_name))
                 # found submachine impl! add to IMPL
                 IMPL[substate_name] = mod_impl
             except AttributeError:
                 continue
     #
     # Print the accessible ACTIVE and IMPL objects
     print "*Accessible Active and Impl objects:"
     print "  ACTIVE%s" % ACTIVE.keys()
     print "    IMPL%s" % IMPL.keys()
     #
     # Finally, activate the ACTIVEs
     for s in ACTIVE.values():
         # Active object start up and register with QF
         s.startActive()
         # start/initialize HSM
         s.onStart(s.top)
         s.start()
Beispiel #10
0
#!/usr/bin/env python3
# coding:utf-8

import logging
from logging import handlers

rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.DEBUG)
socketHandler = handlers.SocketHandler('localhost', 9999)
# don't bother with a formatter, since a socket handler sends the event as
# an unformatted pickle
rootLogger.addHandler(socketHandler)

# Now we can log the root logger, or any other logger,First the root...
logging.info('Jackdaws  love my big sphinx of quartz')

# Now, define a couple of other loggers which might represent areas in your
# application:

logger1 = logging.getLogger('myapp.area1')
logger2 = logging.getLogger('myapp.area2')

logger1.debug('Quick zephyrs blow, vexing daft Jim.')
logger1.info('How quickly daft jumping zebras vex.')
logger2.warning('Jail zesty vixen who grabbed pay from quack.')
logger2.error('The five boxing wizards jump quickly.')
Beispiel #11
0
 def __init__(self, host, port, name, level):
     self.logger =   logging.getLogger(name)
     hdlr        =   handlers.SocketHandler(host, port)
     hdlr.setLevel(level)
     self.logger.addHandler(hdlr)
     self.logger.setLevel(level)