Python logging.handlers 模块,RotatingFileHandler() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用logging.handlers.RotatingFileHandler()

项目:bitcoin-arbitrage    作者:ucfyao    | 项目源码 | 文件源码
def init_logger(self, args):
        level = logging.INFO
        if args.verbose:
            level = logging.VERBOSE
        if args.debug:
            level = logging.DEBUG
        logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s',
                            level=level)

        Rthandler = RotatingFileHandler('arbitrage.log', maxBytes=100*1024*1024,backupCount=10)
        Rthandler.setLevel(level)
        formatter = logging.Formatter('%(asctime)-12s [%(levelname)s] %(message)s')  
        Rthandler.setFormatter(formatter)
        logging.getLogger('').addHandler(Rthandler)

        logging.getLogger("requests").setLevel(logging.WARNING)
        logging.getLogger("urllib3").setLevel(logging.WARNING)
项目:aws-sg-mngr    作者:mkazin    | 项目源码 | 文件源码
def initialize_app():
    app.logger.setLevel(logging.DEBUG)
    file_handler = RotatingFileHandler(
        'flask.log', maxBytes=1024 * 1024 * 100, backupCount=3)
    file_handler.setLevel(logging.DEBUG)
    app.logger.addHandler(file_handler)

    initialize_db()

    # Set up the flast_restplus API
    # See
    # http://michal.karzynski.pl/blog/2016/06/19/building-beautiful-restful-apis-using-flask-swagger-ui-flask-restplus/
    blueprint = Blueprint('api', __name__, url_prefix='/api')
    api.init_app(blueprint)

    # api.add_namespace(sgs_namespace)
    # api.add_namespace(cidrs_namespace)

    app.register_blueprint(blueprint)


# Set up Swagger Docs
# See http://github.com/rantav/flask-restful-swagger
# NOTE: this may not be needed. See if flask_restplus already provides this
# api = swagger.docs(Api(app), apiVersion='0.1')
项目:Solo-Mapper    作者:Escadrone    | 项目源码 | 文件源码
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)
项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def setup_logging(app):
    """Setup logging."""
    from logging.handlers import RotatingFileHandler
    from logging import Formatter
    log_file_path = app.config.get('LOG_FILE')
    log_level = app.config.get('LOG_LEVEL', logging.WARN)
    if log_file_path:  # pragma: no cover
        file_handler = RotatingFileHandler(log_file_path)
        file_handler.setFormatter(Formatter(
            '%(name)s:%(levelname)s:[%(asctime)s] %(message)s '
            '[in %(pathname)s:%(lineno)d]'
            ))
        file_handler.setLevel(log_level)
        app.logger.addHandler(file_handler)
        logger = logging.getLogger('pybossa')
        logger.setLevel(log_level)
        logger.addHandler(file_handler)
项目:guesswhat    作者:GuessWhatGame    | 项目源码 | 文件源码
def create_logger(save_path, name):

    logger = logging.getLogger()
    # Debug = write everything
    logger.setLevel(logging.DEBUG)

    formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(message)s')
    file_handler = RotatingFileHandler(save_path + '/' + name + '.stats.log', 'a', 1000000, 1)
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(formatter)
    logger.addHandler(file_handler)

    steam_handler = logging.StreamHandler()
    steam_handler.setLevel(logging.DEBUG)
    logger.addHandler(steam_handler)

    return logger

# List all the class to plot
项目:data-diode    作者:thephez    | 项目源码 | 文件源码
def configure_logging():
    logger.setLevel(logging.DEBUG)
    logger.setLevel(logging.INFO)
    #logger.setLevel(logging.WARNING)
    formatter = logging.Formatter('%(asctime)s\t%(funcName)s\t%(levelname)s\t%(message)s')

    # Console logging
    ch = logging.StreamHandler()#sys.stdout)
    ch.setFormatter(formatter)
    logger.addHandler(ch)

    # File logging (Rotating)
    try:
        rfh = RotatingFileHandler(LOGFILENAME, maxBytes=512000, backupCount=5)
        rfh.setFormatter(formatter)
        logger.addHandler(rfh)
    except Exception as e:
        logger.critical('Error accessing log file{}.  Exiting.\n\tException Message: {}'.format(LOGFILENAME, e))
        sys.exit()
项目:data-diode    作者:thephez    | 项目源码 | 文件源码
def configure_logging():
    logger.setLevel(logging.DEBUG)
    logger.setLevel(logging.INFO)
    #logger.setLevel(logging.WARNING)
    formatter = logging.Formatter('%(asctime)s\t%(funcName)s\t%(levelname)s\t%(message)s')

    # Console logging
    ch = logging.StreamHandler()#sys.stdout)
    ch.setFormatter(formatter)
    logger.addHandler(ch)

    # File logging (Rotating)
    try:
        rfh = RotatingFileHandler(LOGFILENAME, maxBytes=512000, backupCount=5)
        rfh.setFormatter(formatter)
        logger.addHandler(rfh)
    except Exception as e:
        logger.critical('Error accessing log file{}.  Exiting.\n\tException Message: {}'.format(LOGFILENAME, e))
        sys.exit()
项目:zabbix_templates    作者:BillWang139967    | 项目源码 | 文件源码
def __init__(self, filename, level="debug", logid="qiueer", mbs=20, count=10, is_console=True):
        '''
        mbs: how many MB
        count: the count of remain
        '''
        try:
            self._level = level
            #print "init,level:",level,"\t","get_map_level:",self._level
            self._filename = filename
            self._logid = logid

            self._logger = logging.getLogger(self._logid)


            if not len(self._logger.handlers):
                self._logger.setLevel(self.get_map_level(self._level))  

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

                maxBytes = int(mbs) * 1024 * 1024
                file_handler = RotatingFileHandler(self._filename, mode='a',maxBytes=maxBytes,backupCount=count)
                self._logger.setLevel(self.get_map_level(self._level))  
                file_handler.setFormatter(formatter)  
                self._logger.addHandler(file_handler)

                if is_console == True:
                    stream_handler = logging.StreamHandler(sys.stderr)
                    console_formatter = ColoredFormatter(fmt, datefmt)
                    stream_handler.setFormatter(console_formatter)
                    self._logger.addHandler(stream_handler)

        except Exception as expt:
            print expt
项目:auth-tool    作者:luciddg    | 项目源码 | 文件源码
def make_rotate_logs(self, app):
        # see http://www.cherrypy.org/wiki/Logging#CustomHandlers
        log = app.log

        # Remove the default FileHandlers if present.
        log.error_file = ""
        log.access_file = ""

        maxbytes = getattr(log, "rot_maxBytes", 10485760)
        backupcount = getattr(log, "rot_backupCount", 5)

        # Make a new RotatingFileHandler for the error log.
        fname = getattr(log, "rot_error_file", "error.log")
        h = handlers.RotatingFileHandler(fname, 'a', maxbytes, backupcount)
        h.setLevel(logging.DEBUG)
        h.setFormatter(_cplogging.logfmt)
        log.error_log.addHandler(h)

        # Make a new RotatingFileHandler for the access log.
        fname = getattr(log, "rot_access_file", "access.log")
        h = handlers.RotatingFileHandler(fname, 'a', maxbytes, backupcount)
        h.setLevel(logging.DEBUG)
        h.setFormatter(_cplogging.logfmt)
        log.access_log.addHandler(h)
项目:ALBATROSS    作者:KVSDURGASURESH    | 项目源码 | 文件源码
def _setup_logger(self, loggername, logfile, level=logging.INFO, maxFileBytes=100000):
        """
          Function for logging the entire test run details into a file specified with timestamp
          USAGE:
          _execute('loggername', 'logfile')

          loggername : The name of the logger (ex: Daily_Metrics)
          logfile    : The file name including the directory name

          NOTE:
          This method/function can be used for logging and test event into a specific logger file
          """

        self.loggername = loggername
        self.logfile = logfile
        self.maxFileBytes = maxFileBytes

        logs = logging.getLogger(loggername)
        logs.setLevel(level)
        handler = RotatingFileHandler(logfile, maxBytes=maxFileBytes, backupCount=5)
        fmt = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s", datefmt='%Y-%m-%d %H:%M:%S')
        handler.setFormatter(fmt)
        logs.addHandler(handler)
        assert isinstance(logs, object)
        return logs
项目:landscape-client    作者:CanonicalLtd    | 项目源码 | 文件源码
def test_wb_logging_setup(self):
        """
        setup_logging sets up a "landscape-sysinfo" logger which rotates every
        week and does not propagate logs to higher-level handlers.
        """
        # This hecka whiteboxes but there aren't any underscores!
        logger = getLogger("landscape-sysinfo")
        self.assertEqual(logger.handlers, [])
        setup_logging(landscape_dir=self.makeDir())
        logger = getLogger("landscape-sysinfo")
        self.assertEqual(len(logger.handlers), 1)
        handler = logger.handlers[0]
        self.assertTrue(isinstance(handler, RotatingFileHandler))
        self.assertEqual(handler.maxBytes, 500 * 1024)
        self.assertEqual(handler.backupCount, 1)
        self.assertFalse(logger.propagate)
项目:landscape-client    作者:CanonicalLtd    | 项目源码 | 文件源码
def test_setup_logging_logs_to_var_log_if_run_as_root(self):
        with mock.patch.object(os, "getuid", return_value=0) as mock_getuid, \
                mock.patch.object(
                    os.path, "isdir", return_value=False) as mock_isdir, \
                mock.patch.object(os, "mkdir") as mock_mkdir, \
                mock.patch("logging.open") as mock_open:
            logger = getLogger("landscape-sysinfo")
            self.assertEqual(logger.handlers, [])

            setup_logging()

        mock_getuid.assert_called_with()
        mock_isdir.assert_called_with("/var/log/landscape")
        mock_mkdir.assert_called_with("/var/log/landscape")
        self.assertEqual(
            mock_open.call_args_list[0][0],
            ("/var/log/landscape/sysinfo.log", "a")
        )
        handler = logger.handlers[0]
        self.assertTrue(isinstance(handler, RotatingFileHandler))
        self.assertEqual(handler.baseFilename,
                         "/var/log/landscape/sysinfo.log")
项目:bcloud    作者:wangYanJava    | 项目源码 | 文件源码
def _init_logger(log_level, maxBytes=5*1024*1024, backupCount=5):
    log_file = os.path.expanduser('~/.config/bcloud/bcloud.log')
    dir_name = os.path.dirname(log_file)
    if not os.path.exists(dir_name):
        try:
            os.makedirs(dir_name)
        except Exception:
            sys.exit(1)
    looger = logging.getLogger('bcloud')
    file_handler = RotatingFileHandler(log_file, maxBytes=maxBytes,
                                       backupCount=backupCount)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    file_handler.setFormatter(formatter)
    looger.addHandler(file_handler)
    looger.setLevel(log_level)
    return looger
项目:tv_grab_es_movistartv    作者:MovistarTV    | 项目源码 | 文件源码
def create_logger(argv):
    if not os.path.isdir(app_dir):
        os.mkdir(app_dir)
    log_path = '%s/%s' % (app_dir, log_file)
    handler = RotatingFileHandler(log_path, mode='a', maxBytes=log_size*1048576, backupCount=2, encoding=None, delay=0)
    formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%d/%m/%Y %H:%M:%S')
    handler.setFormatter(formatter)
    handler.setLevel(log_level)
    logger_h = logging.getLogger('movistartv.epg.xmltv')
    logger_h.setLevel(log_level)
    logger_h.addHandler(handler)
    logger_h.info('---------------------------------------------------')
    logger_h.info('MovistarTV EPG Grabber')
    logger_h.info('Parámetros: %s' % argv[1:])
    logger_h.info('---------------------------------------------------')
    return logger_h
项目:torrent-dl    作者:animeshkundu    | 项目源码 | 文件源码
def log_set_up(verbose=False):
    settings = get_settings()
    if not exists(settings.save_path):
        mkdir(settings.save_path)

    logfile = "%s/pyflix.log" % (settings.save_path)
    handler = RotatingFileHandler(logfile, maxBytes=1e6, backupCount=10)
    formatter = logging.Formatter("%(asctime)s  %(name)-22s  "
                                  "%(levelname)-8s %(message)s")
    handler.setFormatter(formatter)
    logger = logging.getLogger()
    logger.addHandler(handler)
    if DEBUG or verbose:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    add_stdout_handler(logger, formatter)
项目:actsys    作者:intel-ctrlsys    | 项目源码 | 文件源码
def test_set_default_log_level(self, mock_connect):
        import logging
        from datastore import get_logger
        from logging.handlers import RotatingFileHandler
        from datastore.postgresstore import PostgresLogHandler

        self.dsb.add_file_db("config-example.json", logging.CRITICAL)
        self.dsb.add_postgres_db("", logging.WARN)
        self.dsb.set_default_log_level(logging.INFO)
        self.assertEqual(DataStore.LOG_LEVEL, logging.INFO)
        logger = get_logger()
        fdbh = None
        pdbh = None
        for handler in logger.handlers:
            if isinstance(handler, RotatingFileHandler):
                fdbh = handler
            if isinstance(handler, PostgresLogHandler):
                pdbh = handler
        self.assertEqual(fdbh.level, logging.CRITICAL)
        self.assertEqual(pdbh.level, logging.WARNING)
项目:actsys    作者:intel-ctrlsys    | 项目源码 | 文件源码
def test_set_default_log_level2(self, mock_connect):
        import logging
        from datastore import get_logger
        from logging.handlers import RotatingFileHandler
        from datastore.postgresstore import PostgresLogHandler

        self.dsb.set_default_log_level(logging.FATAL)
        self.assertEqual(DataStore.LOG_LEVEL, logging.FATAL)
        self.dsb.add_file_db("config-example.json", None)
        self.dsb.add_postgres_db("")

        logger = get_logger()
        fdbh = None
        pdbh = None
        for handler in logger.handlers:
            if isinstance(handler, RotatingFileHandler):
                fdbh = handler
            if isinstance(handler, PostgresLogHandler):
                pdbh = handler
        self.assertEqual(fdbh.level, logging.FATAL)
        self.assertEqual(pdbh.level, logging.FATAL)
项目:actsys    作者:intel-ctrlsys    | 项目源码 | 文件源码
def test_log_add(self):
        import logging
        from logging.handlers import RotatingFileHandler
        logger = self.fs.get_logger()
        for index, handler in enumerate(logger.handlers):
            if not isinstance(handler, RotatingFileHandler):
                logger.handlers.pop(index)

        logger.debug("Does this work?", "knl-29", "BATS")
        logger.info("Does this work?", "knl-30", "BATS")
        logger.warning("Does this work?", "knl-31", "BATS")
        logger.error("Does this work?", "knl-33", "BATS")
        logger.critical("Does this work?", "knl-test", "BATS")
        logger.debug("Does this work?", None, "BATS")
        logger.info("Does this work?", "knl-test")
        logger.warning("Does this work?", "knl-test", None)
        logger.error("Does this work?")
        logger.critical("Does this work?", device_name="knl-test")
项目:wptagent    作者:WPO-Foundation    | 项目源码 | 文件源码
def configure_logger(stdout=True, filepath=None, level=logging.INFO):
    logger = logging.getLogger('ws4py')
    logger.setLevel(level)
    logfmt = logging.Formatter("[%(asctime)s] %(levelname)s %(message)s")

    if filepath:
        h = handlers.RotatingFileHandler(filepath, maxBytes=10485760, backupCount=3)
        h.setLevel(level)
        h.setFormatter(logfmt)
        logger.addHandler(h)

    if stdout:
        import sys
        h = logging.StreamHandler(sys.stdout)
        h.setLevel(level)
        h.setFormatter(logfmt)
        logger.addHandler(h)

    return logger
项目:deb-python-pykmip    作者:openstack    | 项目源码 | 文件源码
def _setup_logging(self, path):
        # Create the logging directory/file if it doesn't exist.
        if not os.path.exists(path):
            if not os.path.isdir(os.path.dirname(path)):
                os.makedirs(os.path.dirname(path))
            open(path, 'w').close()

        handler = handlers.RotatingFileHandler(
            path,
            mode='a',
            maxBytes=1000000,
            backupCount=5
        )
        handler.setFormatter(
            logging.Formatter(
                "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
            )
        )
        self._logger.addHandler(handler)
        self._logger.setLevel(logging.INFO)
项目:deb-python-kmip    作者:openstack    | 项目源码 | 文件源码
def _setup_logging(self, path):
        # Create the logging directory/file if it doesn't exist.
        if not os.path.exists(path):
            if not os.path.isdir(os.path.dirname(path)):
                os.makedirs(os.path.dirname(path))
            open(path, 'w').close()

        handler = handlers.RotatingFileHandler(
            path,
            mode='a',
            maxBytes=1000000,
            backupCount=5
        )
        handler.setFormatter(
            logging.Formatter(
                "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
            )
        )
        self._logger.addHandler(handler)
        self._logger.setLevel(logging.INFO)
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def get_logger(path):
    """Build file logger
    """

    if not os.path.exists(path):
        os.makedirs(path)

    log = logging.getLogger('')
    log.setLevel(logging.DEBUG)
    hdlr = handlers.RotatingFileHandler(
        filename=os.path.join(path, 'anaconda_jsonserver.log'),
        maxBytes=10000000,
        backupCount=5,
        encoding='utf-8'
    )
    formatter = logging.Formatter('%(asctime)s: %(levelname)-8s: %(message)s')
    hdlr.setFormatter(formatter)
    log.addHandler(hdlr)
    return log
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def get_logger(path):
    """Build file logger
    """

    if not os.path.exists(path):
        os.makedirs(path)

    log = logging.getLogger('')
    log.setLevel(logging.DEBUG)
    hdlr = handlers.RotatingFileHandler(
        filename=os.path.join(path, 'anaconda_jsonserver.log'),
        maxBytes=10000000,
        backupCount=5,
        encoding='utf-8'
    )
    formatter = logging.Formatter('%(asctime)s: %(levelname)-8s: %(message)s')
    hdlr.setFormatter(formatter)
    log.addHandler(hdlr)
    return log
项目:flask-api-boilerplate    作者:mikaelm1    | 项目源码 | 文件源码
def app_logger(app):
    """
    Set up logger for the app.
    :param app: The Flask app
    :return: None
    """
    format_string = (
        '=================================================================\n'
        '[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s\n'
        '=================================================================\n'
        )
    formatter = logging.Formatter(format_string)
    handler = RotatingFileHandler(filename='logs/app.log', maxBytes=10000000,
                                  backupCount=1)
    handler.setLevel(app.config['LOG_LEVEL'])
    handler.setFormatter(formatter)
    app.logger.addHandler(handler)
    return
项目:crypto-arbitrager    作者:artooze    | 项目源码 | 文件源码
def init_logger(self, args):
        level = logging.INFO
        if args.verbose:
            level = logging.VERBOSE
        if args.debug:
            level = logging.DEBUG
        logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s',
                            level=level)

        Rthandler = RotatingFileHandler('arbitrage.log', maxBytes=100*1024*1024,backupCount=10)
        Rthandler.setLevel(level)
        formatter = logging.Formatter('%(asctime)-12s [%(levelname)s] %(message)s')  
        Rthandler.setFormatter(formatter)
        logging.getLogger('').addHandler(Rthandler)

        logging.getLogger("requests").setLevel(logging.WARNING)
        logging.getLogger("urllib3").setLevel(logging.WARNING)
项目:PyPocketExplore    作者:Florents-Tselai    | 项目源码 | 文件源码
def setup_logger(name):
    # create a logging format
    formatter = logging.Formatter(
        '%(asctime)s - PID:%(process)d - %(name)s.py:%(funcName)s:%(lineno)d - %(levelname)s - %(message)s')

    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)

    # create a FileHandler
    file_handler = handlers.RotatingFileHandler('{}.log'.format(name), maxBytes=1024 * 1024 * 100, backupCount=20)
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(formatter)

    logger.addHandler(file_handler)

    # create StreamHandler
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.INFO)
    stream_handler.setFormatter(formatter)

    logger.addHandler(stream_handler)

    return logger
项目:textcorpus-generator    作者:pagesjaunes    | 项目源码 | 文件源码
def configure(p_level, p_dir=None, p_filename=None, p_max_filesize=100000, p_max_files=1, p_prefix=None):

    # default value
    logger.setLevel(logging.DEBUG)

    # String format
    if p_prefix:
        formatter = logging.Formatter('[' + p_prefix + '] %(asctime)s :: %(levelname)s :: %(module)s.%(funcName)s : %(message)s')
    else:
        formatter = logging.Formatter('%(asctime)s :: %(levelname)s :: %(module)s.%(funcName)s : %(message)s')

    # Handler console
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(p_level)
    stream_handler.setFormatter(formatter)
    logger.addHandler(stream_handler)

    if p_dir is not None:
        # File handler
        file_path = p_dir + '/' + p_filename
        file_handler = RotatingFileHandler(file_path, 'a', p_max_filesize, p_max_files)
        file_handler.setLevel(p_level)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)
项目:schematizer    作者:Yelp    | 项目源码 | 文件源码
def initialize_uwsgi_logging(log_name, log_directory, log_suffix):
    """Initialize a logger for the `uwsgi` log, sending output to a rotated
    file on disk. This is used to log errors in service startup.

    :param log_name: The name of the log file
    :param log_directory: The location on disk to write the file to
    :param log_suffix: The suffix to be appended to the log_name. This is
        useful for doing things like differentiating different users
        running the same service.
    """
    global uwsgi_initialized
    if not uwsgi_initialized:
        logger = logging.getLogger('uwsgi')

        complete_log_name = '{0}{1}'.format(log_name, log_suffix)
        path = os.path.join(log_directory, complete_log_name)
        handler = RotatingFileHandler(path, maxBytes=102400, backupCount=3)

        handler.setLevel(logging.INFO)
        handler.setFormatter(logging.Formatter(DETAILED_FORMAT))
        logger.addHandler(handler)
        uwsgi_initialized = True
项目:Awesome-Python    作者:JoMingyu    | 项目源码 | 文件源码
def before_first_request():
    def make_logger():
        handler = RotatingFileHandler('server_log.log', maxBytes=100000, backupCount=5)
        # ?? ??? ? RotatingFileHandler ???? ?? ???(????)? ???? ?

        formatter = logging.Formatter("[%(asctime)s] %(levelname)s - %(message)s")
        # ?? ???? ?? logging ??? Formatter ???? ????

        handler.setFormatter(formatter)
        # ???? ???? ?? ??

        app.logger.addHandler(handler)
        # app? logger propery? ???? ?????

        app.logger.setLevel(logging.INFO)
        # logger? level? ??? ??. ???? WARNING??, ????? ??? ????? ?? ??? ???? ????

    make_logger()
    g.logger = app.logger
    # ?? Flask? g ??? ???? ?? ??? ??? ?? ??? ???? ????? ??

    print(g.logger)

    g.logger.info('------ Logger started ------')
项目:VintageousPlus    作者:trishume    | 项目源码 | 文件源码
def __init__(self, name):
        self.logger = logging.getLogger(name)
        default_level = logging.ERROR
        user_level = self._get_log_level_from_file()
        self.logger.setLevel(user_level if user_level is not None else default_level)

        f = logging.Formatter('%(asctime)s %(levelname)-5s %(name)s %(message)s')

        consoleHandler = logging.StreamHandler()
        consoleHandler.setLevel(logging.WARNING)
        consoleHandler.setFormatter(f)
        self.logger.addHandler(consoleHandler)

        file_name = self._file_name()
        if file_name:
            fileHandler = RotatingFileHandler(file_name, maxBytes=1<<10)
            fileHandler.setFormatter(f)
            self.logger.addHandler(fileHandler)
        else:
            print("VintageousPlus: cannot find log file path: %s" % file_name)
项目:cms-htcondor-es    作者:bbockelm    | 项目源码 | 文件源码
def set_up_logging(args):
    """Configure root logger with rotating file handler"""
    logger = logging.getLogger()

    log_level = getattr(logging, args.log_level.upper(), None)
    if not isinstance(log_level, int):
        raise ValueError('Invalid log level: %s' % log_level)
    logger.setLevel(log_level)

    if not os.path.isdir(args.log_dir):
        os.system('mkdir -p %s' % args.log_dir)

    log_file = os.path.join(args.log_dir, 'spider_cms.log')
    filehandler = RotatingFileHandler(log_file, maxBytes=100000)
    filehandler.setFormatter(
        logging.Formatter('%(asctime)s : %(name)s:%(levelname)s - %(message)s'))

    logger.addHandler(filehandler)
项目:tasking-manager    作者:hotosm    | 项目源码 | 文件源码
def initialise_logger(app):
    """
    Read environment config then initialise a 2MB rotating log.  Prod Log Level can be reduced to help diagnose Prod
    only issues.
    """

    log_dir = app.config['LOG_DIR']
    log_level = app.config['LOG_LEVEL']

    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    file_handler = RotatingFileHandler(log_dir + '/tasking-manager.log', 'a', 2 * 1024 * 1024, 3)
    file_handler.setLevel(log_level)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))

    app.logger.addHandler(file_handler)
    app.logger.setLevel(log_level)
项目:aiokts    作者:ktsstudio    | 项目源码 | 文件源码
def setup_logging(self):
        if self.logging_path:
            logging.config.fileConfig(
                self.logging_path,
                disable_existing_loggers=False
            )

        if self.log_path is not None:
            old_file_handler = None
            for handler in logging.root.handlers[:]:
                if isinstance(handler, logging.FileHandler):
                    old_file_handler = handler
                    logging.root.removeHandler(handler)
            if old_file_handler is not None:
                file_handler = RotatingFileHandler(self.log_path, 'w+', 104857600, 100)
                file_handler.setFormatter(old_file_handler.formatter)
                logging.root.addHandler(file_handler)
项目:drip    作者:Dripitio    | 项目源码 | 文件源码
def process_drip_campaigns_task(conf):
    # initialize mongo connection
    mongoengine.connect(
        conf.MONGODB_SETTINGS["db"],
        host=conf.MONGODB_SETTINGS["host"],
        port=conf.MONGODB_SETTINGS["port"])
    # get log directory and name and initialize logger
    log_dir = conf.LOG_SETTINGS["log_dir"]
    log_name = conf.LOG_SETTINGS["log_name"]
    file_handler = RotatingFileHandler(
        filename=os.path.join(log_dir, log_name + ".log"),
        maxBytes=200000000,  # 200MB
        backupCount=20,  # 20*200MB=4GB=nice
    )
    logger = logging.getLogger(name=log_name)
    logger.addHandler(file_handler)
    logger.setLevel(logging.INFO)
    # run the processor
    process_campaigns(logger)
项目:SafeEyes    作者:slgobinath    | 项目源码 | 文件源码
def intialize_logging(debug):
    """
    Initialize the logging framework using the Safe Eyes specific configurations.
    """
    # Configure logging.
    root_logger = logging.getLogger()
    log_formatter = logging.Formatter('%(asctime)s [%(levelname)s]:[%(threadName)s] %(message)s')

    # Append the logs and overwrite once reached 1MB
    if debug:
        # Log to file
        file_handler = RotatingFileHandler(LOG_FILE_PATH, maxBytes=1024 * 1024, backupCount=5, encoding=None, delay=0)
        file_handler.setFormatter(log_formatter)
        # Log to console
        console_handler = logging.StreamHandler()
        console_handler.setFormatter(log_formatter)

        root_logger.setLevel(logging.DEBUG)
        root_logger.addHandler(console_handler)
        root_logger.addHandler(file_handler)
    else:
        root_logger.propagate = False
项目:eesa    作者:EqualExperts    | 项目源码 | 文件源码
def __init__(self, connection_string, release_altitude, relative_altitude):
        self.connection_string = connection_string
        self.closed_pwm = 1850
        self.open_pwm = 1200
        self.twitch=20
        self.release_servo_number = 9 # aux 1
        self.test_servo_numbers = [11,12,13]
        self.release_altitude = release_altitude
        self.relative_altitude = relative_altitude
        self.current_test_servo_pwm = self.closed_pwm
        self.released = False
        self.flight_mission_started = False

        logging.basicConfig(format='%(asctime)-15s %(clientip)s %(user)-8s %(message)s')
        self.logger = logging.getLogger('mission_log')
        self.logger.addHandler(RotatingFileHandler('mission.log', maxBytes=10000000, backupCount=0))
项目:mysql_streamer    作者:Yelp    | 项目源码 | 文件源码
def initialize_uwsgi_logging(log_name, log_directory, log_suffix):
    """Initialize a logger for the `uwsgi` log, sending output to a rotated
    file on disk. This is used to log errors in service startup.

    :param log_name: The name of the log file
    :param log_directory: The location on disk to write the file to
    :param log_suffix: The suffix to be appended to the log_name. This is
        useful for doing things like differentiating different users
        running the same service.
    """
    global uwsgi_initialized
    if not uwsgi_initialized:
        logger = logging.getLogger('uwsgi')

        complete_log_name = '{0}{1}'.format(log_name, log_suffix)
        path = os.path.join(log_directory, complete_log_name)
        handler = RotatingFileHandler(path, maxBytes=102400, backupCount=3)

        handler.setLevel(logging.INFO)
        handler.setFormatter(logging.Formatter(DETAILED_FORMAT))
        logger.addHandler(handler)
        uwsgi_initialized = True
项目:fleaker    作者:croscon    | 项目源码 | 文件源码
def _register_file_logger(self):
        if not self.config['LOGGING_FILE_PATH']:
            return

        formatter = self.config['LOGGING_FILE_FORMATTER']
        handler = RotatingFileHandler(
            self.config['LOGGING_FILE_PATH'],
            maxBytes=self.config['LOGGING_FILE_MAX_SIZE'],
            backupCount=self.config['LOGGING_FILE_MAX_BACKUPS']
        )
        handler.setLevel(self.config['LOGGING_FILE_LEVEL'])

        if isinstance(formatter, logging.Formatter):
            handler.setFormatter(formatter)

        self.logger.addHandler(handler)
项目:JzUnit    作者:hongweifuture    | 项目源码 | 文件源码
def outputLog(self):
        """
        output log to console and file
        """
        if self.outputConsole == 1 and not self.logger.handlers:
            # if true ,it should output log in console
            # if logger.handlers list is empty,add list,or writing log

            console_handler = logging.StreamHandler()
            console_handler.setFormatter(self.formatter)
            self.logger.setLevel(self.outputConsole_level)
            self.logger.addHandler(console_handler)

            if self.outputFile == 1:
                self.file_handler = RotatingFileHandler(self.log_file_path, maxBytes=self.maxBytes, backupCount=self.backupCount)
                # defind RotatingFileHandler: log output pathsingle file max bytes, max backup number.
                self.file_handler.setFormatter(self.formatter)
                self.logger.setLevel(self.outputFile_level)
                self.logger.addHandler(self.file_handler)
            else:
                pass

        return self.logger
项目:pycryptoki    作者:gemalto    | 项目源码 | 文件源码
def configure_logging(logfile=None):
    """
    Setup logging. If a log file is specified, will log to that file.

    :param str logfile: Log file path/name to use for logging.
    :return: Configured logger.
    """
    logger = logging.getLogger("pycryptoki")
    logger.setLevel(getattr(logging, args.loglevel))
    if not logfile:
        handler = logging.StreamHandler(sys.stdout)
    else:
        # 5 megabyte file, max of 10 files.
        handler = RotatingFileHandler(logfile, maxBytes=MAX_LOG_SIZE, backupCount=10)
    handler.setFormatter(logging.Formatter('%(asctime)s:%(name)s:%(levelname)s: %(message)s'))
    logger.addHandler(handler)
    return logger
项目:Netkeeper    作者:1941474711    | 项目源码 | 文件源码
def InitLog():
    logging.getLogger().setLevel(logging.ERROR)
    RtHandler = RotatingFileHandler(filename=C_LOG_DIR, maxBytes=C_LOG_SIZE, backupCount=C_LOG_FILES)
    RtHandler.setLevel(logging.ERROR)
    RtHandler.setFormatter(logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s'))
    logging.getLogger().addHandler(RtHandler)
    logging.error('??????')


# ??????
项目:StratoBalloon    作者:delattreb    | 项目源码 | 文件源码
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)
项目:mongodb_backup_script    作者:hxt168    | 项目源码 | 文件源码
def __init__(self, debug, log_name, log_level, logger):
        self.logger = logging.getLogger(logger)
        if debug:
            logfile = os.path.join(os.getcwd(), log_name)
            max_log_size = 100*1024*1024 #Bytes
            backup_count = 5
            format = \
            "%(asctime)s %(levelname)-8s[%(filename)s:%(lineno)d(%(funcName)s)] %(message)s"
            hdlr = RotatingFileHandler(logfile,
                                          mode='a',
                                          maxBytes=max_log_size,
                                          backupCount=backup_count)
            formatter = logging.Formatter(format)
            hdlr.setFormatter(formatter)
            self.logger.addHandler(hdlr)
            if "DEBUG" == log_level.upper():
                self.logger.setLevel(logging.DEBUG)
            elif "INFO" == log_level.upper():
                self.logger.setLevel(logging.INFO)
            elif "WARNING" == log_level.upper():
                self.logger.setLevel(logging.WARNING)
            elif "ERROR" == log_level.upper():
                self.logger.setLevel(logging.ERROR)
            elif "CRITICAL" == log_level.upper():
                self.logger.setLevel(logging.CRITICAL)
            else:
                self.logger.setLevel(logging.ERROR)
        else:
            self.logger.addHandler(EmptyHandler())
项目:zabbix_manager    作者:BillWang139967    | 项目源码 | 文件源码
def __init__(self, filename, level="debug", logid="qiueer", mbs=20, count=10, is_console=True):
        '''
        mbs: how many MB
        count: the count of remain
        '''
        try:
            self._level = level
            #print "init,level:",level,"\t","get_map_level:",self._level
            self._filename = filename
            self._logid = logid

            self._logger = logging.getLogger(self._logid)


            if not len(self._logger.handlers):
                self._logger.setLevel(self.get_map_level(self._level))  

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

                maxBytes = int(mbs) * 1024 * 1024
                file_handler = RotatingFileHandler(self._filename, mode='a',maxBytes=maxBytes,backupCount=count)
                self._logger.setLevel(self.get_map_level(self._level))  
                file_handler.setFormatter(formatter)  
                self._logger.addHandler(file_handler)

                if is_console == True:
                    stream_handler = logging.StreamHandler(sys.stderr)
                    console_formatter = ColoredFormatter(fmt, datefmt)
                    stream_handler.setFormatter(console_formatter)
                    self._logger.addHandler(stream_handler)

        except Exception as expt:
            print expt
项目:TGIF-Release    作者:raingo    | 项目源码 | 文件源码
def setup_logging():
    if not app.debug:
        import logging
        from logging.handlers import RotatingFileHandler
        from logging import Formatter
        file_handler = RotatingFileHandler(filename = 'logs/flask.log', maxBytes=100000000, backupCount=10)
        file_handler.setLevel(logging.INFO)
        file_handler.setFormatter(Formatter(
            '%(asctime)s %(levelname)s: %(message)s '
                '[in %(pathname)s:%(lineno)d]'
                ))
        app.logger.addHandler(file_handler)
        app.logger.setLevel(logging.INFO)
项目:zhihu_crawler    作者:gavin66    | 项目源码 | 文件源码
def generate(self):
        if not os.path.isdir(os.path.dirname(LOG_PATH)):
            os.makedirs(os.path.dirname(LOG_PATH))
        log_handler = logging.getLogger('zhihu')
        log_handler.setLevel(logging.INFO)
        formatter = logging.Formatter(fmt='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                                      datefmt='%Y-%m-%d %H:%M:%S')
        file_handler = RotatingFileHandler(self._path, mode='a', maxBytes=10 * 1024 * 1024, backupCount=6,
                                           encoding='utf-8')
        file_handler.setFormatter(formatter)
        log_handler.addHandler(file_handler)
        return log_handler
项目:flask_ishuhui    作者:lufficc    | 项目源码 | 文件源码
def init_logger(app):
    handler = RotatingFileHandler('logs/ishuhui.log', maxBytes=1024 * 1024 * 2, backupCount=2)
    logging_format = logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
    handler.setFormatter(logging_format)
    app.logger.addHandler(handler)
    app.logger.setLevel(logging.INFO)
项目:dict_based_learning    作者:tombosc    | 项目源码 | 文件源码
def copy_streams_to_file(log_file, stdout=True, stderr=True):
    logger = logging.getLogger("_copy_stdout_stderr_to_file")
    logger.handlers = []
    logger.setLevel(logging.DEBUG)
    format = logging.Formatter("%(message)s")
    fh = handlers.RotatingFileHandler(log_file, maxBytes=(1048576 * 5), backupCount=7)
    fh.setFormatter(format)
    logger.addHandler(fh)

    if stderr:
        sys.stderr = LoggerWriter(logger.warning)

    if stdout:
        sys.stdout = LoggerWriter(logger.info)
项目:zabbix_templates    作者:BillWang139967    | 项目源码 | 文件源码
def __init__(self, filename, level="debug", logid="qiueer", mbs=20, count=10, is_console=True):
        '''
        mbs: how many MB
        count: the count of remain
        '''
        try:
            self._level = level
            #print "init,level:",level,"\t","get_map_level:",self._level
            self._filename = filename
            self._logid = logid

            self._logger = logging.getLogger(self._logid)


            if not len(self._logger.handlers):
                self._logger.setLevel(self.get_map_level(self._level))  

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

                maxBytes = int(mbs) * 1024 * 1024
                file_handler = RotatingFileHandler(self._filename, mode='a',maxBytes=maxBytes,backupCount=count)
                self._logger.setLevel(self.get_map_level(self._level))  
                file_handler.setFormatter(formatter)  
                self._logger.addHandler(file_handler)

                if is_console == True:
                    stream_handler = logging.StreamHandler(sys.stderr)
                    console_formatter = ColoredFormatter(fmt, datefmt)
                    stream_handler.setFormatter(console_formatter)
                    self._logger.addHandler(stream_handler)

        except Exception as expt:
            print expt