Python logging.StreamHandler() Examples

The following are code examples for showing how to use logging.StreamHandler(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: kas   Author: siemens   File: kas.py    (license) View Source Project 18 votes vote down vote up
def create_logger():
    """
        Setup the logging environment
    """
    log = logging.getLogger()  # root logger
    log.setLevel(logging.INFO)
    format_str = '%(asctime)s - %(levelname)-8s - %(message)s'
    date_format = '%Y-%m-%d %H:%M:%S'
    if HAVE_COLORLOG and os.isatty(2):
        cformat = '%(log_color)s' + format_str
        colors = {'DEBUG': 'reset',
                  'INFO': 'reset',
                  'WARNING': 'bold_yellow',
                  'ERROR': 'bold_red',
                  'CRITICAL': 'bold_red'}
        formatter = colorlog.ColoredFormatter(cformat, date_format,
                                              log_colors=colors)
    else:
        formatter = logging.Formatter(format_str, date_format)
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(formatter)
    log.addHandler(stream_handler)
    return logging.getLogger(__name__) 
Example 2
Project: safetyculture-sdk-python   Author: SafetyCulture   File: import_grs.py    (license) View Source Project 17 votes vote down vote up
def configure_logging(path_to_log_directory):
    """
    Configure logger

    :param path_to_log_directory:  path to directory to write log file in
    :return:
    """
    log_filename = datetime.datetime.now().strftime('%Y-%m-%d') + '.log'
    importer_logger = logging.getLogger('importer_logger')
    importer_logger.setLevel(LOG_LEVEL)
    formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(message)s')

    fh = logging.FileHandler(filename=os.path.join(path_to_log_directory, log_filename))
    fh.setLevel(LOG_LEVEL)
    fh.setFormatter(formatter)
    importer_logger.addHandler(fh)

    sh = logging.StreamHandler(sys.stdout)
    sh.setLevel(LOG_LEVEL)
    sh.setFormatter(formatter)
    importer_logger.addHandler(sh) 
Example 3
Project: sphinxcontrib-versioning   Author: Robpol86   File: setup_logging.py    (MIT License) View Source Project 9 votes vote down vote up
def setup_logging(verbose=0, colors=False, name=None):
    """Configure console logging. Info and below go to stdout, others go to stderr.

    :param int verbose: Verbosity level. > 0 print debug statements. > 1 passed to sphinx-build.
    :param bool colors: Print color text in non-verbose mode.
    :param str name: Which logger name to set handlers to. Used for testing.
    """
    root_logger = logging.getLogger(name)
    root_logger.setLevel(logging.DEBUG if verbose > 0 else logging.INFO)
    formatter = ColorFormatter(verbose > 0, colors)
    if colors:
        colorclass.Windows.enable()

    handler_stdout = logging.StreamHandler(sys.stdout)
    handler_stdout.setFormatter(formatter)
    handler_stdout.setLevel(logging.DEBUG)
    handler_stdout.addFilter(type('', (logging.Filter,), {'filter': staticmethod(lambda r: r.levelno <= logging.INFO)}))
    root_logger.addHandler(handler_stdout)

    handler_stderr = logging.StreamHandler(sys.stderr)
    handler_stderr.setFormatter(formatter)
    handler_stderr.setLevel(logging.WARNING)
    root_logger.addHandler(handler_stderr) 
Example 4
Project: Solo-Mapper   Author: Escadrone   File: LogConfig.py    (Apache License 2.0) View Source Project 8 votes vote down vote up
def __init__(self,loggerName,logFileName,doConsoleLogging):
	#Formatage log 
	default_formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: '+loggerName+' :: %(message)s')
	console_formatter = logging.Formatter('%(levelname)s :: %(message)s')

	self.mainLogger = logging.getLogger('logger.'+logFileName+'') #on nomme le logger
	self.mainLogger.setLevel(logging.DEBUG) #on met le niveau du logger sur DEBUG, comme ca il ecrit tout

	#Log vers la console
	if doConsoleLogging:
	 console_handler = logging.StreamHandler()
	 console_handler.setLevel(logging.DEBUG)
	 console_handler.setFormatter(console_formatter)
	 self.mainLogger.addHandler(console_handler)

	# creation d'un handler qui va rediriger une ecriture du log vers
	# un fichier en mode 'append', avec 1 backup et une taille max de 1Mo
	file_handler = RotatingFileHandler('/mnt/Usb-Solo-Mapper/Logs/'+logFileName+'.log', 'a', 1000000, 1)
	# on lui met le niveau sur DEBUG, on lui dit qu'il doit utiliser le formateur
	# cree precedement et on ajoute ce handler au logger
	file_handler.setLevel(logging.DEBUG)
	file_handler.setFormatter(default_formatter)
	self.mainLogger.addHandler(file_handler) 
Example 5
Project: CopyNet   Author: MultiPath   File: copynet_input.py    (MIT License) View Source Project 7 votes vote down vote up
def init_logging(logfile):
    formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s: %(message)s',
                                  datefmt='%m/%d/%Y %H:%M:%S'   )
    fh = logging.FileHandler(logfile)
    # ch = logging.StreamHandler()

    fh.setFormatter(formatter)
    # ch.setFormatter(formatter)
    # fh.setLevel(logging.INFO)
    # ch.setLevel(logging.INFO)
    # logging.getLogger().addHandler(ch)
    logging.getLogger().addHandler(fh)
    logging.getLogger().setLevel(logging.INFO)
    return logging

# prepare logging. 
Example 6
Project: CopyNet   Author: MultiPath   File: lcsts_test.py    (MIT License) View Source Project 7 votes vote down vote up
def init_logging(logfile):
    formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s: %(message)s',
                                  datefmt='%m/%d/%Y %H:%M:%S'   )
    fh = logging.FileHandler(logfile)
    # ch = logging.StreamHandler()

    fh.setFormatter(formatter)
    # ch.setFormatter(formatter)
    # fh.setLevel(logging.INFO)
    # ch.setLevel(logging.INFO)
    # logging.getLogger().addHandler(ch)
    logging.getLogger().addHandler(fh)
    logging.getLogger().setLevel(logging.INFO)

    return logging

# prepare logging. 
Example 7
Project: uchroma   Author: cyanogen   File: log.py    (GNU Lesser General Public License v3.0) View Source Project 7 votes vote down vote up
def get(cls, tag):
        """
        Get the global logger instance for the given tag

        :param tag: the log tag
        :return: the logger instance
        """
        if tag not in cls._LOGGERS:
            if cls._use_color:
                handler = colorlog.StreamHandler()
                handler.setFormatter(colorlog.ColoredFormatter( \
                    ' %(log_color)s%(name)s/%(levelname)-8s%(reset)s |'
                    ' %(log_color)s%(message)s%(reset)s'))
            else:
                handler = logging.StreamHandler()
                handler.setFormatter(logging.Formatter( \
                    ' %(name)s/%(levelname)-8s | %(message)s'))

            logger = logging.getLogger(tag)
            logger.addHandler(handler)

            cls._LOGGERS[tag] = logger

        return cls._LOGGERS[tag] 
Example 8
Project: safetyculture-sdk-python   Author: SafetyCulture   File: safetypy.py    (license) View Source Project 6 votes vote down vote up
def configure_logging(self):
        """
        Configure logging to log to std output as well as to log file
        """
        log_level = logging.DEBUG

        log_filename = datetime.now().strftime('%Y-%m-%d') + '.log'
        sp_logger = logging.getLogger('sp_logger')
        sp_logger.setLevel(log_level)
        formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(message)s')

        fh = logging.FileHandler(filename=self.log_dir + log_filename)
        fh.setLevel(log_level)
        fh.setFormatter(formatter)
        sp_logger.addHandler(fh)

        sh = logging.StreamHandler(sys.stdout)
        sh.setLevel(log_level)
        sh.setFormatter(formatter)
        sp_logger.addHandler(sh) 
Example 9
Project: python-   Author: secondtonone1   File: distro.py    (license) View Source Project 6 votes vote down vote up
def main():
    import argparse

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler(sys.stdout))

    parser = argparse.ArgumentParser(description="Linux distro info tool")
    parser.add_argument(
        '--json',
        '-j',
        help="Output in machine readable format",
        action="store_true")
    args = parser.parse_args()

    if args.json:
        logger.info(json.dumps(info(), indent=4, sort_keys=True))
    else:
        logger.info('Name: %s', name(pretty=True))
        distribution_version = version(pretty=True)
        if distribution_version:
            logger.info('Version: %s', distribution_version)
        distribution_codename = codename()
        if distribution_codename:
            logger.info('Codename: %s', distribution_codename) 
Example 10
Project: python-   Author: secondtonone1   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def add_stderr_logger(level=logging.DEBUG):
    """
    Helper for quickly adding a StreamHandler to the logger. Useful for
    debugging.

    Returns the handler after adding it.
    """
    # This method needs to be in this __init__.py to get the __name__ correct
    # even if urllib3 is vendored within another package.
    logger = logging.getLogger(__name__)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(level)
    logger.debug('Added a stderr logging handler to logger: %s', __name__)
    return handler

# ... Clean up. 
Example 11
Project: IotCenter   Author: panjanek   File: iotcommon.py    (MIT License) View Source Project 6 votes vote down vote up
def configureLogging(level, console, file):
    logger = logging.getLogger()    
    logger.setLevel(level)
    formatter = logging.Formatter('%(asctime)s  %(levelname)s   %(message)s')
    if console:
        cons = logging.StreamHandler()
        cons.setLevel(level)
        cons.setFormatter(formatter)
        logger.addHandler(cons)
        print("logging to console")
        
    if file:              
        f = logging.FileHandler(file)        
        f.setLevel(level)
        f.setFormatter(formatter)
        logger.addHandler(f)        
        print("logging to file {0}".format(file)) 
Example 12
Project: amadash   Author: ipartola   File: main.py    (MIT License) View Source Project 6 votes vote down vote up
def setup_logging():
    '''Sets up internal logging. Run this once at startup.'''

    logger = logging.getLogger()

    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    if options.log.filename:
        handler = logging.handlers.TimedRotatingFileHandler(filename=options.log.filename, when=options.log.when, backupCount=options.log.backup_count, utc=True)
        handler.setFormatter(formatter)
        logger.addHandler(handler)

    if not options.main.daemon:
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)
        logger.addHandler(handler)

    level = getattr(logging, options.log.level.upper())
    logger.setLevel(level) 
Example 13
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def add_stderr_logger(level=logging.DEBUG):
    """
    Helper for quickly adding a StreamHandler to the logger. Useful for
    debugging.

    Returns the handler after adding it.
    """
    # This method needs to be in this __init__.py to get the __name__ correct
    # even if urllib3 is vendored within another package.
    logger = logging.getLogger(__name__)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(level)
    logger.debug('Added a stderr logging handler to logger: %s', __name__)
    return handler


# ... Clean up. 
Example 14
Project: my-first-blog   Author: AnkurBegining   File: distro.py    (license) View Source Project 6 votes vote down vote up
def main():
    import argparse

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler(sys.stdout))

    parser = argparse.ArgumentParser(description="Linux distro info tool")
    parser.add_argument(
        '--json',
        '-j',
        help="Output in machine readable format",
        action="store_true")
    args = parser.parse_args()

    if args.json:
        logger.info(json.dumps(info(), indent=4, sort_keys=True))
    else:
        logger.info('Name: %s', name(pretty=True))
        distribution_version = version(pretty=True)
        if distribution_version:
            logger.info('Version: %s', distribution_version)
        distribution_codename = codename()
        if distribution_codename:
            logger.info('Codename: %s', distribution_codename) 
Example 15
Project: my-first-blog   Author: AnkurBegining   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def add_stderr_logger(level=logging.DEBUG):
    """
    Helper for quickly adding a StreamHandler to the logger. Useful for
    debugging.

    Returns the handler after adding it.
    """
    # This method needs to be in this __init__.py to get the __name__ correct
    # even if urllib3 is vendored within another package.
    logger = logging.getLogger(__name__)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(level)
    logger.debug('Added a stderr logging handler to logger: %s', __name__)
    return handler

# ... Clean up. 
Example 16
Project: NeoVintageous   Author: NeoVintageous   File: nvim.py    (license) View Source Project 6 votes vote down vote up
def _init_logger():
    formatter = _LogFormatter('%(asctime)s %(levelname)-5s %(name)[email protected]%(funcName)s:%(lineno)d %(message)s')

    logger = logging.getLogger('NeoVintageous')
    logger.setLevel(logging.DEBUG)

    # Stream handler
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(formatter)
    logger.addHandler(stream_handler)

    # File handler
    log_file = _log_file()
    if log_file:
        file_handler = RotatingFileHandler(
            log_file,
            maxBytes=10000000,  # 10000000 = 10MB
            backupCount=2
        )
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)

        logger.debug('debug log file: \'{}\''.format(log_file))
    else:
        console_message('could not create log file \'{}\''.format(log_file)) 
Example 17
Project: core-framework   Author: RedhawkSDR   File: qtbrowse.py    (license) View Source Project 6 votes vote down vote up
def main():
    # Set up a console logger.
    console = logging.StreamHandler()
    formatter = logging.Formatter("%(asctime)s %(name)-12s:%(levelname)-8s: %(message)s")
    console.setFormatter(formatter)
    logging.getLogger().addHandler(console)
    logging.getLogger().setLevel(logging.INFO)

    kw = {}
    longopts = ['domainname=', 'verbose']
    opts, args = getopt.getopt(sys.argv[1:], 'v', longopts)
    for opt, val in opts:
        if opt == '--domainname':
            kw['domainName'] = val
        if opt in ['-v', '--verbose']:
            kw['verbose'] = True

    a = QApplication(sys.argv)
    QObject.connect(a,SIGNAL("lastWindowClosed()"),a,SLOT("quit()"))
    w = BrowseWindow(**kw)
    w.show()
    a.exec_() 
Example 18
Project: gimel   Author: Alephbet   File: logger.py    (MIT License) View Source Project 6 votes vote down vote up
def setup(name=__name__, level=logging.INFO):
    logger = logging.getLogger(name)
    if logger.handlers:
        return logger
    logger.setLevel(level)
    try:
        # check if click exists to swap the logger
        import click  # noqa
        formatter = ColorFormatter('[.] %(message)s')
    except ImportError:
        formatter = CustomFormatter('[.] %(message)s')
    handler = logging.StreamHandler(None)
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)
    return logger 
Example 19
Project: kinect-2-libras   Author: inessadl   File: util.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def log_to_stderr(level=None):
    '''
    Turn on logging and add a handler which prints to stderr
    '''
    global _log_to_stderr
    import logging

    logger = get_logger()
    formatter = logging.Formatter(DEFAULT_LOGGING_FORMAT)
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    if level:
        logger.setLevel(level)
    _log_to_stderr = True
    return _logger

#
# Function returning a temp directory which will be removed on exit
# 
Example 20
Project: googletranslate.popclipext   Author: wizyoung   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def add_stderr_logger(level=logging.DEBUG):
    """
    Helper for quickly adding a StreamHandler to the logger. Useful for
    debugging.

    Returns the handler after adding it.
    """
    # This method needs to be in this __init__.py to get the __name__ correct
    # even if urllib3 is vendored within another package.
    logger = logging.getLogger(__name__)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(level)
    logger.debug('Added a stderr logging handler to logger: %s', __name__)
    return handler


# ... Clean up. 
Example 21
Project: manubot   Author: greenelab   File: manubot.py    (license) View Source Project 6 votes vote down vote up
def main():
    """
    Called as a console_scripts entry point in setup.py. This function defines
    the manubot command line script.
    """
    # Track if message gets logged with severity of error or greater
    # See https://stackoverflow.com/a/45446664/4651668
    error_handler = errorhandler.ErrorHandler()

    # Log to stderr
    logger = logging.getLogger()
    stream_handler = logging.StreamHandler(stream=sys.stderr)
    stream_handler.setFormatter(logging.Formatter('## {levelname}\n{message}', style='{'))
    logger.addHandler(stream_handler)

    args = parse_arguments()
    logger.setLevel(getattr(logging, args.log_level))

    prepare_manuscript(args)

    if error_handler.fired:
        logging.critical('Failure: exiting with code 1 due to logged errors')
        raise SystemExit(1) 
Example 22
Project: VxFuzz   Author: yformaggio   File: fuzz.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def logger(level, name, logfile):
        """ Create and configure file and console logging.
        :param level: console debugging level only.
        :param name: logger name
        :param logfile: log destination file name
        :return: configured logging object
        """
        logger = logging.getLogger(name)
        console_handler = logging.StreamHandler()
        console_handler.setLevel(level)
        file_handler = logging.FileHandler(logfile)
        file_handler.setLevel(logging.DEBUG)
        console_formatter = logging.Formatter("[%(levelname)s] %(message)s")
        file_formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
        console_handler.setFormatter(console_formatter)
        file_handler.setFormatter(file_formatter)
        logger.addHandler(console_handler)
        logger.addHandler(file_handler)

        return logger 
Example 23
Project: Projects   Author: it2school   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def add_stderr_logger(level=logging.DEBUG):
    """
    Helper for quickly adding a StreamHandler to the logger. Useful for
    debugging.

    Returns the handler after adding it.
    """
    # This method needs to be in this __init__.py to get the __name__ correct
    # even if urllib3 is vendored within another package.
    logger = logging.getLogger(__name__)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(level)
    logger.debug('Added a stderr logging handler to logger: %s', __name__)
    return handler


# ... Clean up. 
Example 24
Project: virtualbmc   Author: umago   File: log.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def __init__(self, debug=False, logfile=None):
        logging.Logger.__init__(self, 'VirtualBMC')
        try:
            if logfile is not None:
                self.handler = logging.FileHandler(logfile)
            else:
                self.handler = logging.StreamHandler()

            formatter = logging.Formatter(DEFAULT_LOG_FORMAT)
            self.handler.setFormatter(formatter)
            self.addHandler(self.handler)

            if debug:
                self.setLevel(logging.DEBUG)
            else:
                self.setLevel(logging.INFO)

        except IOError, e:
            if e.errno == errno.EACCES:
                pass 
Example 25
Project: data_kennel   Author: amplify-education   File: util.py    (MIT License) View Source Project 6 votes vote down vote up
def configure_logging(debug):
    '''Sets the data kennel logger to appropriate levels of chattiness.'''
    default_logger = logging.getLogger('')
    datadog_logger = logging.getLogger('datadog.api')
    requests_logger = logging.getLogger('requests')
    if debug:
        default_logger.setLevel(logging.DEBUG)
        datadog_logger.setLevel(logging.INFO)
        requests_logger.setLevel(logging.INFO)
    else:
        default_logger.setLevel(logging.INFO)
        datadog_logger.setLevel(logging.WARNING)
        requests_logger.setLevel(logging.WARNING)

    stream_handler = logging.StreamHandler(sys.__stdout__)
    stream_handler.setLevel(logging.DEBUG)
    stream_handler.setFormatter(logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s'))
    default_logger.addHandler(stream_handler) 
Example 26
Project: Flask_Blog   Author: sugarguo   File: __init__.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def add_stderr_logger(level=logging.DEBUG):
    """
    Helper for quickly adding a StreamHandler to the logger. Useful for
    debugging.

    Returns the handler after adding it.
    """
    # This method needs to be in this __init__.py to get the __name__ correct
    # even if urllib3 is vendored within another package.
    logger = logging.getLogger(__name__)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(level)
    logger.debug('Added an stderr logging handler to logger: %s' % __name__)
    return handler

# ... Clean up. 
Example 27
Project: Flask_Blog   Author: sugarguo   File: helpers.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def test_exception_logging(self):
        out = StringIO()
        app = flask.Flask(__name__)
        app.logger_name = 'flask_tests/test_exception_logging'
        app.logger.addHandler(StreamHandler(out))

        @app.route('/')
        def index():
            1 // 0

        rv = app.test_client().get('/')
        self.assert_equal(rv.status_code, 500)
        self.assert_in(b'Internal Server Error', rv.data)

        err = out.getvalue()
        self.assert_in('Exception on / [GET]', err)
        self.assert_in('Traceback (most recent call last):', err)
        self.assert_in('1 // 0', err)
        self.assert_in('ZeroDivisionError:', err) 
Example 28
Project: Flask_Blog   Author: sugarguo   File: subclassing.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def test_suppressed_exception_logging(self):
        class SuppressedFlask(flask.Flask):
            def log_exception(self, exc_info):
                pass

        out = StringIO()
        app = SuppressedFlask(__name__)
        app.logger_name = 'flask_tests/test_suppressed_exception_logging'
        app.logger.addHandler(StreamHandler(out))

        @app.route('/')
        def index():
            1 // 0

        rv = app.test_client().get('/')
        self.assert_equal(rv.status_code, 500)
        self.assert_in(b'Internal Server Error', rv.data)

        err = out.getvalue()
        self.assert_equal(err, '') 
Example 29
Project: pip-update-requirements   Author: alanhamlett   File: __init__.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def add_stderr_logger(level=logging.DEBUG):
    """
    Helper for quickly adding a StreamHandler to the logger. Useful for
    debugging.

    Returns the handler after adding it.
    """
    # This method needs to be in this __init__.py to get the __name__ correct
    # even if urllib3 is vendored within another package.
    logger = logging.getLogger(__name__)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(level)
    logger.debug('Added a stderr logging handler to logger: %s', __name__)
    return handler


# ... Clean up. 
Example 30
Project: pip-update-requirements   Author: alanhamlett   File: distro.py    (BSD 2-Clause "Simplified" License) View Source Project 6 votes vote down vote up
def main():
    import argparse

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(logging.StreamHandler(sys.stdout))

    parser = argparse.ArgumentParser(description="Linux distro info tool")
    parser.add_argument(
        '--json',
        '-j',
        help="Output in machine readable format",
        action="store_true")
    args = parser.parse_args()

    if args.json:
        logger.info(json.dumps(info(), indent=4, sort_keys=True))
    else:
        logger.info('Name: %s', name(pretty=True))
        distribution_version = version(pretty=True)
        logger.info('Version: %s', distribution_version)
        distribution_codename = codename()
        logger.info('Codename: %s', distribution_codename) 
Example 31
Project: FenicsSolver   Author: qingfengxia   File: SolverBase.py    (GNU Lesser General Public License v3.0) View Source Project 6 votes vote down vote up
def set_logger(self, s):
        logger = logging.getLogger(self.__class__.__name__)
        # create console handler and set level to debug
        if ('logging_file' not in s) or (s['logging_file'] == None):
            fh = logging.StreamHandler()
        else:
            fh = logging.FileHandler(s['logging_file'])
        if 'logging_level' in s:
            fh.setLevel(s['logging_level'])
        else:
            fh.setLevel(logging.DEBUG)
        # create formatter
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)

        # add console stdout or log file to logger
        logger.addHandler(fh)
        self.logger = logger  # usage: self.logger.debug(msg) 
Example 32
Project: aws-waf-security-automation   Author: cerbo   File: __init__.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def add_stderr_logger(level=logging.DEBUG):
    """
    Helper for quickly adding a StreamHandler to the logger. Useful for
    debugging.

    Returns the handler after adding it.
    """
    # This method needs to be in this __init__.py to get the __name__ correct
    # even if urllib3 is vendored within another package.
    logger = logging.getLogger(__name__)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(level)
    logger.debug('Added a stderr logging handler to logger: %s', __name__)
    return handler

# ... Clean up. 
Example 33
Project: oriole-service   Author: zhouxiaoxiang   File: api.py    (license) View Source Project 6 votes vote down vote up
def logger(level='DEBUG', name=""):
    fmt = '[%(module)s] %(asctime)s %(levelname)-7.7s %(message)s'
    dfmt = '%Y-%m-%d %H:%M:%S'
    level = getattr(logging, level, DEBUG)

    logger = getLogger('services')
    logger.setLevel(level)
    fmter = Formatter(fmt, dfmt)
    del logger.handlers[:]

    if name:
        fh = FileHandler(name)
        fh.setLevel(level)
        fh.setFormatter(fmter)
        logger.addHandler(fh)

    ch = StreamHandler()
    ch.setLevel(level)
    ch.setFormatter(fmter)
    logger.addHandler(ch)
    logger.propagate = False

    return logger 
Example 34
Project: post-review   Author: ericforbes   File: logger.py    (license) View Source Project 6 votes vote down vote up
def create_logger():
    #logging.basicConfig(format='%(levelname)s - %(message)s')
    logging.basicConfig(format='%(message)s')

    root = logging.getLogger()
    root.setLevel(logging.getLevelName('INFO'))

    #Add handler for standard output (console) any debug+
    #ch = logging.StreamHandler(sys.stdout)
    #ch.setLevel(logging.getLevelName('DEBUG'))
    #formatter = logging.Formatter('%(message)s')
    #ch.setFormatter(formatter)
    #handler = ColorStreamHandler()
    #handler.setLevel(logging.getLevelName("DEBUG"))
    #root.addHandler(handler)
    
    return root 
Example 35
Project: StratoBalloon   Author: delattreb   File: com_logger.py    (GNU General Public License v3.0) View Source Project 6 votes vote down vote up
def __init__(self, name = ''):
        conf = com_config.Config()
        self.config = conf.getconfig()
        
        self.logger = logging.Logger(name, logging.DEBUG)
        self.logger.name = name
        
        # Formatter
        formatterfile = logging.Formatter('%(asctime)s %(levelname)s : %(name)s - %(message)s', datefmt='%d/%m/%Y %H:%M:%S')
        formatterconsole = colorlog.ColoredFormatter('%(asctime)s %(log_color)s%(levelname)s : %(name)s - %(message)s', datefmt='%d/%m/%Y %H:%M:%S',
                                                     log_colors={'DEBUG':    'white', 'INFO': 'green',
                                                                 'WARNING':  'bold_yellow', 'ERROR': 'bold_red',
                                                                 'CRITICAL': 'bold_red'})
        
        # First logger (file)
        self.logger.setLevel(logging.DEBUG)
        file_handler = RotatingFileHandler(self.config['LOGGER']['logfile'], 'a', int(self.config['LOGGER']['logfilesize']), 1)
        file_handler.setLevel(int(self.config['LOGGER']['levelfile']))
        file_handler.setFormatter(formatterfile)
        self.logger.addHandler(file_handler)
        
        # second logger (console)
        steam_handler = logging.StreamHandler()
        steam_handler.setLevel(int(self.config['LOGGER']['levelconsole']))
        steam_handler.setFormatter(formatterconsole)
        self.logger.addHandler(steam_handler) 
Example 36
Project: socketshark   Author: closeio   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def run(context, config):
    config_obj = load_config(config)

    log_config = config_obj['LOG']

    # Configure root logger if logging level is specified in config
    if log_config['level']:
        level = getattr(logging, log_config['level'])
        logger = logging.getLogger()
        logger.setLevel(level)
        formatter = logging.Formatter(log_config['format'])
        sh = logging.StreamHandler()
        sh.setFormatter(formatter)
        logger.addHandler(sh)

    if log_config['setup_structlog']:
        setup_structlog(sys.stdout.isatty())

    shark = SocketShark(config_obj)
    try:
        shark.start()
    except Exception:
        shark.log.exception('unhandled exception')
        raise 
Example 37
Project: functest   Author: opnfv   File: feature.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def __init__(self, **kwargs):
        super(Feature, self).__init__(**kwargs)
        self.result_file = "{}/{}.log".format(
            CONST.__getattribute__('dir_results'), self.case_name)
        try:
            module = kwargs['run']['module']
            self.logger = logging.getLogger(module)
        except KeyError:
            self.__logger.warning(
                "Cannot get module name %s. Using %s as fallback",
                kwargs, self.case_name)
            self.logger = logging.getLogger(self.case_name)
        handler = logging.StreamHandler()
        handler.setLevel(logging.WARN)
        self.logger.addHandler(handler)
        handler = logging.FileHandler(self.result_file)
        handler.setLevel(logging.DEBUG)
        self.logger.addHandler(handler)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        self.logger.addHandler(handler) 
Example 38
Project: OCV_Vehicles_Features   Author: dan-masek   File: cars.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def init_logging():
    main_logger = logging.getLogger()

    formatter = logging.Formatter(
        fmt='%(asctime)s.%(msecs)03d %(levelname)-8s [%(name)s] %(message)s'
        , datefmt='%Y-%m-%d %H:%M:%S')
    
    handler_stream = logging.StreamHandler(sys.stdout)
    handler_stream.setFormatter(formatter)
    main_logger.addHandler(handler_stream)
    
    if LOG_TO_FILE:
        handler_file = logging.handlers.RotatingFileHandler("debug.log"
            , maxBytes = 2**24
            , backupCount = 10)
        handler_file.setFormatter(formatter)
        main_logger.addHandler(handler_file)
    
    main_logger.setLevel(logging.DEBUG)
    
    return main_logger

# ============================================================================ 
Example 39
Project: SoCFoundationFlow   Author: mattaw   File: Logs.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def emit_override(self, record, **kw):
		self.terminator = getattr(record, 'terminator', '\n')
		stream = self.stream
		if unicode:
			# python2
			msg = self.formatter.format(record)
			fs = '%s' + self.terminator
			try:
				if (isinstance(msg, unicode) and getattr(stream, 'encoding', None)):
					fs = fs.decode(stream.encoding)
					try:
						stream.write(fs % msg)
					except UnicodeEncodeError:
						stream.write((fs % msg).encode(stream.encoding))
				else:
					stream.write(fs % msg)
			except UnicodeError:
				stream.write((fs % msg).encode("UTF-8"))
		else:
			logging.StreamHandler.emit(self, record) 
Example 40
Project: SoCFoundationFlow   Author: mattaw   File: Logs.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def emit_override(self, record, **kw):
		self.terminator = getattr(record, 'terminator', '\n')
		stream = self.stream
		if unicode:
			# python2
			msg = self.formatter.format(record)
			fs = '%s' + self.terminator
			try:
				if (isinstance(msg, unicode) and getattr(stream, 'encoding', None)):
					fs = fs.decode(stream.encoding)
					try:
						stream.write(fs % msg)
					except UnicodeEncodeError:
						stream.write((fs % msg).encode(stream.encoding))
				else:
					stream.write(fs % msg)
			except UnicodeError:
				stream.write((fs % msg).encode("UTF-8"))
		else:
			logging.StreamHandler.emit(self, record) 
Example 41
Project: SoCFoundationFlow   Author: mattaw   File: Logs.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def emit_override(self, record, **kw):
		self.terminator = getattr(record, 'terminator', '\n')
		stream = self.stream
		if hasattr(types, "UnicodeType"):
			# python2
			msg = self.formatter.format(record)
			fs = '%s' + self.terminator
			try:
				if (isinstance(msg, unicode) and getattr(stream, 'encoding', None)):
					fs = fs.decode(stream.encoding)
					try:
						stream.write(fs % msg)
					except UnicodeEncodeError:
						stream.write((fs % msg).encode(stream.encoding))
				else:
					stream.write(fs % msg)
			except UnicodeError:
				stream.write((fs % msg).encode("UTF-8"))
		else:
			logging.StreamHandler.emit(self, record) 
Example 42
Project: supremm   Author: ubccr   File: scripthelpers.py    (GNU Lesser General Public License v3.0) View Source Project 6 votes vote down vote up
def setuplogger(consolelevel, filename=None, filelevel=None):
    """ setup the python root logger to log to the console with defined log
        level. Optionally also log to file with the provided level """

    if filelevel == None:
        filelevel = consolelevel

    if sys.version.startswith("2.7"):
        logging.captureWarnings(True)

    rootlogger = logging.getLogger()
    rootlogger.setLevel(min(consolelevel, filelevel))

    formatter = logging.Formatter('%(asctime)s.%(msecs)03d [%(levelname)s] %(message)s', datefmt='%Y-%m-%dT%H:%M:%S')

    if filename != None:
        filehandler = logging.FileHandler(filename)
        filehandler.setLevel(filelevel)
        filehandler.setFormatter(formatter)
        rootlogger.addHandler(filehandler)

    consolehandler = logging.StreamHandler()
    consolehandler.setLevel(consolelevel)
    consolehandler.setFormatter(formatter)
    rootlogger.addHandler(consolehandler) 
Example 43
Project: swjtu-pyscraper   Author: Desgard   File: __init__.py    (MIT License) View Source Project 6 votes vote down vote up
def add_stderr_logger(level=logging.DEBUG):
    """
    Helper for quickly adding a StreamHandler to the logger. Useful for
    debugging.

    Returns the handler after adding it.
    """
    # This method needs to be in this __init__.py to get the __name__ correct
    # even if urllib3 is vendored within another package.
    logger = logging.getLogger(__name__)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(level)
    logger.debug('Added a stderr logging handler to logger: %s', __name__)
    return handler

# ... Clean up. 
Example 44
Project: CopyNet   Author: MultiPath   File: syn_vest.py    (MIT License) View Source Project 6 votes vote down vote up
def init_logging(logfile):
    formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s: %(message)s',
                                  datefmt='%m/%d/%Y %H:%M:%S'   )
    fh = logging.FileHandler(logfile)
    # ch = logging.StreamHandler()

    fh.setFormatter(formatter)
    # ch.setFormatter(formatter)
    # fh.setLevel(logging.INFO)
    # ch.setLevel(logging.INFO)
    # logging.getLogger().addHandler(ch)
    logging.getLogger().addHandler(fh)
    logging.getLogger().setLevel(logging.INFO)

    return logging

# prepare logging. 
Example 45
Project: CopyNet   Author: MultiPath   File: syntest.py    (MIT License) View Source Project 6 votes vote down vote up
def init_logging(logfile):
    formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s: %(message)s',
                                  datefmt='%m/%d/%Y %H:%M:%S'   )
    fh = logging.FileHandler(logfile)
    # ch = logging.StreamHandler()

    fh.setFormatter(formatter)
    # ch.setFormatter(formatter)
    # fh.setLevel(logging.INFO)
    # ch.setLevel(logging.INFO)
    # logging.getLogger().addHandler(ch)
    logging.getLogger().addHandler(fh)
    logging.getLogger().setLevel(logging.INFO)

    return logging

# prepare logging. 
Example 46
Project: CopyNet   Author: MultiPath   File: bst_vest.py    (MIT License) View Source Project 6 votes vote down vote up
def init_logging(logfile):
    formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s: %(message)s',
                                  datefmt='%m/%d/%Y %H:%M:%S'   )
    fh = logging.FileHandler(logfile)
    # ch = logging.StreamHandler()

    fh.setFormatter(formatter)
    # ch.setFormatter(formatter)
    # fh.setLevel(logging.INFO)
    # ch.setLevel(logging.INFO)
    # logging.getLogger().addHandler(ch)
    logging.getLogger().addHandler(fh)
    logging.getLogger().setLevel(logging.INFO)

    return logging

# prepare logging. 
Example 47
Project: CopyNet   Author: MultiPath   File: lcsts_vest.py    (MIT License) View Source Project 6 votes vote down vote up
def init_logging(logfile):
    formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s: %(message)s',
                                  datefmt='%m/%d/%Y %H:%M:%S'   )
    fh = logging.FileHandler(logfile)
    # ch = logging.StreamHandler()

    fh.setFormatter(formatter)
    # ch.setFormatter(formatter)
    # fh.setLevel(logging.INFO)
    # ch.setLevel(logging.INFO)
    # logging.getLogger().addHandler(ch)
    logging.getLogger().addHandler(fh)
    logging.getLogger().setLevel(logging.INFO)

    return logging

# prepare logging. 
Example 48
Project: CopyNet   Author: MultiPath   File: lcsts_vest_new.py    (MIT License) View Source Project 6 votes vote down vote up
def init_logging(logfile):
    formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s: %(message)s',
                                  datefmt='%m/%d/%Y %H:%M:%S'   )
    fh = logging.FileHandler(logfile)
    # ch = logging.StreamHandler()

    fh.setFormatter(formatter)
    # ch.setFormatter(formatter)
    # fh.setLevel(logging.INFO)
    # ch.setLevel(logging.INFO)
    # logging.getLogger().addHandler(ch)
    logging.getLogger().addHandler(fh)
    logging.getLogger().setLevel(logging.INFO)

    return logging

# prepare logging. 
Example 49
Project: CopyNet   Author: MultiPath   File: weibo_vest.py    (MIT License) View Source Project 6 votes vote down vote up
def init_logging(logfile):
    formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s: %(message)s',
                                  datefmt='%m/%d/%Y %H:%M:%S'   )
    fh = logging.FileHandler(logfile)
    # ch = logging.StreamHandler()

    fh.setFormatter(formatter)
    # ch.setFormatter(formatter)
    # fh.setLevel(logging.INFO)
    # ch.setLevel(logging.INFO)
    # logging.getLogger().addHandler(ch)
    logging.getLogger().addHandler(fh)
    logging.getLogger().setLevel(logging.INFO)

    return logging

# prepare logging. 
Example 50
Project: CopyNet   Author: MultiPath   File: copynet.py    (MIT License) View Source Project 6 votes vote down vote up
def init_logging(logfile):
    formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(module)s: %(message)s',
                                  datefmt='%m/%d/%Y %H:%M:%S'   )
    fh = logging.FileHandler(logfile)
    # ch = logging.StreamHandler()

    fh.setFormatter(formatter)
    # ch.setFormatter(formatter)
    # fh.setLevel(logging.INFO)
    # ch.setLevel(logging.INFO)
    # logging.getLogger().addHandler(ch)
    logging.getLogger().addHandler(fh)
    logging.getLogger().setLevel(logging.INFO)

    return logging

# prepare logging.