当前位置: 首页>>代码示例>>Python>>正文


Python RainbowLoggingHandler.setLevel方法代码示例

本文整理汇总了Python中rainbow_logging_handler.RainbowLoggingHandler.setLevel方法的典型用法代码示例。如果您正苦于以下问题:Python RainbowLoggingHandler.setLevel方法的具体用法?Python RainbowLoggingHandler.setLevel怎么用?Python RainbowLoggingHandler.setLevel使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rainbow_logging_handler.RainbowLoggingHandler的用法示例。


在下文中一共展示了RainbowLoggingHandler.setLevel方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: setup_logging

# 需要导入模块: from rainbow_logging_handler import RainbowLoggingHandler [as 别名]
# 或者: from rainbow_logging_handler.RainbowLoggingHandler import setLevel [as 别名]
def setup_logging() -> None:
    """
    Sets up the logging module to have a verbose option and formats the Console handler and File handler
    """
    logging.addLevelName(VERBOSE, "VERBOSE")
    logging.Logger.verbose = logger_verbose
    logging.verbose = logging_verbose
    logging.VERBOSE = VERBOSE

    # define console handler
    console_handler = ConsoleHandler(sys.stderr)
    if hasattr(console_handler, "_column_color"):
        # noinspection PyProtectedMember
        # pylint: disable=protected-access
        console_handler._column_color['%(message)s'][logging.VERBOSE] = ('cyan', None, False)

    console_formatter = logging.Formatter("[%(asctime)s] %(levelname)s : %(message)s", "%H:%M:%S")
    console_handler.setFormatter(console_formatter)
    console_handler.setLevel(logging.VERBOSE)

    # define file handler
    if not os.path.exists(os.path.dirname(get_global_conf().getdir("install", "log_file"))):
        os.makedirs(os.path.dirname(get_global_conf().getdir("install", "log_file")))
    file_handler = logging.FileHandler(get_global_conf().getdir("install", "log_file"))

    # add handlers
    logging.getLogger().addHandler(console_handler)
    logging.getLogger().addHandler(file_handler)

    logging.getLogger().setLevel(get_global_conf().getint("install", "log_level"))
开发者ID:AmesianX,项目名称:bugbase,代码行数:32,代码来源:logger.py

示例2: get_logger

# 需要导入模块: from rainbow_logging_handler import RainbowLoggingHandler [as 别名]
# 或者: from rainbow_logging_handler.RainbowLoggingHandler import setLevel [as 别名]
def get_logger(name):
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)

    handler = logging.FileHandler(os.path.join(config.logs_dir, '{}.log'.format(name)))
    handler.setFormatter(log_formatter)
    handler.setLevel(logging.DEBUG)

    handler2 = RainbowLoggingHandler(
            sys.stdout,
            '%Y-%m-%d %H:%M:%S',
            color_asctime=('white', None, False)
    )
    handler2.setFormatter(log_formatter)
    handler2.setLevel(logging.DEBUG)

    logger.addHandler(handler)
    logger.addHandler(handler2)

    return logger
开发者ID:INSA-4IF-SpecIFic,项目名称:elif,代码行数:22,代码来源:utils.py

示例3: enable_logging

# 需要导入模块: from rainbow_logging_handler import RainbowLoggingHandler [as 别名]
# 或者: from rainbow_logging_handler.RainbowLoggingHandler import setLevel [as 别名]
def enable_logging(filename: str, level: str):
    class Squelch(logging.Filter):
        def filter(self, record):
            if record.levelno == logging.DEBUG:
                return not record.name.startswith('asyncio') and \
                       not record.name.startswith('websockets') and \
                       not record.name.startswith('aiohttp')
            elif record.levelno == logging.INFO and record.name.startswith('asyncio'):
                return False
            return True

    formatter = logging.Formatter(fmt='%(asctime)s.%(msecs)03d:%(levelname)s:%(name)s:%(message)s')

    # File logger captures everything.
    file_handler = logging.FileHandler(filename)
    file_handler.setLevel(logging.DEBUG)

    # Console output level is configurable.
    stream_handler = RainbowLoggingHandler(
        sys.stdout,
        color_asctime=('cyan', None, False),
        color_msecs=('cyan', None, False),
        color_levelname=('gray', None, False),
        color_module=('yellow', None, False),
        color_name=('blue', None, False),
        color_lineno=('green', None, False),
        datefmt="%Y-%m-%d %H:%M:%S"
    )
    stream_handler.setLevel(getattr(logging, level))
    stream_handler.addFilter(Squelch())

    # Set an output format.
    stream_handler.setFormatter(formatter)
    file_handler.setFormatter(formatter)
    file_handler.addFilter(Squelch())

    # Add handlers to root.
    root = logging.getLogger('')
    root.setLevel(logging.DEBUG)
    root.addHandler(stream_handler)
    root.addHandler(file_handler)
开发者ID:,项目名称:,代码行数:43,代码来源:

示例4: RainbowLoggingHandler

# 需要导入模块: from rainbow_logging_handler import RainbowLoggingHandler [as 别名]
# 或者: from rainbow_logging_handler.RainbowLoggingHandler import setLevel [as 别名]
    log_level = logging.CRITICAL    


# set up logging to file 
logging.basicConfig(level=logging.DEBUG,
                    format='[%(asctime)s] %(name)s %(funcName)s():%(lineno)d\t%(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='spam.log',
                    filemode='w')

# define a Handler which writes INFO messages or higher to the sys.stderr
console = RainbowLoggingHandler(sys.stdout) #logging.StreamHandler() 
# handler = RainbowLoggingHandler(sys.stdout)

# get level from command input
console.setLevel(log_level)

formatter = logging.Formatter("[%(asctime)s] %(name)s %(funcName)s():%(lineno)d\t%(message)s")
# tell the handler to use this format
console.setFormatter(formatter)
# add the handler to the root logger
logging.getLogger('').addHandler(console)
logger = logging.getLogger('nrk2013')
# tell requests lib to chill out
requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.WARNING)


# Dette skulle hjelpe?
# En ekte glob!
request = False
开发者ID:eiriks,项目名称:nrk,代码行数:33,代码来源:run.py

示例5: initialize_logger

# 需要导入模块: from rainbow_logging_handler import RainbowLoggingHandler [as 别名]
# 或者: from rainbow_logging_handler.RainbowLoggingHandler import setLevel [as 别名]
def initialize_logger(args, script_name, syslog_server=None):
    """
    Initialize the logging instance with the values provided
    by the user and return the logging object.

    """
    LOGGER = logging.getLogger(script_name)

    FORMATTER = logging.Formatter(
        ""+script_name+" : "+str(getpass.getuser())+" : %(asctime)s : %(levelname)s : %(message)s",
                                  datefmt='%m/%d/%Y %I:%M:%S %p')

    # create console handler and set level to info
    logging.StreamHandler()

    # setup `RainbowLoggingHandler`
    handler = RainbowLoggingHandler(sys.stderr, color_funcName=('black', 'white', True))
    handler.setFormatter(FORMATTER)
    LOGGER.addHandler(handler)

    # setup log level from arguments
    if args.log:
        if contains('DEBUG', args.log.upper()):
            handler.setLevel(logging.DEBUG)
            LOGGER.setLevel(logging.DEBUG)
        elif contains('WARNING', args.log.upper()):
            handler.setLevel(logging.WARNING)
            LOGGER.setLevel(logging.WARNING)
        elif contains('ERROR', args.log.upper()):
            handler.setLevel(logging.ERROR)
            LOGGER.setLevel(logging.ERROR)
        else:
            handler.setLevel(logging.INFO)
            LOGGER.setLevel(logging.INFO)
        LOGGER.info('Logging level has been set to {}'.format(args.log.upper()))

    # setup logging directory to store log files
    if args.log_dir:

        if not os.path.isdir(args.log_dir):
            os.makedirs(args.log_dir)
        output_dir = args.log_dir

    else:
        output_dir = create_log_dir()

    LOGGER.info('Logging directory has been set to {}'.format(output_dir))


    # create optional syslog handler, if the argument has been supplied to support it
    if args.syslog:

        DESIG_SYSLOG_SERVER = syslog_server

        handler = logging.handlers.SysLogHandler(address=(DESIG_SYSLOG_SERVER,
                                                          logging.handlers.SYSLOG_UDP_PORT))
        syslog_format = logging.Formatter(
            '[appname]: %(name)s: [alias]: '+str(getpass.getuser())+' %(message)s')
        handler.setFormatter(syslog_format)

        if args.syslog_level:
            # Set syslog level to the user specified level
            if args.syslog_level == 'info':
                handler.setLevel(logging.INFO)
            elif args.syslog_level == 'warning':
                handler.setLevel(logging.WARNING)
            elif args.syslog_level == 'error':
                handler.setLevel(logging.ERROR)

        LOGGER.info(
            'Syslog has been enabled for [{}] logging level, sent to syslog server [{}]'.format(
                                                                            args.syslog_level,
                                                                            DESIG_SYSLOG_SERVER))

        # Add syslog handler to logging object
        LOGGER.addHandler(handler)

    # create error file handler and set level to error
    handler = logging.FileHandler(os.path.join(
        output_dir, "error.log"),"a", encoding=None, delay="true")
    handler.setLevel(logging.ERROR)
    handler.setFormatter(FORMATTER)
    LOGGER.addHandler(handler)

    # create debug file handler and set level to debug
    handler = logging.FileHandler(os.path.join(output_dir, "all.log"),"a")
    handler.setLevel(logging.DEBUG)
    handler.setFormatter(FORMATTER)
    LOGGER.addHandler(handler)

    if args.logfile_rotate:
        '''
        User has specified they would like to create a daily rotating logfile.
        Create an instance and DO NOT create a single serving logfile.
        '''
        LOGGER.info('Logfiles are now set to auto-rotate at midnight UTC.')
        filepath_and_name_format = ('{}/{}'.format(output_dir, script_name.replace('.py','')))
        LOGGER.info('Logfiles are now being written at {}'.format(filepath_and_name_format))

        log_filename=filepath_and_name_format
#.........这里部分代码省略.........
开发者ID:zerosignal0,项目名称:ezlogger,代码行数:103,代码来源:__init__.py

示例6: RainbowLoggingHandler

# 需要导入模块: from rainbow_logging_handler import RainbowLoggingHandler [as 别名]
# 或者: from rainbow_logging_handler.RainbowLoggingHandler import setLevel [as 别名]
#! /usr/bin/env python
# -*- coding:utf-8 -*-

# Standard lib imports
import logging.handlers
import sys
import time

# Third Party imports
from rainbow_logging_handler import RainbowLoggingHandler

# BITSON imports

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

log_format = "".join(["[%(asctime)s] %(levelname)8s: ", "%(message)s"])

formatter = logging.Formatter(fmt=log_format)
# Format UTC Time
formatter.converter = time.gmtime

# Console Handler
ch = RainbowLoggingHandler(sys.stderr)
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)
开发者ID:bitson,项目名称:bitsonbot,代码行数:29,代码来源:logger.py

示例7: RainbowLoggingHandler

# 需要导入模块: from rainbow_logging_handler import RainbowLoggingHandler [as 别名]
# 或者: from rainbow_logging_handler.RainbowLoggingHandler import setLevel [as 别名]
# default log format
default_fmt = logging.Formatter('[%(asctime)s] %(levelname)s '
                                '(%(process)d) %(name)s : %(message)s',
                                datefmt='%Y/%m/%d %H:%M:%S')

# set up handler
try:
    # Rainbow Logging
    import sys
    from rainbow_logging_handler import RainbowLoggingHandler
    default_handler = RainbowLoggingHandler(sys.stdout)
except:
    default_handler = logging.StreamHandler()

default_handler.setFormatter(default_fmt)
default_handler.setLevel(logging.DEBUG)

# setup root logger
logger = logging.getLogger()
logger.addHandler(default_handler)


def setFmt(fmt=default_fmt):
    global defaut_handler
    default_handler.setFormatter(fmt)


def setRootLevel(level):
    global logger
    logger.setLevel(level)
开发者ID:takiyu,项目名称:DeepPose,代码行数:32,代码来源:log_initializer.py

示例8: RainbowLoggingHandler

# 需要导入模块: from rainbow_logging_handler import RainbowLoggingHandler [as 别名]
# 或者: from rainbow_logging_handler.RainbowLoggingHandler import setLevel [as 别名]
    # log everything to the file
    import time, os
    logging.basicConfig(
        # A level of the logger
        level=logging.INFO,
        # Specify format string for the handler
        format='%(asctime)s %(filename)-15s:%(lineno)-4d %(levelname)-8s %(message)s',
        datefmt='%m-%d-%Y %H:%M:%S',
        filename='/tmp/hlp-{}-{}.log'.format(int(time.time()), os.getpid()),
        filemode='w'
    )

    # log specific things to the console
    console = RainbowLoggingHandler(sys.stderr)
    console.setLevel(logging.DEBUG)
    console.setFormatter(logging.Formatter('%(filename)s:%(lineno)d\t%(levelname)-8s: %(message)s'))
    logging.getLogger('planning.interface').addHandler(console)
    logging.getLogger('integration.master').addHandler(console)
    logging.getLogger('__main__').addHandler(console)

    # log all warnings or higher
    consoleError = RainbowLoggingHandler(sys.stderr)
    consoleError.setLevel(logging.WARN)
    consoleError.setFormatter(logging.Formatter('%(filename)s:%(lineno)d\t%(levelname)-8s: %(message)s'))
    logging.getLogger().addHandler(consoleError)

    logging.getLogger('OpenGL').setLevel(99)
    # logging.getLogger('integration.jobs').setLevel(logging.WARNING)
    # logging.getLogger('integration.visualization').setLevel(logging.WARNING)
    # logging.getLogger('integration.interface').setLevel(logging.WARNING)
开发者ID:duke-iml,项目名称:ece490-s2016,代码行数:32,代码来源:hlp_master.py

示例9: main

# 需要导入模块: from rainbow_logging_handler import RainbowLoggingHandler [as 别名]
# 或者: from rainbow_logging_handler.RainbowLoggingHandler import setLevel [as 别名]
def main(instruments, mode, log_level, start_date=None, end_date=None):
    """
    Algorithmic trading tool.
    """

    # Make urllib3 logger more calm
    urllib3_logger = logging.getLogger('urllib3')
    urllib3_logger.setLevel(logging.CRITICAL)

    numeric_level = getattr(logging, log_level.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % log_level)
    log_filename = "logs/pyfx_debug_{}-{}.log".format(strftime("%Y_%m_%d-%H_%M"), settings.ENVIRONMENT)
    logging.basicConfig(filename=log_filename, level=logging.DEBUG)
    logger = logging.getLogger('pyFx')

    formatter = logging.Formatter("[%(asctime)s/%(levelname)s] %(funcName)s():%(lineno)d\t%(message)s")
    handler = RainbowLoggingHandler(sys.stdout, color_funcName=('black', 'yellow', True))
    handler.setFormatter(formatter)
    handler.setLevel(numeric_level)
    logger.addHandler(handler)

    start_date_ = start_date if start_date else settings.BACKTEST_START
    end_date_ = end_date if end_date else settings.BACKTEST_END
    BACKTEST_START = parser.parse(start_date_).replace(tzinfo=pytz.utc)
    BACKTEST_END = parser.parse(end_date_).replace(tzinfo=pytz.utc)

    if mode == 'backtest':
        api = oandapy.API(
            environment=settings.ENVIRONMENT,
            access_token=settings.ACCESS_TOKEN,
        )
        broker = OandaBacktestBroker(
            api=api,
            account_id=settings.ACCOUNT_ID,
            initial_balance=decimal.Decimal(5000))

        # Oanda 20:00, Local: 22:00, DailyFx: 16:00
        clock = SimulatedClock(
            start=BACKTEST_START,
            stop=BACKTEST_END,
            interval=settings.CLOCK_INTERVAL,
        )

    elif mode == 'live':
        api = oandapy.API(
            environment=settings.ENVIRONMENT,
            access_token=settings.ACCESS_TOKEN,
        )
        clock = IntervalClock(interval=settings.CLOCK_INTERVAL)
        broker = OandaRealtimeBroker(api=api, account_id=settings.ACCOUNT_ID)
    else:
        raise NotImplementedError()

    # TODO Optimize load of instrument info
    instrument_list = set(instruments)
    for inst in instrument_list:
        inst.load(broker)
    # TODO We have to be able to instantiate strategies with custom args
    strategies = [settings.STRATEGY(instrument)
                  for instrument in instrument_list]
    if mode == 'backtest':
        broker.init_backtest(BACKTEST_START, BACKTEST_END, strategies)
        pf = Portfolio(broker, mode='backtest')
    else:
        pf = Portfolio(broker, mode='live')
    controller = Controller(clock, broker, pf, strategies)
    controller.run_until_stopped()
开发者ID:thatchristoph,项目名称:pyFxTrader,代码行数:70,代码来源:cli.py


注:本文中的rainbow_logging_handler.RainbowLoggingHandler.setLevel方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。