Esempio n. 1
0
def configure_logging(app):
    """Configure file(info) and email(error) logging."""
    if app.debug or app.testing:
        # Skip debug and test mode. Just check standard output.
        return

    # Set info level on logger, which might be overwritten by handers.
    # Suppress DEBUG messages.
    app.logger.setLevel(INFO)

    info_file_handler = StreamHandler()
    info_file_handler.setLevel(INFO)
    info_file_handler.setFormatter(
        Formatter('%(asctime)s %(levelname)s: %(message)s '
                  '[in %(pathname)s:%(lineno)d]'))
    app.logger.addHandler(info_file_handler)

    # Testing
    # app.logger.info("testing info.")
    # app.logger.warn("testing warn.")
    # app.logger.error("testing error.")

    mail_handler = SMTPHandler(
        app.config['MAIL_SERVER'], app.config['MAIL_USERNAME'],
        app.config['ADMINS'], 'O_ops... %s failed!' % app.config['PROJECT'],
        (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']))
    mail_handler.setLevel(ERROR)
    mail_handler.setFormatter(
        Formatter('%(asctime)s %(levelname)s: %(message)s '
                  '[in %(pathname)s:%(lineno)d]'))
    app.logger.addHandler(mail_handler)
Esempio n. 2
0
    def init_app(cls, app):
        Config.init_app(app)

        # email errors to the administrators
        import logging
        from logging.handlers import SMTPHandler
        from logging import Formatter
        credentials = None
        secure = None
        if getattr(cls, 'MAIL_USERNAME', None) is not None:
            credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD)
            if getattr(cls, 'MAIL_USE_TLS', None):
                secure = ()
        mail_handler = SMTPHandler(mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT),
                                   fromaddr=cls.CONF_MAIL_SENDER,
                                   toaddrs=[cls.CONF_ADMIN],
                                   subject=cls.CONF_MAIL_SUBJECT_PREFIX +
                                   ' Production Application Error!',
                                   credentials=credentials,
                                   secure=secure)
        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(
            Formatter('''
        Message type:       %(levelname)s
        Location:           %(pathname)s:%(lineno)d
        Module:             %(module)s
        Function:           %(funcName)s
        Time:               %(asctime)s

        Message:

        %(message)s
        '''))
        app.logger.addHandler(mail_handler)
Esempio n. 3
0
def register_logging(app):
    class RequestFormatter(logging.Formatter):
        def format(self, record):
            record.url = request.url
            record.remote_addr = request.remote_addr
            return super(RequestFormatter, self).format(record)

    request_formatter = RequestFormatter(
        '[%(asctime)s] %(remote_addr)s requested %(url)s\n'
        '%(levelname)s in %(module)s: %(message)s')

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

    file_handler = RotatingFileHandler(os.path.join(basedir,
                                                    'logs/bluelog.log'),
                                       maxBytes=10 * 1024 * 1024,
                                       backupCount=10)
    file_handler.setFormatter(formatter)
    file_handler.setLevel(logging.INFO)

    mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'],
                               fromaddr=app.config['MAIL_USERNAME'],
                               toaddrs=['ADMIN_EMAIL'],
                               subject='Bluelog Application Error',
                               credentials=(app.config['MAIL_USERNAME'],
                                            app.config['MAIL_PASSWORD']))
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(request_formatter)

    if not app.debug:
        app.logger.addHandler(mail_handler)
        app.logger.addHandler(file_handler)
Esempio n. 4
0
File: app.py Progetto: srt32/rodeo
def configure_logging(app):
    """Configure file(info) and email(error) logging."""
    if app.debug or app.testing:
        # Skip debug and test mode. Just check standard output.
        return

    # Set info level on logger, which might be overwritten by handers.
    # Suppress DEBUG messages.
    app.logger.setLevel(INFO)

    info_file_handler = StreamHandler()
    info_file_handler.setLevel(INFO)
    info_file_handler.setFormatter(Formatter(
        '%(asctime)s %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]')
    )
    app.logger.addHandler(info_file_handler)

    # Testing
    # app.logger.info("testing info.")
    # app.logger.warn("testing warn.")
    # app.logger.error("testing error.")

    mail_handler = SMTPHandler(app.config['MAIL_SERVER'],
                               app.config['MAIL_USERNAME'],
                               app.config['ADMINS'],
                               'O_ops... %s failed!' % app.config['PROJECT'],
                               (app.config['MAIL_USERNAME'],
                                app.config['MAIL_PASSWORD']))
    mail_handler.setLevel(ERROR)
    mail_handler.setFormatter(Formatter(
        '%(asctime)s %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]')
    )
    app.logger.addHandler(mail_handler)
Esempio n. 5
0
def configure_logger(app):
    if not app.debug:
        mail_handler = SMTPHandler('127.0.0.1',
                                   '*****@*****.**',
                                   app.config['MAIL_ERROR_BOXES'],
                                   'Application Failed')
        mail_handler.setLevel(logging.WARNING)
        mail_handler.setFormatter(logging.Formatter('''
        Message type:       %(levelname)s
        Location:           %(pathname)s:%(lineno)d
        Module:             %(module)s
        Function:           %(funcName)s
        Time:               %(asctime)s

        Message:

        %(message)s
        '''))
        app.logger.addHandler(mail_handler)

        create_logs_root(app)
        file_handler = logging.FileHandler(app.config['LOG_FILE'])
        file_handler.setLevel(logging.WARNING)
        file_handler.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]'
        ))
        app.logger.addHandler(file_handler)
Esempio n. 6
0
def _setup_error_mail_handler(app):

    class ContextualFilter(logging.Filter):
        def filter(self, log_record):
            log_record.url = request.path
            log_record.method = request.method
            log_record.ip = request.environ.get("REMOTE_ADDR")
            log_record.headers = request.headers
            return True

    mailhost = tuple(config.get('smtp.server', 'localhost').split(":"))
    mail_handler = SMTPHandler(
        mailhost=mailhost,
        fromaddr=config.get('error_email_from'),
        toaddrs=[config.get('email_to')],
        subject='Application Error'
    )

    mail_handler.setFormatter(logging.Formatter('''
Time:               %(asctime)s
URL:                %(url)s
Method:             %(method)s
IP:                 %(ip)s
Headers:            %(headers)s

'''))

    context_provider = ContextualFilter()
    app.logger.addFilter(context_provider)
    app.logger.addHandler(mail_handler)
Esempio n. 7
0
def configure_logging(app):
    import logging
    from logging.handlers import RotatingFileHandler, SMTPHandler

    app.logger.setLevel(logging.INFO)

    log_path = os.path.join(app.instance_path, 'info.log')
    file_handler = RotatingFileHandler(log_path,
                                       maxBytes=100000, backupCount=10)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]'))

    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)

    try:
        mail_handler = SMTPHandler(app.config['MAIL_SERVER'],
                                   app.config['MAIL_FROM'],
                                   app.config['ADMINS'],
                                   'Error on %s' % app.config['SERVER_NAME'],
                                   (app.config['MAIL_USERNAME'],
                                    app.config['MAIL_PASSWORD']),
                                   ())
        mail_handler.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]'))

        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
    except KeyError:
        pass
Esempio n. 8
0
def add_mail_handler(app):
    mail_handler = SMTPHandler(mailhost=(app.config['MAIL_HOST'],
                                         app.config['MAIL_PORT']),
                               fromaddr=app.config['MAIL_FROMADDR'],
                               toaddrs=app.config['ADMINS_MAIL_LIST'],
                               subject='Server error',
                               credentials=(app.config['MAIL_USERNAME'],
                                            app.config['MAIL_PASSWORD']),
                               secure=())

    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(
        logging.Formatter('''
                                        Message type:       %(levelname)s
                                        Location:           %(pathname)s:%(lineno)d
                                        Module:             %(module)s
                                        Function:           %(funcName)s
                                        Time:               %(asctime)s

                                        Message:

                                        %(message)s
                                        '''))

    app.logger.addHandler(mail_handler)
def register_logging(app):
    # 文件日志
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler = RotatingFileHandler(filename='./logs/flaskdemo.log',
                                       maxBytes=10 * 1024 * 1024,
                                       backupCount=10)
    file_handler.setFormatter(formatter)
    file_handler.setLevel(logging.INFO)
    app.logger.setLevel(logging.INFO)

    default_handler.setLevel(logging.INFO)

    class RequestFormatter(logging.Formatter):
        def format(self, record) -> str:
            record.url = request.url
            record.remote_addr = request.remote_addr
            return super(RequestFormatter, self).format(record)

    request_formatter = RequestFormatter(
        '[%(asctime)s] %(remote_addr)s requested %(url)s\n%(levelname)s in %(module)s: %(message)s'
    )
    mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'],
                               fromaddr=app.config['MAIL_USERNAME'],
                               toaddrs=app.config['ALBUMY_ADMIN_EMAIL'],
                               subject='Application Error',
                               credentials=(app.config['MAIL_USERNAME'],
                                            app.config['MAIL_PASSWORD']))
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(request_formatter)
    if not app.debug:
        app.logger.addHandler(file_handler)
        app.logger.addHandler(default_handler)
        app.logger.addHandler(mail_handler)
Esempio n. 10
0
def __setup_advanced_logging() -> None:
    """Sets up advanced logging over mail and Discord
    """
    if config.getboolean("logging", "enable_mail_logging"):
        mailcfg = dict(config.items("mail_logging"))
        mailhost = (mailcfg["mailhost"], mailcfg["mailport"])
        toaddrs = mailcfg["toaddrs"].split(",")
        credentials = (mailcfg["username"], mailcfg["password"])
        eh = SMTPHandler(mailhost=mailhost,
                         fromaddr=mailcfg["fromaddr"],
                         toaddrs=toaddrs,
                         subject=mailcfg["subject"],
                         credentials=credentials,
                         secure=(),
                         timeout=config.getint("mail_logging",
                                               "timeout"))
        eh.setFormatter(formatter)
        eh.setLevel(logging.WARNING)
        logger.addHandler(eh)

    if config.getboolean("logging", "enable_discord_logging"):
        avatar_url = config["discord_logging"]["avatar_url"]
        avatar_url = avatar_url if avatar_url else None
        dh = DiscordHandler(config["discord_logging"]["username"],
                            config["discord_logging"]["webhook_url"],
                            avatar_url)
        dh.setFormatter(formatter)
        dh.setLevel(logging.WARNING)
        logger.addHandler(dh)
Esempio n. 11
0
def configure_logging(app):
    """Configure file(info) and email(error) logging."""

    if app.debug or app.testing:
        # skip debug and test mode.
        return

    import logging
    from logging.handlers import RotatingFileHandler, SMTPHandler

    # Set info level on logger, which might be overwritten by handers.
    app.logger.setLevel(logging.INFO)

    debug_log = os.path.join(app.root_path, app.config["DEBUG_LOG"])
    file_handler = logging.handlers.RotatingFileHandler(debug_log, maxBytes=100000, backupCount=10)
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(
        logging.Formatter("%(asctime)s %(levelname)s: %(message)s " "[in %(pathname)s:%(lineno)d]")
    )
    app.logger.addHandler(file_handler)

    ADMINS = ["*****@*****.**"]
    mail_handler = SMTPHandler(
        app.config["MAIL_SERVER"],
        app.config["MAIL_USERNAME"],
        ADMINS,
        "O_ops... %s failed!" % PROJECT,
        (app.config["MAIL_USERNAME"], app.config["MAIL_PASSWORD"]),
    )
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(
        logging.Formatter("%(asctime)s %(levelname)s: %(message)s " "[in %(pathname)s:%(lineno)d]")
    )
    app.logger.addHandler(mail_handler)
Esempio n. 12
0
    def init_app(self, app):
        handlers = []
        filehandler = RotatingFileHandler(filename=app.config['LOG_FILE_LOC'],
                                          maxBytes=1000000, backupCount=5)
        formatter = logging.Formatter(
            "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s")
        filehandler.setLevel(logging.INFO)
        if app.config['TESTING']:
            filehandler.setLevel(logging.ERROR)
        filehandler.setFormatter(formatter)

        logging.basicConfig()
        handlers.append(filehandler)

        if not app.debug:
            mail_handler = SMTPHandler(
                (app.config['INTERNAL_MAILS_SERVER'],
                 app.config['INTERNAL_MAILS_PORT']),
                app.config['INTERNAL_MAILS_SERVER_USERNAME'],
                app.config['NIGHTS_WATCH'],
                app.config.get('SERVER_ERROR_MAIL_SUBJECT',
                               'Server error'),
                credentials=(app.config['INTERNAL_MAILS_SERVER_USERNAME'],
                             app.config['INTERNAL_MAILS_SERVER_PASSWORD']),
                secure=())
            mail_handler.setLevel(logging.ERROR)
            mail_handler.setFormatter(formatter)
            handlers.append(mail_handler)
        self.logging_queue_listener = QueueListener(
            self.logging_queue, *handlers)
        app.logger.addHandler(self.logging_queue_handler)
Esempio n. 13
0
    def init_app(cls, app):
        Config.init_app(app)

        # email errors to the administrators
        import logging
        from logging.handlers import SMTPHandler, RotatingFileHandler

        fmt = logging.Formatter(
            fmt='[%(asctime)s] %(levelname)s %(filename)s: %(lineno)d (%(funcName)s, %(threadName)s):\n %(message)s')

        credentials = None
        secure = None
        if app.config.get('MAIL_USERNAME') is not None:
            credentials = (app.config['MAIL_USERNAME'], app.config.get('MAIL_PASSWORD'))
            if app.config.get('MAIL_USE_TLS'):
                secure = ()
        mail_handler = SMTPHandler(
            mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
            fromaddr=app.config['MAIL_DEFAULT_SENDER'],
            toaddrs=[app.config['APP_ADMIN']],
            subject=app.config['APP_EMAIL_SUBJECT_PREFIX'] + ' Application Error',
            credentials=credentials,
            secure=secure)
        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(fmt)
        app.logger.addHandler(mail_handler)

        filehandler = RotatingFileHandler(
            filename=os.path.join(app.config['DATABASE_DIR'], 'farmatempapp.log'), maxBytes=10000000,
            backupCount=10)
        filehandler.setLevel(logging.INFO)
        filehandler.setFormatter(fmt)
        app.logger.addHandler(filehandler)
Esempio n. 14
0
    def init_app(cls, app):
        Config.init_app(app)
        # 把错误通过电子邮件发送给管理员
        import logging
        from logging.handlers import SMTPHandler

        credentials = None
        secure = None
        if getattr(cls, 'MAIL_USERNAME', None) is not None:
            credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD)
            if getattr(cls, 'MAIL_USE_TLS', None):
                secure = ()
            mail_handler = SMTPHandler(
                mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT),
                fromaddr=cls.MAIL_DEFAULT_SENDER,
                toaddrs=[cls.AP_ADMIN],
                subject=cls.FLASKY_MAIL_SUBJECT_PREFIX + ' Application Error',
                credentials=credentials,
                secure=secure)
            formatter = logging.Formatter(
                '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
            mail_handler.setLevel(logging.DEBUG)
            mail_handler.setFormatter(formatter)
            app.logger.addHandler(mail_handler)
            file_handler = logging.StreamHandler()
            file_handler.setLevel(logging.WARNING)
            app.logger.addHandler(file_handler)
Esempio n. 15
0
def init(level=None, logger=getLogger(), handler=StreamHandler(), development=True):
    logging.basicConfig(level=level, datefmt='%m-%d %H:%M')
    logger = logging.getLogger()

    if (os.isatty(sys.stdout.fileno())
            and not sys.platform.startswith('win')):
        fmt = ANSIFormatter()
    else:
        fmt = TextFormatter()
    handler.setFormatter(fmt)
    logger.addHandler(handler)

    if level:
        logger.setLevel(level)

    if not development:
        logger.info("Setting up email handler for production-mode.")
        fmt = EmailFormatter()
        smtpHandler = SMTPHandler('127.0.0.1', '*****@*****.**',
            ['*****@*****.**'], 'ALERT docfu error!')
        smtpHandler.setFormatter(fmt)
        smtpHandler.setLevel(logging.ERROR)
        logger.addHandler(smtpHandler)

    return logger
Esempio n. 16
0
def configure_logging(app):
    """Configure file(info) and email(error) logging."""

    if app.debug or app.testing:
        # skip debug and test mode.
        return

    import logging
    from logging.handlers import RotatingFileHandler, SMTPHandler

    # Set info level on logger, which might be overwritten by handers.
    app.logger.setLevel(logging.INFO)

    debug_log = os.path.join(app.root_path, app.config['DEBUG_LOG'])
    file_handler = logging.handlers.RotatingFileHandler(debug_log, maxBytes=100000, backupCount=10)
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]')
    )
    app.logger.addHandler(file_handler)

    ADMINS = ['*****@*****.**']
    mail_handler = SMTPHandler(app.config['MAIL_SERVER'],
                               app.config['MAIL_USERNAME'],
                               ADMINS,
                               'O_ops... %s failed!' % PROJECT,
                               (app.config['MAIL_USERNAME'],
                                app.config['MAIL_PASSWORD']))
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]')
    )
    app.logger.addHandler(mail_handler)
Esempio n. 17
0
def init(app):
    """
    Initialize logging for the application, (only if its not in debug mode)
    """
    if not app.debug:
        from logging import Formatter
        from logging.handlers import SMTPHandler, TimedRotatingFileHandler
        
        # File handler
        file_formatter = Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
        file_handler = TimedRotatingFileHandler(app.config['LOG_FILE_NAME'], when='midnight', backupCount=31)
        file_handler.setFormatter(file_formatter)
        file_handler.setLevel(app.config['LOG_FILE_LEVEL'])
        app.logger.addHandler(file_handler)
        
        # Email handler
        mail_formatter = Formatter('''
Message type:       %(levelname)s
Location:           %(pathname)s:%(lineno)d
Module:             %(module)s
Function:           %(funcName)s
Time:               %(asctime)s

Message:

%(message)s
''')
        mail_handler = SMTPHandler(app.config['LOG_EMAIL_SERVER'], app.config['LOG_EMAIL_SENDER'],
                                   app.config['ADMIN_EMAILS'].split(','), '[%s] Error' % app.config['HOST_DOMAIN'])
        mail_handler.setFormatter(mail_formatter)
        mail_handler.setLevel(app.config['LOG_EMAIL_LEVEL'])
        app.logger.addHandler(mail_handler)
        
def exception_handler(app):
    """
    Register 0 or more exception handlers (mutates the app passed in).

    :param app: Flask application instance
    :return: None
    """
    # This will not execute when debug is set to True.
    mail_handler = SMTPHandler((app.config.get('MAIL_SERVER'),
                                app.config.get('MAIL_PORT')),
                               '*****@*****.**',
                               [app.config.get('MAIL_USERNAME')],
                               '[Exception handler] A 5xx was thrown',
                               (app.config.get('MAIL_USERNAME'),
                                app.config.get('MAIL_PASSWORD')),
                               secure=())

    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(logging.Formatter('''
    Time:         %(asctime)s
    Message type: %(levelname)s


    Message:

    %(message)s
    '''))
    app.logger.addHandler(mail_handler)

    return None
Esempio n. 19
0
def ErrorMail():
    if not app.debug:
        import logging
        from logging.handlers import SMTPHandler
        credentials=None
        if MAIL_USERNAME or MAIL_PASSWORD:
            credentials=(MAIL_USERNAME,MAIL_PASSWORD)
        mail_handler = SMTPHandler(MAIL_PORT,
                                   'no-reply@' + MAIL_SERVER,
                                   ADMINS, 'microblg failture',credentials)
        from logging import Formatter
        mail_handler.setFormatter(Formatter('''

Messagetype:        %(levelname)s
Location:           %(pathname)s:%(lineno)d
Module:             %(module)s
Function:           %(funcName)s
Time:               %(asctime)s

Message:

%(message)s
'''))
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
Esempio n. 20
0
def internal_server_error(error):
    errorstr = str(error)
    if errorstr.startswith('(8017, '):
        flash(
            'Could not connect to Teradata : Make sure your userid and Password (Roche) is correct',
            'danger')
        return render_template('login.html', error=error), 500
    else:
        #CODE FOR EMAILING ERROR TO ADMINS
        admins = ['*****@*****.**']
        monitor = '0.0.0.0'

        if not app.debug:
            import logging
            from logging.handlers import SMTPHandler
            from logging import Formatter

            mail_handler = SMTPHandler(
                monitor, '<myemail>', admins,
                'The R&U Application Failed - check why')
            mail_handler.setLevel(logging.ERROR)
            mail_handler.setFormatter(
                Formatter('''
            Message type:       %(levelname)s
            Location:           %(pathname)s:%(lineno)d
            Module:             %(module)s
            Function:           %(funcName)s
            Time:               %(asctime)s

            Message:
            %(message)s
            '''))
            app.logger.addHandler(mail_handler)
            return render_template('login.html', error=error), 500
Esempio n. 21
0
def register_logging(app=None):
    app.logger.setLevel(logging.INFO)

    formatter = logging.Formatter(
        '%(asctime)s - %(levelname)s - "%(pathname)s", line:%(lineno)s - %(message)s'
    )
    file_handler = RotatingFileHandler('logs/data.log',
                                       maxBytes=10 * 1024 * 1024,
                                       backupCount=10)
    file_handler.setFormatter(formatter)
    file_handler.setLevel(logging.INFO)

    class RequestFormatter(logging.Formatter):
        def format(self, record):
            record.url = request.url
            record.remote_addr = request.remote_addr
            return super(RequestFormatter, self).format(record)

    request_formatter = RequestFormatter(
        '[%(asctime)s] - "%(remote_addr)s : %(url)s" - %(levelname)s - "%(pathname)s", line:%(lineno)s - %(message)s'
    )

    mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'],
                               fromaddr=app.config['MAIL_USERNAME'],
                               toaddrs=app.config['ALBUMY_ADMIN_EMAIL'],
                               subject='CatChat程序错误',
                               credentials=(app.config['MAIL_USERNAME'],
                                            app.config['MAIL_PASSWORD']))
    mail_handler.setFormatter(request_formatter)
    mail_handler.setLevel(logging.ERROR)

    if not app.debug:
        app.logger.addHandler(file_handler)
        app.logger.addHandler(mail_handler)
def init_logging(app):
    """Initialize app error logging

    :type app: flask.Flask
    :param app: The application to configure.
    """
    if app.debug:
        return

    ADMINS = ['*****@*****.**']
    import logging
    from logging.handlers import SMTPHandler

    credentials = None
    secure = None
    if app.config.get("MAIL_USERNAME") is not None:
        credentials = (app.config["MAIL_USERNAME"], app.config.get("MAIL_PASSWORD"))
        if app.config.get("MAIL_USE_TLS") is not None or app.config.get("MAIL_USE_SSL") is not None:
            secure = tuple()

    mail_handler = SMTPHandler(app.config["MAIL_SERVER"],
                               app.config["ERROR_SENDER"],
                               app.config["ERROR_ADDRESS"],
                               app.config["ERROR_SUBJECT"],
                               credentials=credentials, secure=secure)

    mail_handler.setLevel(logging.ERROR)
    if app.config.get("ERROR_FORMAT") is not None:
        mail_handler.setFormatter(Formatter(app.config["ERROR_FORMAT"]))

    for log in (getLogger('sqlalchemy'), app.logger):
        log.addHandler(mail_handler)
Esempio n. 23
0
def _setup_error_mail_handler(app):
    class ContextualFilter(logging.Filter):
        def filter(self, log_record):
            log_record.url = request.path
            log_record.method = request.method
            log_record.ip = request.environ.get("REMOTE_ADDR")
            log_record.headers = request.headers
            return True

    mailhost = tuple(config.get('smtp.server', 'localhost').split(":"))
    credentials = None
    if config.get('smtp.user'):
        credentials = (config.get('smtp.user'), config.get('smtp.password'))
    secure = () if asbool(config.get('smtp.starttls')) else None
    mail_handler = SMTPHandler(mailhost=mailhost,
                               fromaddr=config.get('error_email_from'),
                               toaddrs=[config.get('email_to')],
                               subject='Application Error',
                               credentials=credentials,
                               secure=secure)

    mail_handler.setFormatter(
        logging.Formatter('''
Time:               %(asctime)s
URL:                %(url)s
Method:             %(method)s
IP:                 %(ip)s
Headers:            %(headers)s

'''))

    context_provider = ContextualFilter()
    app.logger.addFilter(context_provider)
    app.logger.addHandler(mail_handler)
Esempio n. 24
0
def register_loggers(app):
    if not (app.debug or app.config.get('LOGGING_DISABLE', False)):
        import logging
        from logging import Formatter
        from logging.handlers import SMTPHandler
        mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'],
                                   fromaddr=app.config['LOGGING_SENDER'],
                                   toaddrs=app.config['ADMINS'],
                                   subject='CorpScores Server Error',
                                   credentials=(app.config['MAIL_USERNAME'],
                                                app.config['MAIL_PASSWORD']))
        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(Formatter('''
            Message type:       %(levelname)s
            Location:           %(pathname)s:%(lineno)d
            Module:             %(module)s
            Function:           %(funcName)s
            Time:               %(asctime)s

            Message:

            %(message)s
        '''))
        app.logger.addHandler(mail_handler)
    return None
Esempio n. 25
0
def add_email_handler(app,
                      mail_server,
                      mail_port,
                      mail_from_host,
                      log_email_recipients,
                      log_email_topic,
                      level=logging.ERROR):
    """Adds email notifications about captured logs."""
    mail_handler = SMTPHandler((mail_server, mail_port),
                               "logs@" + mail_from_host, log_email_recipients,
                               log_email_topic)
    mail_handler.setLevel(level)
    mail_handler.setFormatter(
        logging.Formatter('''
    Message type: %(levelname)s
    Location: %(pathname)s:%(lineno)d
    Module: %(module)s
    Function: %(funcName)s
    Time: %(asctime)s

    Message:

    %(message)s
    '''))
    app.logger.addHandler(mail_handler)
Esempio n. 26
0
def configure_logging(app):
    """Configure file(info) and email(error) logging."""

    if app.debug or app.testing:
        # skip debug and test mode.
        return

    import logging
    from logging.handlers import SMTPHandler

    # Set info level on logger, which might be overwritten by handers.
    app.logger.setLevel(logging.INFO)

    debug_log = os.path.join(app.root_path, app.config['DEBUG_LOG'])
    file_handler = logging.handlers.RotatingFileHandler(debug_log, maxBytes=100000, backupCount=10)
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]')
    )
    app.logger.addHandler(file_handler)

    ADMINS = ['*****@*****.**']
    mail_handler = SMTPHandler(app.config['MAIL_SERVER'],
                               app.config['MAIL_USERNAME'],
                               ADMINS,
                               'Error: Satellite',
                               (app.config['MAIL_USERNAME'],
                                app.config['MAIL_PASSWORD']))
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]')
    )
    app.logger.addHandler(mail_handler)
Esempio n. 27
0
def register_error_logger(app):
    if not app.debug:
        import logging
        from logging.handlers import SMTPHandler
        mail_handler = SMTPHandler(
            ('smtp.gmail.com','587'),
            '[Sistema Impresion] ' + date.today().strftime("%d-%m-%Y"),
            ADMINS,
            'Error!',
            ('*****@*****.**', '*****'),
            tuple()
        )
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)    
    
        mail_handler.setFormatter(Formatter('''
                Message type:       %(levelname)s
                Location:           %(pathname)s:%(lineno)d
                Module:             %(module)s
                Function:           %(funcName)s
                Time:               %(asctime)s
                
                Message:
                
                %(message)s
            ''')
        )
Esempio n. 28
0
def configure_logging(app):
    """Set up logging or debugging"""
    if app.debug:
        from flask_debugtoolbar import DebugToolbarExtension
        toolbar = DebugToolbarExtension(app)
    else:
        import logging
        from logging.handlers import SMTPHandler
        from logging import Formatter
        credentials = None
        if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
            credentials = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
        mail_handler = SMTPHandler((app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
                                'no-reply@' + app.config['MAIL_SERVER'], 
                                app.config['ADMINS'], 'data news error!!', credentials)
        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(Formatter('''
        Message type:       %(levelname)s
        Location:           %(pathname)s:%(lineno)d
        Module:             %(module)s
        Function:           %(funcName)s
        Time:               %(asctime)s

        Message:

        %(message)s
        '''))
        app.logger.addHandler(mail_handler)
Esempio n. 29
0
def create_app(name, config_filename):
    app = Flask(name,
                template_folder='app/templates',
                static_folder='app/static')
    app.config.from_pyfile(config_filename)

    from app.models import db
    db.init_app(app)
    db.app = app
    from app.sms import mail
    mail.init_app(app)
    mail.app = app

    from app.views import main
    app.register_blueprint(main)

    #TODO: Secure admin view
    admin = Admin()
    admin.init_app(app)
    admin.app = app
    admin.add_view(ModelView(User, db.session))

    if not (app.debug or app.config.get('LOGGING_DISABLE', False)):
        import logging
        from logging import Formatter
        from logging.handlers import SMTPHandler, RotatingFileHandler
        mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'],
                                   fromaddr=app.config['LOGGING_SENDER'],
                                   toaddrs=app.config['ADMINS'],
                                   subject='dci-notify Server Error',
                                   credentials=(app.config['MAIL_USERNAME'],
                                                app.config['MAIL_PASSWORD']))

        file_handler = RotatingFileHandler(filename=os.path.join(
            basedir, 'app.log'),
                                           maxBytes=1048756,
                                           backupCount=5)

        mail_handler.setLevel(logging.ERROR)
        file_handler.setLevel(logging.WARNING)
        mail_handler.setFormatter(
            Formatter('''
            Message type:       %(levelname)s
            Location:           %(pathname)s:%(lineno)d
            Module:             %(module)s
            Function:           %(funcName)s
            Time:               %(asctime)s

            Message:

            %(message)s
        '''))

        file_handler.setFormatter(
            Formatter('%(asctime)s %(levelname)s: %(message)s '
                      '[in %(pathname)s:%(lineno)d]'))
        app.logger.addHandler(mail_handler)
        app.logger.addHandler(file_handler)

    return app
Esempio n. 30
0
    def _add_logger(self, app):
        """ Creates SMTPHandler for logging errors to the specified admins list
        """
        kwargs = dict()
        username = app.config.get('MAIL_USERNAME')
        password = app.config.get('MAIL_PASSWORD')

        if username and password:
            kwargs['credentials'] = (username, password)

        mail_handler = SMTPHandler(app.config['MAIL_SERVER'],
                                   app.config['DEFAULT_MAIL_SENDER'],
                                   app.config['ADMINS'],
                                   '[ERROR] Findevent got error',
                                   **kwargs)

        mail_handler.setFormatter(logging.Formatter('''
            Message type:       %(levelname)s
            Location:           %(pathname)s:%(lineno)d
            Module:             %(module)s
            Function:           %(funcName)s
            Time:               %(asctime)s

            Message:

            %(message)s
        '''))

        mail_handler.setLevel(logging.DEBUG)

        if not app.debug:
            app.logger.addHandler(mail_handler)
Esempio n. 31
0
File: app.py Progetto: 8dspaces/wiwi
def configure_logging(app):
    """Configure file(info) and email(error) logging."""

    if app.debug or app.testing:
        # Skip debug and test mode.
        # You can check stdout logging.
        return

    import logging
    from logging.handlers import SMTPHandler

    # Set info level on logger, which might be overwritten by handers.
    # Suppress DEBUG messages.
    app.logger.setLevel(logging.INFO)

    info_log = os.path.join(app.root_path, "..", "logs", "app-info.log")
    info_file_handler = logging.handlers.RotatingFileHandler(info_log,
                                                             maxBytes=1048576,
                                                             backupCount=20)
    info_file_handler.setLevel(logging.INFO)
    info_file_handler.setFormatter(
        logging.Formatter('%(asctime)s %(levelname)s: %(message)s '
                          '[in %(pathname)s:%(lineno)d]'))
    app.logger.addHandler(info_file_handler)

    ADMINS = ['*****@*****.**']
    mail_handler = SMTPHandler(
        app.config['MAIL_SERVER'], app.config['MAIL_USERNAME'], ADMINS,
        'O_ops... %s failed!' % app.config['PROJECT'],
        (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']))
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(
        logging.Formatter('%(asctime)s %(levelname)s: %(message)s '
                          '[in %(pathname)s:%(lineno)d]'))
    app.logger.addHandler(mail_handler)
Esempio n. 32
0
    def init_app(cls, app):
        Development.init_app(app)

        import logging
        from logging.handlers import SMTPHandler, SysLogHandler
        credentials, secure = None, None
        if getattr(cls, 'MAIL_USERNAME', None) is not None:
            credentials = (cls.MAIL_USERNAME, cls.MAIL_PASSWORD)
            if getattr(cls, 'MAIL_USE_TLS', None):
                secure = ()

            mail_handler = SMTPHandler(
                mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT),
                fromaddr=cls.MAIL_SENDER,
                toaddrs=[cls.XYCH_ADMIN],
                subject=cls.MAIL_SUBJECT_PREFIX + ' App Error',
                credentials=credentials,
                secure=secure
            )
            mail_handler.setLevel(logging.ERROR)
            mail_handler.setFormatter(logging.Formatter("""
                Message type: %(levelname)s
                Location:     %(pathname)s:%(lineno)d
                Module:       %(module)s
                Function:     %(funcName)s
                Time:         %(asctime)s
                Message:      %(message)s"""))
            app.logger.addHandler(mail_handler)

            sys_log = SysLogHandler(address='/dev/log')
            sys_log.setLevel(logging.WARNING)
            app.logger.addHandler(sys_log)
Esempio n. 33
0
def configure_logging(app):
    """Configure file(info) and email(error) logging."""

    import logging
    from logging.handlers import SMTPHandler

    # Set info level on logger, which might be overwritten by handers.
    # Suppress DEBUG messages.
    app.logger.setLevel(logging.INFO)

    info_log = os.path.join(app.config['LOG_FOLDER'], 'info.log')
    info_file_handler = logging.handlers.RotatingFileHandler(
        info_log, maxBytes=100000, backupCount=10)
    info_file_handler.setLevel(logging.INFO)
    info_file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]')
    )
    app.logger.addHandler(info_file_handler)
    if not app.config['DEBUG']:
        mail_handler = SMTPHandler(app.config['MAIL_SERVER'],
                                   app.config['MAIL_USERNAME'],
                                   app.config['ADMINS'],
                                   'O_ops... %s failed!' % app.config[
                                       'PROJECT'],
                                   (app.config['MAIL_USERNAME'],
                                    app.config['MAIL_PASSWORD']))
        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]')
        )
        app.logger.addHandler(mail_handler)
Esempio n. 34
0
def configure_logging(app):
    '''Setup file(info) and email(error) logging'''
    # Return if in debug or testing mode
    if app.debug or app.testing:
        return

    import logging
    from logging.handlers import RotatingFileHandler, SMTPHandler

    # Set logging level to info
    app.logger.setLevel(logging.INFO)

    # Rotating File loggiing for (info) level
    debug_log = os.path.join(app.root_path, app.config['DEBUG_LOG'])
    file_handler = RotatingFileHandler(debug_log, maxBytes=100000, backupCount=10)
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(processName)s\t | %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]')
    )
    app.logger.addHandler(file_handler)

    # Mail logging haldler for (error) level
    mail_handler = SMTPHandler(app.config['MAIL_SERVER'],
                               app.config['MAIL_USERNAME'],
                               app.config['SITE_ADMINS'],
                               'O_ops... %s failed!' % app.config['SITE_NAME'],
                               (app.config['MAIL_USERNAME'],
                                app.config['MAIL_PASSWORD']))
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(processName)s\t | %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]')
    )
    app.logger.addHandler(mail_handler)
Esempio n. 35
0
def configure_logging(app):
    """Configure file(info) and email(error) logging."""

    import logging
    from logging.handlers import SMTPHandler

    # Set info level on logger, which might be overwritten by handers.
    # Suppress DEBUG messages.
    app.logger.setLevel(logging.INFO)

    info_log = os.path.join(app.config['LOG_FOLDER'], 'info.log')
    info_file_handler = logging.handlers.RotatingFileHandler(info_log,
                                                             maxBytes=100000,
                                                             backupCount=10)
    info_file_handler.setLevel(logging.INFO)
    info_file_handler.setFormatter(
        logging.Formatter('%(asctime)s %(levelname)s: %(message)s '
                          '[in %(pathname)s:%(lineno)d]'))
    app.logger.addHandler(info_file_handler)
    if not app.config['DEBUG']:
        mail_handler = SMTPHandler(
            app.config['MAIL_SERVER'], app.config['MAIL_USERNAME'],
            app.config['ADMINS'],
            'O_ops... %s failed!' % app.config['PROJECT'],
            (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']))
        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(
            logging.Formatter('%(asctime)s %(levelname)s: %(message)s '
                              '[in %(pathname)s:%(lineno)d]'))
        app.logger.addHandler(mail_handler)
Esempio n. 36
0
def configure_logging(app):
    hostname = os.uname()[1]
    mail_handler = SMTPHandler(app.config['MAIL_SERVER'],
                               app.config['DEFAULT_MAIL_SENDER'],
                               app.config['ADMINS'],
                               '[%s] CMDB error' % hostname, (
                                   app.config['MAIL_USERNAME'],
                                   app.config['MAIL_PASSWORD'],
                               ))
    mail_formater = logging.Formatter(
        "%(asctime)s %(levelname)s %(pathname)s %(lineno)d\n%(message)s")
    mail_handler.setFormatter(mail_formater)
    mail_handler.setLevel(logging.ERROR)
    if not app.debug:
        app.logger.addHandler(mail_handler)
    formatter = logging.Formatter(
        "%(asctime)s %(levelname)s %(pathname)s %(lineno)d - %(message)s")
    log_file = app.config['LOG_PATH']
    file_handler = TimedRotatingFileHandler(log_file,
                                            when='d',
                                            interval=1,
                                            backupCount=7)
    file_handler.setLevel(getattr(logging, app.config['LOG_LEVEL']))
    file_handler.setFormatter(formatter)
    app.logger.addHandler(file_handler)
    app.logger.setLevel(getattr(logging, app.config['LOG_LEVEL']))
Esempio n. 37
0
def init(app):

    if app.config.get('ERROR_EMAIL'):

        if app.debug:
            logging.getLogger().setLevel(logging.DEBUG)
        else:
            log_format = logging.Formatter('''
    ---
    Message type:       %(levelname)s
    Location:           %(pathname)s:%(lineno)d
    Module:             %(module)s
    Function:           %(funcName)s
    Time:               %(asctime)s

%(message)s

    ''')

            # Send errors via email
            mail_handler = SMTPHandler('127.0.0.1',
                                       app.config.get('DEFAULT_MAIL_SENDER'),
                                       app.config.get('ERROR_EMAIL'), 'Error')
            mail_handler.setLevel(logging.ERROR)
            mail_handler.setFormatter(log_format)

            # Also continue to log errors to stderr
            stream_handler = logging.StreamHandler()
            stream_handler.setFormatter(log_format)

            app.logger.addHandler(stream_handler)
            app.logger.addHandler(mail_handler)
Esempio n. 38
0
    def add_logging_handlers(self):
        if self.debug: return

        import logging
        from logging import Formatter, Filter
        from logging.handlers import RotatingFileHandler, SMTPHandler

        # Set general log level
        self.logger.setLevel(logging.INFO)

        # Inject additional log record fields
        class ContextFilter(Filter):
            def __init__(self, app):
                self.app = app

            def filter(self, record):
                record.app_name = self.app.name
                record.url = request.url
                record.ip = request.remote_addr
                if g.current_user:
                    user = g.current_user
                    record.user = '******' % (user.name, user.email_address)
                else:
                    record.user = '******'

                return True

        self.logger.addFilter(ContextFilter(self))

        # Add SMTP handler
        mail_handler = SMTPHandler(
            'localhost', '*****@*****.**',
            self.config.get('ADMINS', []), 'SkyLines Error Report')
        mail_handler.setLevel(logging.ERROR)

        mail_formatter = Formatter('''
App:                %(app_name)s
Time:               %(asctime)s
URL:                %(url)s
IP:                 %(ip)s
User:               %(user)s

Message:

%(message)s
''')
        mail_handler.setFormatter(mail_formatter)
        self.logger.addHandler(mail_handler)

        # Add log file handler (if configured)
        path = self.config.get('LOGFILE')
        if path:
            file_handler = RotatingFileHandler(path, 'a', 10000, 4)
            file_handler.setLevel(logging.INFO)

            file_formatter = Formatter(
                '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
            file_handler.setFormatter(file_formatter)

            self.logger.addHandler(file_handler)
Esempio n. 39
0
def register_logging(app):
    class RequestFormatter(logging.Formatter):
        def format(self, record):
            record.url = request.url
            record.remote_addr = request.remote_addr
            return super(RequestFormatter, self).format(record)

    request_formatter = RequestFormatter(
        '[%(asctime)s] %(remote_addr)s requested % (url)s\n'
        '%(levelname)s in %(module)s: %(message)s')
    mail_handler = SMTPHandler(mailhost=os.getenv('MAIL_SERVER'),
                               fromaddr=os.getenv('MAIL_USERNAME'),
                               toaddrs=os.getenv('BLUELOG_ADMIN_EMAIL'),
                               subject='Application Error',
                               credentials=(os.getenv('MAIL_USERNAME'),
                                            os.getenv('MAIL_PASSWORD')))
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(request_formatter)

    app.logger.setLevel(logging.INFO)

    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_handler = RotatingFileHandler('logs/bluelog.log',
                                       maxBytes=10 * 1024 * 1024,
                                       backupCount=10)
    file_handler.setFormatter(formatter)
    file_handler.setLevel(logging.INFO)

    # 在调试状态下不会添加处理器
    if not app.debug:
        app.logger.addHandler(file_handler)
        app.logger.addHandler(mail_handler)
Esempio n. 40
0
def setUpLogger():
    # Who should receive the emails if an error or an exception occures?
    mail_env = os.environ.get("MAILRECEIVER", "")
    if mail_env:
        mail = mail_env.split()
    else:
        mail = []

    logger = logging.getLogger("UserLab")
    # In trace will be sensitive information like tokens
    logging.addLevelName(5, "TRACE")

    def trace_func(self, message, *args, **kws):
        if self.isEnabledFor(5):
            # Yes, logger takes its '*args' as 'args'.
            self._log(5, message, args, **kws)

    logging.Logger.trace = trace_func
    mail_handler = SMTPHandler(
        mailhost=os.environ.get("MAILHOST"),
        fromaddr=os.environ.get("MAILFROM"),
        toaddrs=mail,
        subject=os.environ.get("MAILSUBJECT"),
    )
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(
        logging.Formatter(
            "[%(asctime)s] %(levelname)s in %(filename)s ( Line=%(lineno)d ): %(message)s"
        ))
    logging.config.fileConfig(os.environ.get("LOGGINGCONF"))
    logger.addHandler(mail_handler)
Esempio n. 41
0
def configure_logging():
    global detection_logger

    logging_config = config["logging"]
    level = logging.getLevelName(logging_config["level"])
    formatter = logging.Formatter("%(asctime)s %(name)s: %(message)s")

    detection_logger = logging.getLogger(logging_config["name"])
    detection_logger.setLevel(level)

    # make sure we have something to log against
    detection_logger.addHandler(logging.NullHandler())

    syslog_config = config["syslog"]
    smtp_config = config["smtp"]

    if syslog_config["enabled"]:  # use syslog
        syslog_handler = SysLogHandler((syslog_config["server"], int(syslog_config["port"])))
        syslog_handler.setFormatter(formatter)
        detection_logger.addHandler(syslog_handler)

    if smtp_config["enabled"]:  # use smtp
        creds = None

        if smtp_config["user"]:  # check if we need credentials
            creds = (smtp_config["user"], smtp_config["password"])

        smtp_handler = SMTPHandler((smtp_config["server"], smtp_config["port"]), fromaddr=smtp_config["from"], toaddrs=smtp_config["to"], subject=smtp_config["subject"], credentials=creds)
        smtp_handler.setFormatter(formatter)
        detection_logger.addHandler(smtp_handler)
Esempio n. 42
0
def create_app(name, config_filename):
    app = Flask(name,
                template_folder='app/templates',
                static_folder='app/static')
    app.config.from_pyfile(config_filename)

    from app.models import db
    db.init_app(app)
    db.app = app
    from app.sms import mail
    mail.init_app(app)
    mail.app = app

    from app.views import main
    app.register_blueprint(main)

    #TODO: Secure admin view
    admin = Admin()
    admin.init_app(app)
    admin.app = app
    admin.add_view(ModelView(User, db.session))

    if not (app.debug or app.config.get('LOGGING_DISABLE', False)):
        import logging
        from logging import Formatter
        from logging.handlers import SMTPHandler, RotatingFileHandler
        mail_handler = SMTPHandler(mailhost=app.config['MAIL_SERVER'],
                                   fromaddr=app.config['LOGGING_SENDER'],
                                   toaddrs=app.config['ADMINS'],
                                   subject='dci-notify Server Error',
                                   credentials=(app.config['MAIL_USERNAME'],
                                                app.config['MAIL_PASSWORD']))

        file_handler = RotatingFileHandler(filename=os.path.join(basedir,
                                                                 'app.log'),
                                           maxBytes=1048756,
                                           backupCount=5)

        mail_handler.setLevel(logging.ERROR)
        file_handler.setLevel(logging.WARNING)
        mail_handler.setFormatter(Formatter('''
            Message type:       %(levelname)s
            Location:           %(pathname)s:%(lineno)d
            Module:             %(module)s
            Function:           %(funcName)s
            Time:               %(asctime)s

            Message:

            %(message)s
        '''))

        file_handler.setFormatter(Formatter(
            '%(asctime)s %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]'
        ))
        app.logger.addHandler(mail_handler)
        app.logger.addHandler(file_handler)

    return app
Esempio n. 43
0
def init_mail_handler(app_logger,flask_app=None):
    '''
    邮件发送日志,发送的级别为 ERROR
    :param app_logger: 
    :return: 
    '''
    SMTP_HOST = 'smtp.163.com'
    SMTP_PORT = 25

    FROM = '*****@*****.**'
    PASS = '******'
    TO = ['*****@*****.**']

    if flask_app is None or not flask_app.debug:
        mail_handler = SMTPHandler(
            (SMTP_HOST, SMTP_PORT)
            , FROM
            , TO
            , 'YourApplication Failed'
            , (FROM, PASS))
        # 设置发送邮件的日志级别
        mail_handler.setLevel(logging.ERROR)
        # 设置邮件日志格式
        mail_handler.setFormatter(Formatter('''
        Message type:       %(levelname)s
        Location:           %(pathname)s:%(lineno)d
        Module:             %(module)s
        Function:           %(funcName)s
        Time:               %(asctime)s

        Message:

        %(message)s
        '''))
        app_logger.addHandler(mail_handler)
Esempio n. 44
0
def exception_handler(app):
    """
    Register 0 or more exception handlers (mutates the app passed in).

    :param app: Flask application instance
    :return: None
    """
    # This will not execute when debug is set to True.
    mail_handler = SMTPHandler(
        (app.config.get('MAIL_SERVER'), app.config.get('MAIL_PORT')),
        '*****@*****.**', [app.config.get('MAIL_USERNAME')],
        '[Exception handler] A 5xx was thrown',
        (app.config.get('MAIL_USERNAME'), app.config.get('MAIL_PASSWORD')),
        secure=())

    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(
        logging.Formatter('''
    Time:         %(asctime)s
    Message type: %(levelname)s


    Message:

    %(message)s
    '''))
    app.logger.addHandler(mail_handler)

    return None
Esempio n. 45
0
    def add_logging_handlers(self):
        if self.debug: return

        import logging
        from logging import Formatter, Filter
        from logging.handlers import RotatingFileHandler, SMTPHandler

        # Set general log level
        self.logger.setLevel(logging.INFO)

        # Inject additional log record fields
        class ContextFilter(Filter):
            def __init__(self, app):
                self.app = app

            def filter(self, record):
                record.app_name = self.app.name
                record.url = request.url
                record.ip = request.remote_addr
                if g.current_user:
                    user = g.current_user
                    record.user = '******' % (user.name, user.email_address)
                else:
                    record.user = '******'

                return True

        self.logger.addFilter(ContextFilter(self))

        # Add SMTP handler
        mail_handler = SMTPHandler(
            'localhost', '*****@*****.**',
            self.config.get('ADMINS', []), 'SkyLines Error Report')
        mail_handler.setLevel(logging.ERROR)

        mail_formatter = Formatter('''
App:                %(app_name)s
Time:               %(asctime)s
URL:                %(url)s
IP:                 %(ip)s
User:               %(user)s

Message:

%(message)s
''')
        mail_handler.setFormatter(mail_formatter)
        self.logger.addHandler(mail_handler)

        # Add log file handler (if configured)
        path = self.config.get('LOGFILE')
        if path:
            file_handler = RotatingFileHandler(path, 'a', 10000, 4)
            file_handler.setLevel(logging.INFO)

            file_formatter = Formatter(
                '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')
            file_handler.setFormatter(file_formatter)

            self.logger.addHandler(file_handler)
Esempio n. 46
0
def exception_handler(app):
    """
    Register 0 or more exception handlers (mutates the app passed in).

    :param app: Flask application instance
    :return: None
    """
    mail_handler = SMTPHandler(
        (app.config.get('MAIL_SERVER'), app.config.get('MAIL_PORT')),
        app.config.get('MAIL_USERNAME'), [app.config.get('MAIL_USERNAME')],
        '[Exception handler] A 5xx was thrown',
        (app.config.get('MAIL_USERNAME'), app.config.get('MAIL_PASSWORD')),
        secure=())

    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(
        logging.Formatter("""
    Time:               %(asctime)s
    Message type:       %(levelname)s


    Message:

    %(message)s
    """))
    app.logger.addHandler(mail_handler)

    return None
Esempio n. 47
0
def init_logging(app):
    """Initialize app error logging

    :type app: flask.Flask
    :param app: The application to configure.
    """
    if app.debug:
        return

    import logging
    from logging.handlers import SMTPHandler
    from logging import Formatter, getLogger

    credentials = None
    secure = None
    if app.config.get("MAIL_USERNAME") is not None:
        credentials = (app.config["MAIL_USERNAME"], app.config.get("MAIL_PASSWORD"))
        if app.config.get("MAIL_USE_TLS") is not None or app.config.get("MAIL_USE_SSL") is not None:
            secure = tuple()

    mail_handler = SMTPHandler(app.config["MAIL_SERVER"],
                               app.config["ERROR_SENDER"],
                               app.config["ERROR_ADDRESS"],
                               app.config["ERROR_SUBJECT"],
                               credentials=credentials, secure=secure)

    mail_handler.setLevel(logging.ERROR)
    if app.config.get("ERROR_FORMAT") is not None:
        mail_handler.setFormatter(Formatter(app.config["ERROR_FORMAT"]))

    for log in (getLogger('sqlalchemy'), app.logger):
        log.addHandler(mail_handler)
Esempio n. 48
0
def exception_handler(app):
    """
    Register 0 or more exception handlers (mutates the app passed in).

    :param app: Flask application instance
    :return: None
    """
    # <rms/>
    secure = None

    mail_handler = SMTPHandler(mailhost=(app.config.get('MAIL_SERVER'), app.config.get('MAIL_PORT')),
                               fromaddr=app.config.get('MAIL_DEFAULT_SENDER'),
                               toaddrs=[app.config.get('MAIL_DEFAULT_SENDER')],
                               subject='5xx err',
                               credentials=(app.config.get('MAIL_USERNAME'), app.config.get('MAIL_PASSWORD')),
                               secure=secure)

    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(logging.Formatter("""
    Time:               %(asctime)s
    Message type:       %(levelname)s


    Message:

    %(message)s
    """))
    app.logger.addHandler(mail_handler)

    return None
Esempio n. 49
0
def _configure_log(debug):
    """Re-configure the default logger returned by ``desiutil.log``.

    Parameters
    ----------
    debug : :class:`bool`
        If ``True`` set the log level to ``DEBUG``.
    """
    global log
    log = get_logger(timestamp=True)
    if debug:
        log.setLevel(logging.DEBUG)
    email_from = 'NOIRLab Mirror Account <{0}@{1}>'.format(os.environ['USER'], getfqdn())
    email_to = ['*****@*****.**']
    handler2 = SMTPHandler('localhost', email_from, email_to,
                           'Error reported by desi_tucson_transfer!')
    fmt = """Greetings,

At %(asctime)s, desi_tucson_transfer reported this serious error:

%(message)s

Kia ora koutou,
The DESI NOIRLab Mirror Account
"""
    formatter2 = logging.Formatter(fmt, datefmt='%Y-%m-%d %H:%M:%S %Z')
    handler2.setFormatter(formatter2)
    handler2.setLevel(logging.CRITICAL)
    log.parent.addHandler(handler2)
Esempio n. 50
0
File: app.py Progetto: 0xsKu/flaskbb
def configure_logging(app):
    """Configures logging."""

    logs_folder = os.path.join(app.root_path, os.pardir, "logs")
    from logging.handlers import SMTPHandler
    formatter = logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s '
        '[in %(pathname)s:%(lineno)d]')

    info_log = os.path.join(logs_folder, app.config['INFO_LOG'])

    info_file_handler = logging.handlers.RotatingFileHandler(
        info_log,
        maxBytes=100000,
        backupCount=10
    )

    info_file_handler.setLevel(logging.INFO)
    info_file_handler.setFormatter(formatter)
    app.logger.addHandler(info_file_handler)

    error_log = os.path.join(logs_folder, app.config['ERROR_LOG'])

    error_file_handler = logging.handlers.RotatingFileHandler(
        error_log,
        maxBytes=100000,
        backupCount=10
    )

    error_file_handler.setLevel(logging.ERROR)
    error_file_handler.setFormatter(formatter)
    app.logger.addHandler(error_file_handler)

    if app.config["SEND_LOGS"]:
        mail_handler = \
            SMTPHandler(
                app.config['MAIL_SERVER'],
                app.config['MAIL_DEFAULT_SENDER'],
                app.config['ADMINS'],
                'application error, no admins specified',
                (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
            )

        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(formatter)
        app.logger.addHandler(mail_handler)

    if app.config["SQLALCHEMY_ECHO"]:
        # Ref: http://stackoverflow.com/a/8428546
        @event.listens_for(Engine, "before_cursor_execute")
        def before_cursor_execute(conn, cursor, statement,
                                  parameters, context, executemany):
            conn.info.setdefault('query_start_time', []).append(time.time())

        @event.listens_for(Engine, "after_cursor_execute")
        def after_cursor_execute(conn, cursor, statement,
                                 parameters, context, executemany):
            total = time.time() - conn.info['query_start_time'].pop(-1)
            app.logger.debug("Total Time: %f", total)
Esempio n. 51
0
def create_smtp_log_handler(mail_host, mail_port, from_address, to_addresses, email_subject,
                            username, password, use_tls):
    secure = () if use_tls else None
    handler = SMTPHandler((mail_host, mail_port), from_address, to_addresses, email_subject,
                          credentials=(username, password), secure=secure)
    handler.setLevel(logging.WARNING)
    handler.setFormatter(create_log_formatter())
    return handler
Esempio n. 52
0
def setup_email_logging(app):
    mail_handler = SMTPHandler(config.HOST,
                               config.HOSTMAIL,
                               config.ADMINS,
                               'Production Monitoring Platform')
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(Formatter(__EMAIL_LOG_FORMAT))
    app.logger.addHandler(mail_handler)
Esempio n. 53
0
def get_mail_handler():
    mail_handler = SMTPHandler('127.0.0.1',
                               app.config["SECURITY_EMAIL_SENDER"],
                               app.config["ADMIN_EMAILS"],
                               'Code Review application failed')
    mail_handler.setLevel(logging.WARNING)
    mail_handler.setFormatter(logging.Formatter(EMAIL_LOG_TEMPLATE))
    return mail_handler
Esempio n. 54
0
def create_app(environment):
    app = Flask(__name__)
    app.config.from_pyfile("config/{}.py".format(environment))

    database.init(app.config["DB_PATH"])

    if app.config["EMAIL_ERRORS"]:
        from logging.handlers import SMTPHandler
        mail_handler = SMTPHandler('127.0.0.1', app.config["EMAIL_FROM"], app.config["SITE_ADMIN"], 'Exception in TFT-{}'.format(environment))
        mail_handler.setLevel(logging.ERROR)
        mail_handler.setFormatter(log_formatter)
        app.logger.addHandler(mail_handler)

    from modules.account.blueprint import account
    from modules.staticpages.blueprint import staticpages
    from modules.donations.blueprint import donations
    from modules.volunteer.blueprint import volunteer
    from modules.rcon.blueprint import rcon
    from modules.security.blueprint import security

    app.register_blueprint(account)
    app.register_blueprint(security)
    app.register_blueprint(volunteer)
    app.register_blueprint(donations)
    app.register_blueprint(rcon)
    app.register_blueprint(staticpages) # staticpages must be registered last

    @app.route("/favicon.ico")
    def favicon(): return redirect('/static/favicon.ico')

    @app.route("/robots.txt")
    def robots_txt(): return redirect('/static/robots.txt')

    @app.route("/teensforteens.info.html")
    def verify_cert(): return "MTRHYzBuSUg3TU1DSnNiZzJqZHo0WXllWnc0NVB3OWE4MmpUd0ZGa0dSdz0"

    @app.route("/googlefe31abc06e03d8f7.html")
    def google(): return "google-site-verification: googlefe31abc06e03d8f7.html"

    @app.context_processor
    def inject_config():
        if app.config["DISPLAY_DEBUG_INFO"]:
            version = subprocess.check_output(["git", "describe", "--always"]).decode().strip()
        else:
            version = ""
        return dict(global_config=app.config, version=version)

    @app.errorhandler(500)
    def internal_error(exc):
        trace = traceback.format_exc()
        try:
            send_error_email(environment, trace)
        except:
            trace = traceback.format_exc()
        return make_response(render_template("whoops.html", trace=trace), 500)

    return app
Esempio n. 55
0
def setup_logging(app):
    if not app.debug:
        import logging

        #Setup email handling
        from logging.handlers import SMTPHandler
        mail_handler = SMTPHandler((
            app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
            app.config['MAIL_USERNAME'],
            app.config['ADMINS'],
            subject="alarmaway failure",
            credentials=(app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD']),
            secure=(),
        )

        mail_formatter = logging.Formatter('''
            Message type:       %(levelname)s
            Location:           %(pathname)s:%(lineno)d
            Module:             %(module)s
            Function:           %(funcName)s
            Time:               %(asctime)s

            Message:

            %(message)s
            ''')
        mail_handler.setFormatter(mail_formatter)
        mail_handler.setLevel(logging.ERROR)

        #Setup File logging
        try:
            log_file = app.config['LOG_FILE']
        except KeyError:
            log_file = 'alarmaway.log'

        file_handler = logging.FileHandler(log_file)
        file_formatter = logging.Formatter(
            '%(asctime)s %(levelname)s -- %(module)s.%(funcName)s: '
            '%(message)s '
            '[in %(pathname)s:%(lineno)d]'
        )
        file_handler.setFormatter(file_formatter)
        file_handler.setLevel(logging.DEBUG)

        # Ensure a root logger exists
        root_logger = logging.getLogger('alarmaway')

        # Add handlers to all known loggers
        loggers = [
            app.logger,
            root_logger,
            logging.getLogger('sqlalchemy'),
        ]
        for logger in loggers:
            logger.addHandler(mail_handler)
            logger.addHandler(file_handler)
Esempio n. 56
0
class EmailLogger(object):
    """An email logging class"""

    def __init__(self, mailhost, fromaddr, toaddrs, subject):
        self.logger = logging.getLogger('telecaster')
        self.hdlr = SMTPHandler(mailhost, fromaddr, toaddrs, subject)
        self.formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        self.hdlr.setFormatter(self.formatter)
        self.logger.addHandler(self.hdlr)
        self.logger.setLevel(logging.INFO)
Esempio n. 57
0
def setlogging():
#----------------------------------------------------------------------

    # this is needed for any INFO or DEBUG logging
    app.logger.setLevel(logging.DEBUG)

    # patch werkzeug logging -- not sure why this is being bypassed in werkzeug._internal._log
    werkzeug_logger = logging.getLogger('werkzeug')
    werkzeug_logger.setLevel(logging.INFO)

    # TODO: move this to new module logging, bring in from dispatcher
    # set up logging
    ADMINS = ['*****@*****.**']
    if not app.debug:
        mail_handler = SMTPHandler('localhost',
                                   '*****@*****.**',
                                   ADMINS, '[scoretility] exception encountered')
        if 'LOGGING_LEVEL_MAIL' in app.config:
            mailloglevel = app.config['LOGGING_LEVEL_MAIL']
        else:
            mailloglevel = logging.ERROR
        mail_handler.setLevel(mailloglevel)
        mail_handler.setFormatter(Formatter('''
        Message type:       %(levelname)s
        Location:           %(pathname)s:%(lineno)d
        Module:             %(module)s
        Function:           %(funcName)s
        Time:               %(asctime)s
        
        Message:
        
        %(message)s
        '''))
        app.logger.addHandler(mail_handler)
        app.config['LOGGING_MAIL_HANDLER'] = mail_handler
        
        logpath = None
        if 'LOGGING_PATH' in app.config:
            logpath = app.config['LOGGING_PATH']
            
        if logpath:
            # file rotates every Monday
            file_handler = TimedRotatingFileHandler(logpath,when='W0',delay=True)
            if 'LOGGING_LEVEL_FILE' in app.config:
                fileloglevel = app.config['LOGGING_LEVEL_FILE']
            else:
                fileloglevel = logging.WARNING
            file_handler.setLevel(fileloglevel)
            app.logger.addHandler(file_handler)
            app.config['LOGGING_FILE_HANDLER'] = file_handler
            
            file_handler.setFormatter(Formatter(
                '%(asctime)s %(levelname)s: %(message)s '
                '[in %(pathname)s:%(lineno)d]'
            ))
Esempio n. 58
0
def main():
    # check args
    options, args = check_args()
    
    ## logging
    logger = logging.getLogger(APP_NAME)
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
    # define handler
    hdlr = RotatingFileHandler(os.path.join(LOG_DIR, ('info.log')))
    mail_hdlr = SMTPHandler(mailhost=MAIL_HOST, fromaddr=MAIL_SENDER,
                            toaddrs=ADMINS,
                            subject='%s App Error' % APP_NAME.capitalize(),
                            credentials=(MAIL_USER, MAIL_PASSWORD),
                            secure=())
    # set formatter
    hdlr.setFormatter(formatter)
    mail_hdlr.setFormatter(formatter)
    # set level
    hdlr.setLevel(logging.INFO)
    mail_hdlr.setLevel(logging.ERROR)
    # add handler
    logger.addHandler(hdlr)
    logger.addHandler(mail_hdlr)

    if options.target == 'tommorow':
        subject = u'明日の予定'
        task_filter = 'status:incomplete AND due:"tommorow"'
    elif options.target == 'two_weeks':
        subject = u'直近の予定'
        task_filter = 'status:incomplete AND dueWithin:"2 week of today"'
    elif options.target == 'six_month':
        subject = u'今後の予定'
        task_filter = 'status:incomplete AND NOT list:"出勤時刻" AND dueWithin:"6 months of today"'

    body = ''
    for task in get_task(task_filter):
        body += '* %s %s\n' %(task['due'], task['name'])
        
    if not body:
        return
    
    if options.important:
        to_addr = MAIL_MOBILE_RECIPIENTS + MAIL_RECIPIENTS
        subject += u'(重要)'
        task_filter += ' AND (priority:1 OR list:"出勤時刻")"'
    else:
        to_addr = MAIL_RECIPIENTS

    to_addr = MAIL_MOBILE_RECIPIENTS + MAIL_RECIPIENTS
    try:
        send_mail(subject=subject, body=body, to_addr=to_addr)
        logger.info('send %s task' % options.target)
    except Exception as e:
        logger.exception(str(e))