Add file_handler to logger
492274
def log_to_file(log_path, log_urllib=False, limit=None):
    
    log_path = log_path
    file_handler = logging.FileHandler(log_path)
    if limit:
        file_handler = RotatingFileHandler(
            log_path,
            mode='a',
            maxBytes=limit * 1024 * 1024,
            backupCount=2,
            encoding=None,
            delay=0)
    fmt = '[%(asctime)s %(filename)18s] %(levelname)-7s - %(message)7s'
    date_fmt = '%Y-%m-%d %H:%M:%S'
    formatter = logging.Formatter(fmt, datefmt=date_fmt)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)
    if log_urllib:
        urllib_logger.addHandler(file_handler)
        urllib_logger.setLevel(logging.DEBUG)
1006505
def _add_filehandler(logger, logpath, formatter=None, name="Bench"):
    
    formatter = formatter if formatter else BenchFormatterWithType(loggername=name)
    handler = _get_filehandler_with_formatter(logpath, formatter)
    config = LOGGING_CONFIG.get(name, {}).get("file", DEFAULT_LOGGING_CONFIG.get("file"))
    handler.setLevel(getattr(logging, config.get("level", "DEBUG")))
    logger.addHandler(handler)
    return logger
524733
def install_handler(self, app):
        """"""
        # Configure python logging
        if app.config['LOGGING_CONSOLE_PYWARNINGS']:
            self.capture_pywarnings(logging.StreamHandler())

        if app.config['LOGGING_CONSOLE_LEVEL'] is not None:
            for h in app.logger.handlers:
                h.setLevel(app.config['LOGGING_CONSOLE_LEVEL'])

        # Add request_id to log record
        app.logger.addFilter(add_request_id_filter)
974334
def add_logging_handler(handler, format_='file'):
    
    global __UTOOL_ROOT_LOGGER__
    if __UTOOL_ROOT_LOGGER__ is None:
        builtins.print('[WARNING] logger not started, cannot add handler')
        return
    # create formatter and add it to the handlers
    #logformat = '%Y-%m-%d %H:%M:%S'
    #logformat = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    timeformat = '%H:%M:%S'
    if format_ == 'file':
        logformat = '[%(asctime)s]%(message)s'
    elif format_ == 'stdout':
        logformat = '%(message)s'
    else:
        raise AssertionError('unknown logging format_: %r' % format_)
    # Create formatter for handlers
    formatter = logging.Formatter(logformat, timeformat)
    handler.setLevel(logging.DEBUG)
    handler.setFormatter(formatter)
    __UTOOL_ROOT_LOGGER__.addHandler(handler)
1107806
def capture(package, prefix, modules=[], level=logging.DEBUG):
    
    handler = LogFileHandler(package, prefix)
    formatter = logging.Formatter(FORMAT)
    handler.setFormatter(formatter)
    modules = set(modules + ['loadkit'])

    for logger in modules:
        if not hasattr(logger, 'addHandler'):
            logger = logging.getLogger(logger)
        logger.setLevel(level=level)
        logger.addHandler(handler)

    return handler
1270115
def setup_stream_handlers(conf):
    """"""
    class StdoutFilter(logging.Filter):
        def filter(self, record):
            return record.levelno in (logging.DEBUG, logging.INFO)

    log.handlers = []

    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setLevel(logging.WARNING)
    stdout_handler.addFilter(StdoutFilter())
    if conf.debug:
        stdout_handler.setLevel(logging.DEBUG)
    elif conf.verbose:
        stdout_handler.setLevel(logging.INFO)
    else:
        stdout_handler.setLevel(logging.WARNING)
    log.addHandler(stdout_handler)

    stderr_handler = logging.StreamHandler(sys.stderr)
    msg_format = "%(levelname)s: %(message)s"
    stderr_handler.setFormatter(logging.Formatter(fmt=msg_format))
    stderr_handler.setLevel(logging.WARNING)
    log.addHandler(stderr_handler)
315157
def patch_python_logging_handlers():
    '''
    
    '''
    logging.StreamHandler = StreamHandler
    logging.FileHandler = FileHandler
    logging.handlers.SysLogHandler = SysLogHandler
    logging.handlers.WatchedFileHandler = WatchedFileHandler
    logging.handlers.RotatingFileHandler = RotatingFileHandler
    if sys.version_info >= (3, 2):
        logging.handlers.QueueHandler = QueueHandler
1165190
def configure_file_logger(name, log_dir, log_level=logging.DEBUG):
    """"""
    from .srothandler import SizeRotatingFileHandler

    root = logging.getLogger()
    root.setLevel(log_level)
    handler = SizeRotatingFileHandler(os.path.join(log_dir, '%s.log' % name))
    handler.setLevel(log_level)
    handler.setFormatter(logging.Formatter(LOG_FORMAT_STANDARD))

    root.addHandler(handler)
1120373
def get_logger(name=None):
    '''
    
    '''
    logger = logging.getLogger(name)
    if len(logger.handlers) == 0:
        logger = add_stream_handler(logger)
    return logger
1102006
def get_logger(name=None, level=None, stream=DEFAULT_STREAM,
               clobber_root_handler=True, logger_factory=None,
               wrapper_class=None):
    """"""
    _configure_logger(
        logger_factory=logger_factory,
        wrapper_class=wrapper_class)
    log = structlog.get_logger(name)
    root_logger = logging.root
    if log == root_logger:
        if not _has_streamhandler(root_logger, level=level, stream=stream):
            stream_handler = logging.StreamHandler(stream)
            stream_handler.setLevel(level)
            stream_handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT))
            root_logger.addHandler(stream_handler)
        else:
            if clobber_root_handler:
                for handler in root_logger.handlers:
                    handler.setFormatter(logging.Formatter(fmt=LOG_FORMAT))
    if level:
        log.setLevel(level)
    return log
431987
def add_log_file(path):
    
    logfile_handler = RotatingFileHandler(
        path, maxBytes=50000, backupCount=2)
    formatter = logging.Formatter(
        fmt='%(asctime)s %(levelname)s %(module)s - %(message)s',
        datefmt="%d-%b-%Y %H:%M:%S")
    logfile_handler.setFormatter(formatter)
    geoparse_logger.addHandler(logfile_handler)
468265
def _logger():
        """"""
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)
        ch = logging.StreamHandler(sys.stdout)
        ch.setLevel(logging.DEBUG)
        logger.addHandler(ch)
        return logger
288639
def set_log_rotate_handler(self, set_file):
        '''

        '''
        if hasattr(self, 'debug_handler'):
            if set_file:
                self.log.addHandler(self.debug_handler)
                self.log.addHandler(self.error_handler)
            else:
                try:
                    self.log.removeHandler(self.error_handler)
                    self.log.removeHandler(self.debug_handler)
                except Exception:
                    pass
        else:
            self.log.debug('The file log handlers were not created. It is not\
                           possible to write to the log files.')
231563
def handle(job_id, log_level='info', log_file=None):
    
    handlers = [LogDatabaseHandler(job_id)]  # log on db always
    if log_file is None:
        # add a StreamHandler if not already there
        if not any(h for h in logging.root.handlers
                   if isinstance(h, logging.StreamHandler)):
            handlers.append(LogStreamHandler(job_id))
    else:
        handlers.append(LogFileHandler(job_id, log_file))
    for handler in handlers:
        logging.root.addHandler(handler)
    init(job_id, LEVELS.get(log_level, logging.WARNING))
    try:
        yield
    finally:
        # sanity check to make sure that the logging on file is working
        if (log_file and log_file != os.devnull and
                os.path.getsize(log_file) == 0):
            logging.root.warn('The log file %s is empty!?' % log_file)
        for handler in handlers:
            logging.root.removeHandler(handler)
18503
def get_logger(
        name, file_name=None, stream=None, template=None, propagate=False):
    

    logger = logging.getLogger(name)

    if propagate is not None:
        logger.propagate = propagate

    for handler in logger.handlers:
        logger.removeHandler(handler)

    if not template:
        template = "%(name)s %(process)s %(levelname)s %(message)s"

    formatter = logging.Formatter(template)

    if not file_name and not stream:
        stream = sys.stdout

    handlers = []

    if stream is not None:

        handlers.append(logging.StreamHandler(stream=stream))

    if file_name is not None:

        if os.path.isdir(os.path.dirname(file_name)):
            handlers.append(logging.FileHandler(file_name))
        else:
            print("ERROR: Can't open log file {}".format(file_name))

    for ch in handlers:
        ch.setFormatter(formatter)
        logger.addHandler(ch)

    logger.setLevel(logging.INFO)

    return logger
1161362
def configure_logger(logger, filename, folder, log_level):
    '''
    '''
    fmt = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
    if folder is not None:
        log_file = os.path.join(folder, filename)
        hdl = logging.FileHandler(log_file)
        hdl.setFormatter(fmt)
        hdl.setLevel(log_level)
        logger.addHandler(hdl)
    shdl = logging.StreamHandler()
    shdl.setLevel(log_level)
    shdl.setFormatter(fmt)
    logger.addHandler(shdl)
    logger.setLevel(log_level)
185257
def create_recipe_file_logger(logger, logfile, logformat):
    """"""
    recipe_formatter = logging.Formatter(logformat)
    fh = logging.FileHandler(logfile, mode='w')
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(recipe_formatter)
    return fh