Python logging.INFO() Examples

The following are code examples for showing how to use logging.INFO(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: incubator-spot   Author: apache   File: utilities.py    Apache License 2.0 15 votes vote down vote up
def get_logger(cls,logger_name,create_file=False):

        # create logger for prd_ci
        log = logging.getLogger(logger_name)
        log.setLevel(level=logging.INFO)

        # create formatter and add it to the handlers
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        if create_file:
                # create file handler for logger.
                fh = logging.FileHandler('SPOT.log')
                fh.setLevel(level=logging.DEBUG)
                fh.setFormatter(formatter)
        # reate console handler for logger.
        ch = logging.StreamHandler()
        ch.setLevel(level=logging.DEBUG)
        ch.setFormatter(formatter)

        # add handlers to logger.
        if create_file:
            log.addHandler(fh)

        log.addHandler(ch)
        return  log 
Example 2
Project: mlbv   Author: kmac   File: util.py    GNU General Public License v3.0 11 votes vote down vote up
def init_logging(log_file=None, append=False, console_loglevel=logging.INFO):
    """Set up logging to file and console."""
    if log_file is not None:
        if append:
            filemode_val = 'a'
        else:
            filemode_val = 'w'
        logging.basicConfig(level=logging.DEBUG,
                            format="%(asctime)s %(levelname)s %(threadName)s %(name)s %(message)s",
                            # datefmt='%m-%d %H:%M',
                            filename=log_file,
                            filemode=filemode_val)
    # define a Handler which writes INFO messages or higher to the sys.stderr
    console = logging.StreamHandler()
    console.setLevel(console_loglevel)
    # set a format which is simpler for console use
    formatter = logging.Formatter("%(message)s")
    console.setFormatter(formatter)
    # add the handler to the root logger
    logging.getLogger('').addHandler(console)
    global LOG
    LOG = logging.getLogger(__name__) 
Example 3
Project: Hasami   Author: Lokraan   File: main.py    MIT License 7 votes vote down vote up
def setup_logging(config: dict) -> None:
	logging.getLogger("discord.http").setLevel(logging.WARNING)
	logging.getLogger("discord").setLevel(logging.INFO)

	logger = logging.getLogger()

	level = logging.DEBUG if config["debug"] else logging.INFO

	f_handler = logging.FileHandler(filename="hasami.log", encoding="utf-8", mode="w")
	cl_handler = logging.StreamHandler()

	dt_fmt = "%Y-%m-%d %H:%M:%S"
	out_fmt = "[{asctime}] [{levelname:<6}] {name}: {message}"
	logger_fmt = logging.Formatter(out_fmt, dt_fmt, style="{")

	cl_handler.setFormatter(logger_fmt)
	f_handler.setFormatter(logger_fmt)

	logger.addHandler(cl_handler)
	logger.addHandler(f_handler)
	logger.setLevel(level) 
Example 4
Project: incubator-spot   Author: apache   File: utils.py    Apache License 2.0 6 votes vote down vote up
def get_logger(cls, logger_name, create_file=False):

        # create logger for prd_ci
        log = logging.getLogger(logger_name)
        log.setLevel(level=logging.INFO)

        # create formatter and add it to the handlers
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

        if create_file:
            # create file handler for logger.
            fh = logging.FileHandler('oa.log')
            fh.setLevel(level=logging.DEBUG)
            fh.setFormatter(formatter)
        # reate console handler for logger.
        ch = logging.StreamHandler()
        ch.setLevel(level=logging.DEBUG)
        ch.setFormatter(formatter)

        # add handlers to logger.
        if create_file:
            log.addHandler(fh)

        log.addHandler(ch)
        return log 
Example 5
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_nested_explicit(self):
        # Logging levels in a nested namespace, all explicitly set.
        m = self.next_message

        INF = logging.getLogger("INF")
        INF.setLevel(logging.INFO)
        INF_ERR  = logging.getLogger("INF.ERR")
        INF_ERR.setLevel(logging.ERROR)

        # These should log.
        INF_ERR.log(logging.CRITICAL, m())
        INF_ERR.error(m())

        # These should not log.
        INF_ERR.warn(m())
        INF_ERR.info(m())
        INF_ERR.debug(m())

        self.assert_log_lines([
            ('INF.ERR', 'CRITICAL', '1'),
            ('INF.ERR', 'ERROR', '2'),
        ]) 
Example 6
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_nested_with_virtual_parent(self):
        # Logging levels when some parent does not exist yet.
        m = self.next_message

        INF = logging.getLogger("INF")
        GRANDCHILD = logging.getLogger("INF.BADPARENT.UNDEF")
        CHILD = logging.getLogger("INF.BADPARENT")
        INF.setLevel(logging.INFO)

        # These should log.
        GRANDCHILD.log(logging.FATAL, m())
        GRANDCHILD.info(m())
        CHILD.log(logging.FATAL, m())
        CHILD.info(m())

        # These should not log.
        GRANDCHILD.debug(m())
        CHILD.debug(m())

        self.assert_log_lines([
            ('INF.BADPARENT.UNDEF', 'CRITICAL', '1'),
            ('INF.BADPARENT.UNDEF', 'INFO', '2'),
            ('INF.BADPARENT', 'CRITICAL', '3'),
            ('INF.BADPARENT', 'INFO', '4'),
        ]) 
Example 7
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_config_9_ok(self):
        with captured_stdout() as output:
            self.apply_config(self.config9)
            logger = logging.getLogger("compiler.parser")
            #Nothing will be output since both handler and logger are set to WARNING
            logger.info(self.next_message())
            self.assert_log_lines([], stream=output)
            self.apply_config(self.config9a)
            #Nothing will be output since both handler is still set to WARNING
            logger.info(self.next_message())
            self.assert_log_lines([], stream=output)
            self.apply_config(self.config9b)
            #Message should now be output
            logger.info(self.next_message())
            self.assert_log_lines([
                ('INFO', '3'),
            ], stream=output) 
Example 8
Project: UR5_Controller   Author: tsinghua-rll   File: example_get_info.py    MIT License 6 votes vote down vote up
def main(ROBOT_HOST = "192.168.1.104"):

    keep_running = True

    logging.getLogger().setLevel(logging.INFO)
    api = HAPI(ROBOT_HOST)

    while True:
        time.sleep(0.5)
        ep = api.GetCurrentEndPos()
        ef = api.GetCurrentEndForce()
        print ("Current Tool Position=(x=%f, y=%f, z=%f), (w=%f, i=%f, j=%f, k=%f)" %
               (ep[0][0], ep[0][1], ep[0][2], ep[1][0], ep[1][1], ep[1][2], ep[1][3]))
        print ("Current Tool Force=(x=%f, y=%f, z=%f), (rx=%f, ry=%f, rz=%f)" %
               (ef[0], ef[1], ef[2], ef[3], ef[4], ef[5]))
        print ("") 
Example 9
Project: BASS   Author: Cisco-Talos   File: cmdline.py    GNU General Public License v2.0 6 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(description = "Bass")
    parser.add_argument("-v", "--verbose", action = "count", default = 0, help = "Increase verbosity")
    parser.add_argument("samples", metavar = "sample", nargs = "+", help = "Sample path") 

    args = parser.parse_args()

    try:
        loglevel = {
            0: logging.ERROR,
            1: logging.WARN,
            2: logging.INFO
        }[args.verbose]
    except KeyError:
        loglevel = logging.DEBUG

    logging.basicConfig(level = loglevel)
    logging.getLogger().setLevel(loglevel)

    return args 
Example 10
Project: BASS   Author: Cisco-Talos   File: whitelist.py    GNU General Public License v2.0 6 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(description = "Add samples to BASS whitelist")
    parser.add_argument("-v", "--verbose", action = "count", default = 0, help = "Increase verbosity")
    parser.add_argument("--url", type = str, default = "http://localhost:5000", help = "URL of BASS server")
    parser.add_argument("sample", help = "Whitelist sample")

    args = parser.parse_args()

    try:
        loglevel = {
            0: logging.ERROR,
            1: logging.WARN,
            2: logging.INFO}[args.verbose]
    except KeyError:
        loglevel = logging.DEBUG
    logging.basicConfig(level = loglevel)
    logging.getLogger().setLevel(loglevel)

    return args 
Example 11
Project: BASS   Author: Cisco-Talos   File: client.py    GNU General Public License v2.0 6 votes vote down vote up
def parse_args():
    parser = argparse.ArgumentParser(description = "Find common ngrams in binary files")
    parser.add_argument("-v", "--verbose", action = "count", default = 0, help = "Increase verbosity")
    parser.add_argument("--output", type = str, default = None, help = "Output to file instead of stdout")
    parser.add_argument("--url", type = str, default = "http://localhost:5000", help = "URL of BASS server")
    parser.add_argument("samples", metavar = "sample", nargs = "+", help = "Cluster samples")

    args = parser.parse_args()

    try:
        loglevel = {
            0: logging.ERROR,
            1: logging.WARN,
            2: logging.INFO}[args.verbose]
    except KeyError:
        loglevel = logging.DEBUG
    logging.basicConfig(level = loglevel)
    logging.getLogger().setLevel(loglevel)

    return args 
Example 12
Project: oeffis-paper   Author: djaffry   File: utils.py    MIT License 6 votes vote down vote up
def get_logger(name):
    """
    Get a preconfigured logger

    Example logging output
    2019-03-03 12:40:20,025 - INFO - __main__: Application start.sh!

    :param name: Logger name
    :return: preconfigured logger
    """
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    handler = logging.StreamHandler(sys.stdout)
    handler.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s:  %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger 
Example 13
Project: iSDX   Author: sdn-ixp   File: replay.py    Apache License 2.0 6 votes vote down vote up
def main(argv):
    logging.basicConfig(level=logging.INFO)

    log_history = LogHistory(argv.config, argv.flow_dir, argv.port_dir, int(argv.num_steps), debug=True)

    channel = "sdx_stats"
    address = "192.168.99.100"
    port = 6379
    db = 0

    publisher = Publisher(channel, address, port)

    log_replay = LogReplay(log_history, publisher, int(argv.timestep), debug=True)

    # start replay
    replay_thread = Thread(target=log_replay.start)
    replay_thread.daemon = True
    replay_thread.start()

    while replay_thread.is_alive():
        try:
            replay_thread.join(1)
        except KeyboardInterrupt:
            log_replay.stop() 
Example 14
Project: mmdetection   Author: open-mmlab   File: train.py    Apache License 2.0 6 votes vote down vote up
def get_root_logger(log_file=None, log_level=logging.INFO):
    logger = logging.getLogger('mmdet')
    # if the logger has been initialized, just return it
    if logger.hasHandlers():
        return logger

    logging.basicConfig(
        format='%(asctime)s - %(levelname)s - %(message)s', level=log_level)
    rank, _ = get_dist_info()
    if rank != 0:
        logger.setLevel('ERROR')
    elif log_file is not None:
        file_handler = logging.FileHandler(log_file, 'w')
        file_handler.setFormatter(
            logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        file_handler.setLevel(log_level)
        logger.addHandler(file_handler)

    return logger 
Example 15
Project: Price-prediction-and-recommendation-of-second-hand-housing-in-Shanghai   Author: tz28   File: __init__.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config_dict[config_name])

    # 初始化
    # db.init_app(app)

    # 蓝图
    from .views import main

    app.register_blueprint(main)

    # 其他

    # 日志
    handler = TimedRotatingFileHandler('app.log', when='D', backupCount=7, encoding='UTF-8')
    handler.setLevel(logging.INFO)
    logging_format = logging.Formatter(
        '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
    handler.setFormatter(logging_format)
    app.logger.addHandler(handler)

    return app 
Example 16
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: ui.py    MIT License 6 votes vote down vote up
def hidden_cursor(file):
    # The Windows terminal does not support the hide/show cursor ANSI codes,
    # even via colorama. So don't even try.
    if WINDOWS:
        yield
    # We don't want to clutter the output with control characters if we're
    # writing to a file, or if the user is running with --quiet.
    # See https://github.com/pypa/pip/issues/3418
    elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:
        yield
    else:
        file.write(HIDE_CURSOR)
        try:
            yield
        finally:
            file.write(SHOW_CURSOR) 
Example 17
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: ui.py    MIT License 6 votes vote down vote up
def open_spinner(message):
    # Interactive spinner goes directly to sys.stdout rather than being routed
    # through the logging system, but it acts like it has level INFO,
    # i.e. it's only displayed if we're at level INFO or better.
    # Non-interactive spinner goes through the logging system, so it is always
    # in sync with logging configuration.
    if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO:
        spinner = InteractiveSpinner(message)
    else:
        spinner = NonInteractiveSpinner(message)
    try:
        with hidden_cursor(sys.stdout):
            yield spinner
    except KeyboardInterrupt:
        spinner.finish("canceled")
        raise
    except Exception:
        spinner.finish("error")
        raise
    else:
        spinner.finish("done") 
Example 18
Project: oslodatascience-rl   Author: Froskekongen   File: common.py    MIT License 6 votes vote down vote up
def __init__(self, logfile, console=False, level=logging.INFO, name=None):
        self.logfile = logfile
        self.level = level
        if name is None: name = __name__
        self.logger = logging.getLogger(name)
        self.logger.setLevel(level)
        
        formatter = logging.Formatter('%(asctime)s;%(message)s')
        self.fh = logging.FileHandler(logfile)
        self.fh.setFormatter(formatter)
        self.logger.addHandler(self.fh)

        if console:
            self.ch = logging.StreamHandler()
            self.ch.setFormatter(formatter)
            self.logger.addHandler(self.ch) 
Example 19
Project: Graphlib   Author: HamletWantToCode   File: logger.py    MIT License 6 votes vote down vote up
def setup_logging(save_dir, log_config='logger/logger_config.json', default_level=logging.INFO):
    """
    Setup logging configuration
    """
    log_config = Path(log_config)
    if log_config.is_file():
        config = read_json(log_config)
        # modify logging paths based on run config
        for _, handler in config['handlers'].items():
            if 'filename' in handler:
                handler['filename'] = str(save_dir / handler['filename'])

        logging.config.dictConfig(config)
    else:
        print("Warning: logging configuration file is not found in {}.".format(log_config))
        logging.basicConfig(level=default_level) 
Example 20
Project: thingpin   Author: mgk   File: logger.py    MIT License 6 votes vote down vote up
def Logger(name='thingpin', level=logging.INFO, log_file=None):
    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.propagate = False

    if log_file is not None:
        handler = logging.handlers.RotatingFileHandler(
            log_file, maxBytes=10 * 1024 * 1024, backupCount=50)
        handler.setFormatter(logging.Formatter(
            '%(asctime)s %(name)s %(process)d %(levelname)s %(message)s'))
    else:
        handler = logging.StreamHandler(stream=sys.stdout)
        handler.setFormatter(logging.Formatter(
            '%(asctime)s %(name)s %(levelname)s %(message)s'))

    logger.addHandler(handler)
    return logger 
Example 21
Project: pnp   Author: HazardDede   File: pnp.py    MIT License 6 votes vote down vote up
def _setup_logging(*candidates, default_level=logging.INFO, env_key='PNP_LOG_CONF', verbose=False):
    """Setup logging configuration"""
    log_file_path = get_first_existing_file(*candidates)
    env_path = os.getenv(env_key, None)
    if env_path:
        log_file_path = env_path
    if log_file_path and os.path.exists(log_file_path):
        with open(log_file_path, 'rt') as fhandle:
            config = yaml.safe_load(fhandle.read())
        logging.config.dictConfig(config)
        logging.info("Logging loaded from: %s", log_file_path)
        if verbose:
            logging.getLogger().setLevel(logging.DEBUG)
    else:
        logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                            level=logging.DEBUG if verbose else default_level)
        logging.info("Logging loaded with basic configuration") 
Example 22
Project: django-qcloud-cos   Author: jasonham   File: utils.py    Apache License 2.0 6 votes vote down vote up
def get_logger(name='common', logfile=None):
    '''
    参数: name (str): logger name
        logfile (str): log file, 没有时使用stream handler
    返回:
        logger obj
    '''
    my_logger = logging.getLogger(name)
    my_logger.setLevel(logging.INFO)
    if logfile:
        handler = logging.FileHandler(logfile)
    else:
        handler = logging.StreamHandler()
    fmt = '%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s'
    formatter = logging.Formatter(fmt)
    handler.setFormatter(formatter)
    my_logger.addHandler(handler)
    # 阻止冒泡
    my_logger.propagate = False
    return my_logger 
Example 23
Project: fs_image   Author: facebookincubator   File: common.py    MIT License 5 votes vote down vote up
def init_logging(*, debug: bool=False):
    logging.basicConfig(
        format='%(levelname)s %(name)s %(asctime)s %(message)s',
        level=logging.DEBUG if debug else logging.INFO,
    ) 
Example 24
Project: fs_image   Author: facebookincubator   File: btrfs_loopback.py    MIT License 5 votes vote down vote up
def _create_or_resize_image_file(
    path: bytes, at_least_bytes: int, log_level: int=logging.INFO,
):
    '''
    Be sure to call `btrfs filesystem resize` and `losetup --set-capacity`
    in the appropriate order.
    '''
    rounded_bytes = _round_to_loop_block_size(at_least_bytes, log_level)
    run_stdout_to_err([
        'truncate', '-s', str(rounded_bytes), path,
    ], check=True) 
Example 25
Project: leapp-repository   Author: oamg   File: ntp2chrony.py    Apache License 2.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description="Convert ntp configuration to chrony.")
    parser.add_argument("-r", "--root", dest="roots", default=["/"], nargs="+",
                        metavar="DIR", help="specify root directory (default /)")
    parser.add_argument("--ntp-conf", action="store", default="/etc/ntp.conf",
                        metavar="FILE", help="specify ntp config (default /etc/ntp.conf)")
    parser.add_argument("--step-tickers", action="store", default="",
                        metavar="FILE", help="specify ntpdate step-tickers config (no default)")
    parser.add_argument("--chrony-conf", action="store", default="/etc/chrony.conf",
                        metavar="FILE", help="specify chrony config (default /etc/chrony.conf)")
    parser.add_argument("--chrony-keys", action="store", default="/etc/chrony.keys",
                        metavar="FILE", help="specify chrony keyfile (default /etc/chrony.keys)")
    parser.add_argument("-b", "--backup", action="store_true", help="backup existing configs before writing")
    parser.add_argument("-L", "--ignored-lines", action="store_true", help="print ignored lines")
    parser.add_argument("-D", "--ignored-directives", action="store_true",
                        help="print names of ignored directives")
    parser.add_argument("-n", "--dry-run", action="store_true", help="don't make any changes")
    parser.add_argument("-v", "--verbose", action="count", default=0, help="increase verbosity")

    args = parser.parse_args()

    logging.basicConfig(format="%(message)s",
                        level=[logging.ERROR, logging.INFO, logging.DEBUG][min(args.verbose, 2)])

    for root in args.roots:
        conf = NtpConfiguration(root, args.ntp_conf, args.step_tickers)

        if args.ignored_lines:
            for line in conf.ignored_lines:
                print(line)

        if args.ignored_directives:
            for directive in conf.ignored_directives:
                print(directive)

        conf.write_chrony_configuration(args.chrony_conf, args.chrony_keys, args.dry_run, args.backup) 
Example 26
Project: incubator-spot   Author: apache   File: utils.py    Apache License 2.0 5 votes vote down vote up
def get_logger(cls, name, level='INFO', filepath=None, fmt=None):
        '''
            Return a new logger or an existing one, if any.

        :param cls     : The class as implicit first argument.
        :param name    : Return a logger with the specified name.
        :param filepath: Path of the file, where logs will be saved. If it is not set,
                         redirects the log stream to `sys.stdout`.
        :param fmt     : A format string for the message as a whole, as well as a format
                         string for the date/time portion of the message.
                         Default: '%(asctime)s %(levelname)-8s %(name)-34s %(message)s'
        :rtype         : :class:`logging.Logger`
        '''
        logger = logging.getLogger(name)
        # .............................if logger already exists, return it
        if logger.handlers: return logger

        if filepath:
            # .........................rotate log file (1 rotation per 512KB
            handler  = RotatingFileHandler(filepath, maxBytes=524288, backupCount=8)
        else:
            handler  = logging.StreamHandler(sys.stdout)

        fmt = fmt or '%(asctime)s %(levelname)-8s %(name)-34s %(message)s'
        handler.setFormatter(logging.Formatter(fmt))

        try:
            logger.setLevel(getattr(logging, level.upper() if level else 'INFO'))
        except: logger.setLevel(logging.INFO)

        logger.addHandler(handler)
        return logger 
Example 27
Project: ubittool   Author: carlosperate   File: gui.py    MIT License 5 votes vote down vote up
def activate(self):
        """Configure std out/in to send to write to the console text widget."""
        sys.stdout = StdoutRedirector(self, text_color="#0D4")
        sys.stderr = StdoutRedirector(self, text_color="#D00")
        logger = logging.getLogger()
        logger.setLevel(level=logging.INFO)
        logging_handler_out = logging.StreamHandler(sys.stdout)
        logging_handler_out.setLevel(logging.INFO)
        logger.addHandler(logging_handler_out)
        logging_handler_err = logging.StreamHandler(sys.stderr)
        logging_handler_err.setLevel(logging.WARNING)
        logger.addHandler(logging_handler_err) 
Example 28
Project: tom-bot   Author: maartenberg   File: system_plugin.py    MIT License 5 votes vote down vote up
def loginfo_cb(bot, message=None, *args, **kwargs):
    ''' Temporarily (re)set the loglevel to info. '''
    if message:
        if not isadmin(bot, message):
            return 'Not authorized.'
    logging.getLogger().setLevel(logging.INFO)
    return 'Ok.' 
Example 29
Project: pyblish-win   Author: pyblish   File: driver.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def main(*args):
    """Main program, when run as a script: produce grammar pickle files.

    Calls load_grammar for each argument, a path to a grammar text file.
    """
    if not args:
        args = sys.argv[1:]
    logging.basicConfig(level=logging.INFO, stream=sys.stdout,
                        format='%(message)s')
    for gt in args:
        load_grammar(gt, save=True, force=True)
    return True 
Example 30
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, appname, dllname=None, logtype="Application"):
        logging.Handler.__init__(self)
        try:
            import win32evtlogutil, win32evtlog
            self.appname = appname
            self._welu = win32evtlogutil
            if not dllname:
                dllname = os.path.split(self._welu.__file__)
                dllname = os.path.split(dllname[0])
                dllname = os.path.join(dllname[0], r'win32service.pyd')
            self.dllname = dllname
            self.logtype = logtype
            self._welu.AddSourceToRegistry(appname, dllname, logtype)
            self.deftype = win32evtlog.EVENTLOG_ERROR_TYPE
            self.typemap = {
                logging.DEBUG   : win32evtlog.EVENTLOG_INFORMATION_TYPE,
                logging.INFO    : win32evtlog.EVENTLOG_INFORMATION_TYPE,
                logging.WARNING : win32evtlog.EVENTLOG_WARNING_TYPE,
                logging.ERROR   : win32evtlog.EVENTLOG_ERROR_TYPE,
                logging.CRITICAL: win32evtlog.EVENTLOG_ERROR_TYPE,
         }
        except ImportError:
            print("The Python Win32 extensions for NT (service, event "\
                        "logging) appear not to be available.")
            self._welu = None 
Example 31
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getEventType(self, record):
        """
        Return the event type for the record.

        Override this if you want to specify your own types. This version does
        a mapping using the handler's typemap attribute, which is set up in
        __init__() to a dictionary which contains mappings for DEBUG, INFO,
        WARNING, ERROR and CRITICAL. If you are using your own levels you will
        either need to override this method or place a suitable dictionary in
        the handler's typemap attribute.
        """
        return self.typemap.get(record.levelno, self.deftype) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_filter(self):
        # Only messages satisfying the specified criteria pass through the
        #  filter.
        filter_ = logging.Filter("spam.eggs")
        handler = self.root_logger.handlers[0]
        try:
            handler.addFilter(filter_)
            spam = logging.getLogger("spam")
            spam_eggs = logging.getLogger("spam.eggs")
            spam_eggs_fish = logging.getLogger("spam.eggs.fish")
            spam_bakedbeans = logging.getLogger("spam.bakedbeans")

            spam.info(self.next_message())
            spam_eggs.info(self.next_message())  # Good.
            spam_eggs_fish.info(self.next_message())  # Good.
            spam_bakedbeans.info(self.next_message())

            self.assert_log_lines([
                ('spam.eggs', 'INFO', '2'),
                ('spam.eggs.fish', 'INFO', '3'),
            ])
        finally:
            handler.removeFilter(filter_)


#
#   First, we define our levels. There can be as many as you want - the only
#     limitations are that they should be integers, the lowest should be > 0 and
#   larger values mean less information being logged. If you need specific
#   level values which do not fit into these limitations, you can use a
#   mapping dictionary to convert between your application levels and the
#   logging system.
# 
Example 33
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_flush(self):
        # The memory handler flushes to its target handler based on specific
        #  criteria (message count and message level).
        self.mem_logger.debug(self.next_message())
        self.assert_log_lines([])
        self.mem_logger.info(self.next_message())
        self.assert_log_lines([])
        # This will flush because the level is >= logging.WARNING
        self.mem_logger.warn(self.next_message())
        lines = [
            ('DEBUG', '1'),
            ('INFO', '2'),
            ('WARNING', '3'),
        ]
        self.assert_log_lines(lines)
        for n in (4, 14):
            for i in range(9):
                self.mem_logger.debug(self.next_message())
            self.assert_log_lines(lines)
            # This will flush because it's the 10th message since the last
            #  flush.
            self.mem_logger.debug(self.next_message())
            lines = lines + [('DEBUG', str(i)) for i in range(n, n + 10)]
            self.assert_log_lines(lines)

        self.mem_logger.debug(self.next_message())
        self.assert_log_lines(lines) 
Example 34
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_config1_ok(self, config=config1):
        # A config file defining a sub-parser as well.
        with captured_stdout() as output:
            self.apply_config(config)
            logger = logging.getLogger("compiler.parser")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            self.assert_log_lines([
                ('INFO', '1'),
                ('ERROR', '2'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([]) 
Example 35
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_config1_ok(self, config=config1):
        # A config defining a sub-parser as well.
        with captured_stdout() as output:
            self.apply_config(config)
            logger = logging.getLogger("compiler.parser")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            self.assert_log_lines([
                ('INFO', '1'),
                ('ERROR', '2'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([]) 
Example 36
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_config7_ok(self):
        with captured_stdout() as output:
            self.apply_config(self.config1)
            logger = logging.getLogger("compiler.parser")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            self.assert_log_lines([
                ('INFO', '1'),
                ('ERROR', '2'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([])
        with captured_stdout() as output:
            self.apply_config(self.config7)
            logger = logging.getLogger("compiler.parser")
            self.assertTrue(logger.disabled)
            logger = logging.getLogger("compiler.lexer")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            self.assert_log_lines([
                ('INFO', '3'),
                ('ERROR', '4'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([])

    #Same as test_config_7_ok but don't disable old loggers. 
Example 37
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_config_8_ok(self):
        with captured_stdout() as output:
            self.apply_config(self.config1)
            logger = logging.getLogger("compiler.parser")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            self.assert_log_lines([
                ('INFO', '1'),
                ('ERROR', '2'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([])
        with captured_stdout() as output:
            self.apply_config(self.config8)
            logger = logging.getLogger("compiler.parser")
            self.assertFalse(logger.disabled)
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            logger = logging.getLogger("compiler.lexer")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            self.assert_log_lines([
                ('INFO', '3'),
                ('ERROR', '4'),
                ('INFO', '5'),
                ('ERROR', '6'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([]) 
Example 38
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_listen_config_1_ok(self):
        with captured_stdout() as output:
            self.setup_via_listener(textwrap.dedent(ConfigFileTest.config1))
            logger = logging.getLogger("compiler.parser")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            self.assert_log_lines([
                ('INFO', '1'),
                ('ERROR', '2'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([]) 
Example 39
Project: drydock   Author: airshipit   File: base.py    Apache License 2.0 5 votes vote down vote up
def info(self, ctx, msg):
        self.log_error(ctx, logging.INFO, msg) 
Example 40
Project: UR5_Controller   Author: tsinghua-rll   File: example_teach.py    MIT License 5 votes vote down vote up
def main(ROBOT_HOST = "192.168.1.104"):

    keep_running = True

    logging.getLogger().setLevel(logging.INFO)
    api = HAPI(ROBOT_HOST)

    print ("Lets start teaching")
    caps = api.RecordingActions()

    # control loop
    while keep_running:
        print ("Now, lets replay the record")
        api.ReplayCapturedData(caps, with_time=True)
        time.sleep(3) 
Example 41
Project: UR5_Controller   Author: tsinghua-rll   File: example_running_script.py    MIT License 5 votes vote down vote up
def main(ROBOT_HOST = "192.168.1.104"):

    keep_running = True

    logging.getLogger().setLevel(logging.INFO)
    api = API(ROBOT_HOST)

    scripy_path = "./hammer.script"
    print ("Now start running script")
    api.run_script(scripy_path)
    # sleep for 5 min to keep script running
    if keep_running:
        time.sleep(300) 
Example 42
Project: UR5_Controller   Author: tsinghua-rll   File: demo_ori.py    MIT License 5 votes vote down vote up
def main():
    keep_running = True

    logging.getLogger().setLevel(logging.INFO)
    api = HAPI("192.168.1.104")

    api.set_coordinate_origin((0.46945, -0.00105, 0.04308))

    api.MoveEndPointToPosition(pos=(0.0, 0.0, 0.0),
                               rotation=(2.2144, -2.2144, 0))
    while not api.isLastMovementEnd():
        time.sleep(0.5)
    time.sleep(2)
    api.FineTuningPosition(interactive=True, add_value=(0.0005, 0.0005, 0.0005, 0.001, 0.001, 0.001), factor=10.0) 
Example 43
Project: UR5_Controller   Author: tsinghua-rll   File: example_force.py    MIT License 5 votes vote down vote up
def main(ROBOT_HOST = "192.168.1.104"):

    keep_running = True

    logging.getLogger().setLevel(logging.INFO)
    api = HAPI(ROBOT_HOST)

    api.MoveEndPointToPosition(pos=(0.5774472131510267, -0.11612032542570545, 0.21002231707422814),
                               rotation=(2.2558090087495724, -2.1853634973877805, 0.016568855033798274))

    while not api.isLastMovementEnd():
        time.sleep(0.5)
    time.sleep(2)
    print ("Start force mode, hand will give a 10N force toward ground")
    api.switch_mode(direct_mode=False)
    for _ in range(3):
        api.ForceMode(selection=(0, 0, 1, 0, 0, 0), wrench=(0, 0, -10.0, 0, 0, 0), limits=(0.5, 0.5, 20.0, 0.5, 0.5, 0.5), duration=0)
        api.MoveEndPointToPosition(pos=(0.6774472131510267, -0.11612032542570545, 0.21002231707422814), v=0.05)
        api.MoveEndPointToPosition(pos=(0.4774472131510267, -0.11612032542570545, 0.21002231707422814), v=0.05)
        api.Sleep(5.0)
        api.run_buffer()
        print ("1 Loop End")
        time.sleep(5)

    print ("End force mode")
    api.switch_mode(direct_mode=True)
    api.EndForceMode() 
Example 44
Project: UR5_Controller   Author: tsinghua-rll   File: example_keypad_control.py    MIT License 5 votes vote down vote up
def main(ROBOT_HOST = "192.168.1.104"):

    keep_running = True

    logging.getLogger().setLevel(logging.INFO)
    api = HAPI(ROBOT_HOST)
    api.MoveEndPointToPosition(pos=(0.5774472131510267, -0.11612032542570545, 0.21002231707422814),
                               rotation=(2.2558090087495724, -2.1853634973877805, 0.016568855033798274))
    while not api.isLastMovementEnd():
        time.sleep(0.5)
    time.sleep(2)
    api.FineTuningPosition(interactive=True, add_value=(0.0005, 0.0005, 0.0005, 0.0001, 0.0001, 0.0001), factor=50.0) 
Example 45
Project: UR5_Controller   Author: tsinghua-rll   File: exaple_change_coordinate.py    MIT License 5 votes vote down vote up
def main(ROBOT_HOST = "192.168.1.104"):

    keep_running = True

    logging.getLogger().setLevel(logging.INFO)
    api = HAPI(ROBOT_HOST)

    api.set_coordinate_origin((0.5774, -0.1161, 0.2100))

    api.MoveEndPointToPosition(pos=(0.0, 0.0, 0.0),
                               rotation=(2.2144, -2.2144, 0))
    while not api.isLastMovementEnd():
        time.sleep(0.5)
    time.sleep(2)
    api.FineTuningPosition(interactive=True, add_value=(0.0005, 0.0005, 0.0005, 0.001, 0.001, 0.001), factor=50.0) 
Example 46
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: _internal.py    Apache License 2.0 5 votes vote down vote up
def _log(type, message, *args, **kwargs):
    """Log into the internal werkzeug logger."""
    global _logger
    if _logger is None:
        import logging
        _logger = logging.getLogger('werkzeug')
        # Only set up a default log handler if the
        # end-user application didn't set anything up.
        if not logging.root.handlers and _logger.level == logging.NOTSET:
            _logger.setLevel(logging.INFO)
            handler = logging.StreamHandler()
            _logger.addHandler(handler)
    getattr(_logger, type)(message.rstrip(), *args, **kwargs) 
Example 47
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: _internal.py    Apache License 2.0 5 votes vote down vote up
def _log(type, message, *args, **kwargs):
    """Log into the internal werkzeug logger."""
    global _logger
    if _logger is None:
        import logging
        _logger = logging.getLogger('werkzeug')
        # Only set up a default log handler if the
        # end-user application didn't set anything up.
        if not logging.root.handlers and _logger.level == logging.NOTSET:
            _logger.setLevel(logging.INFO)
            handler = logging.StreamHandler()
            _logger.addHandler(handler)
    getattr(_logger, type)(message.rstrip(), *args, **kwargs) 
Example 48
Project: prediction-constrained-topic-models   Author: dtak   File: pprint_logging.py    MIT License 5 votes vote down vote up
def pprint(msg_str='', level=logging.INFO):
    global RootLog
    if RootLog is None:
        print msg_str
    else:
        RootLog.log(level, msg_str) 
Example 49
Project: rubbish.py   Author: alphapapa   File: rubbish.py    GNU General Public License v3.0 5 votes vote down vote up
def cli(verbose):

    # Setup logging
    if verbose >= 2:
        LOG_LEVEL = log.DEBUG
    elif verbose == 1:
        LOG_LEVEL = log.INFO
    else:
        LOG_LEVEL = log.WARNING

    log.basicConfig(level=LOG_LEVEL, format="%(levelname)s: %(message)s")

# * Commands

# ** empty 
Example 50
Project: ieml   Author: IEMLdev   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def error(m):
    logger.error(m)
    print(m, file=stderr)

# logger.setLevel(logging.INFO) 
Example 51
Project: shaptools   Author: SUSE   File: shell_test.py    Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        """
        Global setUp.
        """

        logging.basicConfig(level=logging.INFO) 
Example 52
Project: shaptools   Author: SUSE   File: netweaver_test.py    Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        """
        Global setUp.
        """

        logging.basicConfig(level=logging.INFO) 
Example 53
Project: shaptools   Author: SUSE   File: hana_test.py    Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        """
        Global setUp.
        """

        logging.basicConfig(level=logging.INFO) 
Example 54
Project: shaptools   Author: SUSE   File: init_test.py    Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        """
        Global setUp.
        """

        logging.basicConfig(level=logging.INFO) 
Example 55
Project: shaptools   Author: SUSE   File: pyhdb_connector_test.py    Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        """
        Global setUp.
        """

        logging.basicConfig(level=logging.INFO)
        sys.modules['pyhdb'] = mock.Mock()
        from shaptools.hdb_connector.connectors import pyhdb_connector
        cls._pyhdb_connector = pyhdb_connector 
Example 56
Project: shaptools   Author: SUSE   File: base_connect_test.py    Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        """
        Global setUp.
        """

        logging.basicConfig(level=logging.INFO)
        sys.modules['hdbcli'] = mock.Mock()
        sys.modules['pyhdb'] = mock.Mock()

        from shaptools.hdb_connector.connectors import base_connector
        cls._base_connector = base_connector 
Example 57
Project: shaptools   Author: SUSE   File: dbapi_connector_test.py    Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        """
        Global setUp.
        """

        logging.basicConfig(level=logging.INFO)
        sys.modules['hdbcli'] = mock.Mock()
        from shaptools.hdb_connector.connectors import dbapi_connector
        cls._dbapi_connector = dbapi_connector 
Example 58
Project: code2pdf   Author: tushar-rishav   File: code2pdf.py    MIT License 5 votes vote down vote up
def logger(func):
    def log_wrap(self, ifile=None, ofile=None, size="A4"):
        logging.getLogger().name = "code2pdf> "
        logging.getLogger().setLevel(logging.INFO)
        func(self, ifile, ofile, size)
    return log_wrap 
Example 59
Project: utilities   Author: czbiohub   File: log_util.py    MIT License 5 votes vote down vote up
def get_logger(name, debug=False, dryrun=False):
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)

    # create a logging format
    if dryrun:
        formatter = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s - (DRYRUN) - %(message)s"
        )
    else:
        formatter = logging.Formatter(
            "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
        )

    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.DEBUG if debug else logging.INFO)
    stream_handler.setFormatter(formatter)

    logger.addHandler(stream_handler)

    if os.environ.get("AWS_BATCH_JOB_ID"):
        log_file = os.path.abspath("{}.log".format(os.environ["AWS_BATCH_JOB_ID"]))
        file_handler = logging.FileHandler(log_file)
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)

        # add the handlers to the logger
        logger.addHandler(file_handler)
    else:
        log_file = None
        file_handler = None

    return logger, log_file, file_handler 
Example 60
Project: rnm   Author: alexjaw   File: service.py    MIT License 5 votes vote down vote up
def test_me():
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    logger.info('------------- Starting test... -------------')

    ap = AccessPoint()
    dhcp = DHCP()

    resp = ap.status()
    logger.info(repr(resp))

    resp = dhcp.status()
    logger.info(repr(resp))

    logger.info('-------------    Finished      -------------') 
Example 61
Project: rnm   Author: alexjaw   File: rnm.py    MIT License 5 votes vote down vote up
def test_me():
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    logger.info('------------- Starting test... -------------')

    wifi = WiFi()
    ap = AccessPoint()
    dhcp = DHCP()

    logger.info('-------------    Finished      -------------') 
Example 62
Project: neural-fingerprinting   Author: StephanZheng   File: run_multigpu.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_trainer(hparams):
    logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)

    if 'multigpu' in hparams.attack_type_train:
        logging.info('Multi GPU Trainer.')
        trainer = TrainerMultiGPU(hparams)
    else:
        logging.info('Single GPU Trainer.')
        trainer = TrainerSingleGPU(hparams)
    trainer.model_train()
    trainer.eval(inc_epoch=False)

    return trainer.finish() 
Example 63
Project: chess-chiller   Author: fsmosca   File: chess-chiller.py    GNU General Public License v3.0 5 votes vote down vote up
def initialize_logger(logger_level):
    """ Save logs to file, use RotatingFileHandler to avoid disk space overrun """
    logger = logging.getLogger()
    logger.setLevel(logger_level)
     
    # Creates console handler for info/warning/error/critical logs
    handler = logging.StreamHandler()
    handler.setLevel(logging.INFO)
    formatter = logging.Formatter("%(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
 
    # Creates error/critical file handler
    handler = RotatingFileHandler("error.log", mode='w',
                                  maxBytes=5000000, backupCount=5)  
    handler.setLevel(logging.ERROR)
    formatter = logging.Formatter("%(asctime)s [%(threadName)-10.10s] [%(funcName)-12.12s] [%(levelname)-5.5s] > %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler)
 
    # Creates debug/info/warning/error/critical file handler
    handler = RotatingFileHandler("all.log", mode='w',
                                  maxBytes=5000000, backupCount=5)   
    handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s [%(threadName)-10.10s] [%(funcName)-12.12s] [%(levelname)-5.5s] > %(message)s")
    handler.setFormatter(formatter)
    logger.addHandler(handler) 
Example 64
Project: mlimages   Author: icoxfog417   File: log_api.py    MIT License 5 votes vote down vote up
def _bool_2_level(boolean):
    level = INFO if not boolean else DEBUG
    return level 
Example 65
Project: MusicDownloader   Author: wwwpf   File: utils.py    GNU General Public License v3.0 5 votes vote down vote up
def init_logging():
    FILE_NAME = "log.txt"
    file_handler = logging.FileHandler(FILE_NAME, encoding="utf-8")
    FORMAT = "%(asctime)s %(filename)s[line:%(lineno)d]\t"\
        "%(levelname)s\t%(message)s"
    logging.basicConfig(handlers=[file_handler],
                        level=logging.INFO, format=FORMAT) 
Example 66
Project: aws-auto-remediate   Author: servian   File: lambda_handler.py    GNU General Public License v3.0 5 votes vote down vote up
def lambda_handler(event, context):
    loggger = logging.getLogger()

    if loggger.handlers:
        for handler in loggger.handlers:
            loggger.removeHandler(handler)

    # change logging levels for boto and others to prevent log spamming
    logging.getLogger("boto3").setLevel(logging.ERROR)
    logging.getLogger("botocore").setLevel(logging.ERROR)
    logging.getLogger("urllib3").setLevel(logging.ERROR)

    # set logging format
    logging.basicConfig(
        format="[%(levelname)s] %(message)s (%(filename)s, %(funcName)s(), line %(lineno)d)",
        level=os.environ.get("LOGLEVEL", "WARNING"),
    )

    # add SNS logger
    # sns_logger = SNSLoggingHandler(os.environ.get('LOGTOPIC'))
    # sns_logger.setLevel(logging.INFO)
    # loggger.addHandler(sns_logger)

    # instantiate class
    remediate = Remediate(logging, event)

    # run functions
    remediate.remediate() 
Example 67
Project: models   Author: kipoi   File: test_all_models.py    MIT License 5 votes vote down vote up
def test_model(model_name, caplog):
    """kipoi test ...
    """
    caplog.set_level(logging.INFO)

    source_name = "kipoi"
    assert source_name == "kipoi"

    env_name = conda_env_name(model_name, model_name, source_name)
    env_name = "test-" + env_name  # prepend "test-"

    # if environment already exists, remove it
    if env_exists(env_name):
        print("Removing the environment: {0}".format(env_name))
        remove_env(env_name)

    # create the model test environment
    args = ["kipoi", "env", "create",
            "--source", source_name,
            "--env", env_name,
            model_name]
    returncode = subprocess.call(args=args)
    assert returncode == 0

    if model_name == "basenji":
        batch_size = str(2)
    else:
        batch_size = str(4)

    # run the tests in the environment
    args = [get_kipoi_bin(env_name), "test",
            "--batch_size", batch_size,
            "--source", source_name,
            model_name]
    returncode = subprocess.call(args=args)
    assert returncode == 0

    for record in caplog.records:
        # there shoudn't be any warning
        assert record.levelname not in ['WARN', 'WARNING', 'ERROR', 'CRITICAL'] 
Example 68
Project: spleeter   Author: deezer   File: logging.py    MIT License 5 votes vote down vote up
def get_logger():
    """ Returns library scoped logger.

    :returns: Library logger.
    """
    if _LoggerHolder.INSTANCE is None:
        formatter = logging.Formatter(_FORMAT)
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)
        logger = logging.getLogger('spleeter')
        logger.addHandler(handler)
        logger.setLevel(logging.INFO)
        _LoggerHolder.INSTANCE = logger
    return _LoggerHolder.INSTANCE 
Example 69
Project: spleeter   Author: deezer   File: logging.py    MIT License 5 votes vote down vote up
def enable_tensorflow_logging():
    """ Enable tensorflow logging. """
    environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
    tf_logger = get_tensorflow_logger()
    tf_logger.set_verbosity(tf_logger.INFO)
    logger = get_logger()
    logger.setLevel(logging.DEBUG) 
Example 70
Project: flasky   Author: RoseOu   File: log.py    MIT License 5 votes vote down vote up
def class_logger(cls):
    logger = logging.getLogger(cls.__module__ + "." + cls.__name__)
    cls._should_log_debug = lambda self: logger.isEnabledFor(logging.DEBUG)
    cls._should_log_info = lambda self: logger.isEnabledFor(logging.INFO)
    cls.logger = logger
    _logged_classes.add(cls)
    return cls 
Example 71
Project: flasky   Author: RoseOu   File: log.py    MIT License 5 votes vote down vote up
def _should_log_info(self):
        return self.logger.isEnabledFor(logging.INFO) 
Example 72
Project: flasky   Author: RoseOu   File: log.py    MIT License 5 votes vote down vote up
def __init__(self, echo, name):
        self.echo = echo
        self.logger = logging.getLogger(name)

        # if echo flag is enabled and no handlers,
        # add a handler to the list
        if self._echo_map[echo] <= logging.INFO \
           and not self.logger.handlers:
            _add_default_handler(self.logger)

    #
    # Boilerplate convenience methods
    # 
Example 73
Project: flasky   Author: RoseOu   File: log.py    MIT License 5 votes vote down vote up
def info(self, msg, *args, **kwargs):
        """Delegate an info call to the underlying logger."""

        self.log(logging.INFO, msg, *args, **kwargs) 
Example 74
Project: flasky   Author: RoseOu   File: plugin_base.py    MIT License 5 votes vote down vote up
def _log(opt_str, value, parser):
    global logging
    if not logging:
        import logging
        logging.basicConfig()

    if opt_str.endswith('-info'):
        logging.getLogger(value).setLevel(logging.INFO)
    elif opt_str.endswith('-debug'):
        logging.getLogger(value).setLevel(logging.DEBUG) 
Example 75
Project: alfred-yubikey-otp   Author: robertoriv   File: workflow.py    MIT License 4 votes vote down vote up
def logger(self):
        """Logger that logs to both console and a log file.

        If Alfred's debugger is open, log level will be ``DEBUG``,
        else it will be ``INFO``.

        Use :meth:`open_log` to open the log file in Console.

        :returns: an initialised :class:`~logging.Logger`

        """
        if self._logger:
            return self._logger

        # Initialise new logger and optionally handlers
        logger = logging.getLogger('')

        # Only add one set of handlers
        # Exclude from coverage, as pytest will have configured the
        # root logger already
        if not len(logger.handlers):  # pragma: no cover

            fmt = logging.Formatter(
                '%(asctime)s %(filename)s:%(lineno)s'
                ' %(levelname)-8s %(message)s',
                datefmt='%H:%M:%S')

            logfile = logging.handlers.RotatingFileHandler(
                self.logfile,
                maxBytes=1024 * 1024,
                backupCount=1)
            logfile.setFormatter(fmt)
            logger.addHandler(logfile)

            console = logging.StreamHandler()
            console.setFormatter(fmt)
            logger.addHandler(console)

        if self.debugging:
            logger.setLevel(logging.DEBUG)
        else:
            logger.setLevel(logging.INFO)

        self._logger = logger

        return self._logger 
Example 76
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_flat(self):
        #Logging levels in a flat logger namespace.
        m = self.next_message

        ERR = logging.getLogger("ERR")
        ERR.setLevel(logging.ERROR)
        INF = logging.getLogger("INF")
        INF.setLevel(logging.INFO)
        DEB = logging.getLogger("DEB")
        DEB.setLevel(logging.DEBUG)

        # These should log.
        ERR.log(logging.CRITICAL, m())
        ERR.error(m())

        INF.log(logging.CRITICAL, m())
        INF.error(m())
        INF.warn(m())
        INF.info(m())

        DEB.log(logging.CRITICAL, m())
        DEB.error(m())
        DEB.warn (m())
        DEB.info (m())
        DEB.debug(m())

        # These should not log.
        ERR.warn(m())
        ERR.info(m())
        ERR.debug(m())

        INF.debug(m())

        self.assert_log_lines([
            ('ERR', 'CRITICAL', '1'),
            ('ERR', 'ERROR', '2'),
            ('INF', 'CRITICAL', '3'),
            ('INF', 'ERROR', '4'),
            ('INF', 'WARNING', '5'),
            ('INF', 'INFO', '6'),
            ('DEB', 'CRITICAL', '7'),
            ('DEB', 'ERROR', '8'),
            ('DEB', 'WARNING', '9'),
            ('DEB', 'INFO', '10'),
            ('DEB', 'DEBUG', '11'),
        ]) 
Example 77
Project: pyblish-win   Author: pyblish   File: test_logging.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_config7_ok(self):
        with captured_stdout() as output:
            self.apply_config(self.config1a)
            logger = logging.getLogger("compiler.parser")
            # See issue #11424. compiler-hyphenated sorts
            # between compiler and compiler.xyz and this
            # was preventing compiler.xyz from being included
            # in the child loggers of compiler because of an
            # overzealous loop termination condition.
            hyphenated = logging.getLogger('compiler-hyphenated')
            # All will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            hyphenated.critical(self.next_message())
            self.assert_log_lines([
                ('INFO', '1'),
                ('ERROR', '2'),
                ('CRITICAL', '3'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([])
        with captured_stdout() as output:
            self.apply_config(self.config7)
            logger = logging.getLogger("compiler.parser")
            self.assertFalse(logger.disabled)
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            logger = logging.getLogger("compiler.lexer")
            # Both will output a message
            logger.info(self.next_message())
            logger.error(self.next_message())
            # Will not appear
            hyphenated.critical(self.next_message())
            self.assert_log_lines([
                ('INFO', '4'),
                ('ERROR', '5'),
                ('INFO', '6'),
                ('ERROR', '7'),
            ], stream=output)
            # Original logger output is empty.
            self.assert_log_lines([]) 
Example 78
Project: wechat-alfred-workflow   Author: TKkk-iOSer   File: workflow.py    MIT License 4 votes vote down vote up
def logger(self):
        """Logger that logs to both console and a log file.

        If Alfred's debugger is open, log level will be ``DEBUG``,
        else it will be ``INFO``.

        Use :meth:`open_log` to open the log file in Console.

        :returns: an initialised :class:`~logging.Logger`

        """
        if self._logger:
            return self._logger

        # Initialise new logger and optionally handlers
        logger = logging.getLogger('')

        # Only add one set of handlers
        # Exclude from coverage, as pytest will have configured the
        # root logger already
        if not len(logger.handlers):  # pragma: no cover

            fmt = logging.Formatter(
                '%(asctime)s %(filename)s:%(lineno)s'
                ' %(levelname)-8s %(message)s',
                datefmt='%H:%M:%S')

            logfile = logging.handlers.RotatingFileHandler(
                self.logfile,
                maxBytes=1024 * 1024,
                backupCount=1)
            logfile.setFormatter(fmt)
            logger.addHandler(logfile)

            console = logging.StreamHandler()
            console.setFormatter(fmt)
            logger.addHandler(console)

        if self.debugging:
            logger.setLevel(logging.DEBUG)
        else:
            logger.setLevel(logging.INFO)

        self._logger = logger

        return self._logger 
Example 79
Project: Graphlib   Author: HamletWantToCode   File: parse_config.py    MIT License 4 votes vote down vote up
def __init__(self, args, options='', timestamp=True):
        # parse default and custom cli options
        for opt in options:
            args.add_argument(*opt.flags, default=None, type=opt.type)
        args = args.parse_args()

        if args.device:
            os.environ["CUDA_VISIBLE_DEVICES"] = args.device
        if args.resume:
            self.resume = Path(args.resume)
            self.cfg_fname = self.resume.parent / 'config.json'
        else:
            msg_no_cfg = "Configuration file need to be specified. Add '-c config.json', for example."
            assert args.config is not None, msg_no_cfg
            self.resume = None
            self.cfg_fname = Path(args.config)

        # load config file and apply custom cli options
        config = read_json(self.cfg_fname)
        self._config = _update_config(config, options, args)

        # set save_dir where trained model and log will be saved.
        save_dir = Path(self.config['trainer']['save_dir'])
        timestamp = datetime.now().strftime(r'%m%d_%H%M%S') if timestamp else ''

        exper_name = self.config['name']
        self._save_dir = save_dir / 'models' / exper_name / timestamp
        self._log_dir = save_dir / 'log' / exper_name / timestamp

        self.save_dir.mkdir(parents=True, exist_ok=True)
        self.log_dir.mkdir(parents=True, exist_ok=True)

        # save updated config file to the checkpoint dir
        write_json(self.config, self.save_dir / 'config.json')

        # configure logging module
        setup_logging(self.log_dir)
        self.log_levels = {
            0: logging.WARNING,
            1: logging.INFO,
            2: logging.DEBUG
        } 
Example 80
Project: flasky   Author: RoseOu   File: __main__.py    MIT License 4 votes vote down vote up
def parse_options():
    """
    Define and parse `optparse` options for command-line usage.
    """
    usage = """%prog [options] [INPUTFILE]
       (STDIN is assumed if no INPUTFILE is given)"""
    desc = "A Python implementation of John Gruber's Markdown. " \
           "http://packages.python.org/Markdown/"
    ver = "%%prog %s" % markdown.version
    
    parser = optparse.OptionParser(usage=usage, description=desc, version=ver)
    parser.add_option("-f", "--file", dest="filename", default=None,
                      help="Write output to OUTPUT_FILE. Defaults to STDOUT.",
                      metavar="OUTPUT_FILE")
    parser.add_option("-e", "--encoding", dest="encoding",
                      help="Encoding for input and output files.",)
    parser.add_option("-q", "--quiet", default = CRITICAL,
                      action="store_const", const=CRITICAL+10, dest="verbose",
                      help="Suppress all warnings.")
    parser.add_option("-v", "--verbose",
                      action="store_const", const=INFO, dest="verbose",
                      help="Print all warnings.")
    parser.add_option("-s", "--safe", dest="safe", default=False,
                      metavar="SAFE_MODE",
                      help="'replace', 'remove' or 'escape' HTML tags in input")
    parser.add_option("-o", "--output_format", dest="output_format", 
                      default='xhtml1', metavar="OUTPUT_FORMAT",
                      help="'xhtml1' (default), 'html4' or 'html5'.")
    parser.add_option("--noisy",
                      action="store_const", const=DEBUG, dest="verbose",
                      help="Print debug messages.")
    parser.add_option("-x", "--extension", action="append", dest="extensions",
                      help = "Load extension EXTENSION.", metavar="EXTENSION")
    parser.add_option("-n", "--no_lazy_ol", dest="lazy_ol", 
                      action='store_false', default=True,
                      help="Observe number of first item of ordered lists.")

    (options, args) = parser.parse_args()

    if len(args) == 0:
        input_file = None
    else:
        input_file = args[0]

    if not options.extensions:
        options.extensions = []

    return {'input': input_file,
            'output': options.filename,
            'safe_mode': options.safe,
            'extensions': options.extensions,
            'encoding': options.encoding,
            'output_format': options.output_format,
            'lazy_ol': options.lazy_ol}, options.verbose