예제 #1
0
def init_log_config(use_mail=False):
    '''
    Do basic configuration for the logging system. support ConsoleHandler, RotatingFileHandler and SMTPHandler
    :param use_mail: Whether to use the email notification function, default False
    :return: None
    '''
    logging.basicConfig(level=LOG_OUTPUT_LEVEL,
                        format=FORMATTER,
                        datefmt=DATE_FORMAT)

    # add rotating file handler
    rf_handler = handlers.RotatingFileHandler(LOG_FILE_PATH, maxBytes=LOG_FILE_SIZE, backupCount=LOG_BACKUP_COUNT)
    rf_handler.setLevel(LOG_FILE_LEVEL)
    formatter = logging.Formatter(FORMATTER)
    rf_handler.setFormatter(formatter)
    logging.getLogger().addHandler(rf_handler)

    # add smtp handler if use_mail is True
    if use_mail:
        mail_handler = handlers.SMTPHandler(
            mailhost=(MAIL_SERVER, MAIL_PORT),
            fromaddr=FROM_ADDR,
            toaddrs=TO_ADDRS.split(";"),
            subject=SUBJECT,
            credentials=CREDENTIALS
        )
        mail_handler.setLevel(LOG_MAIL_LEVEL)
        mail_handler.setFormatter(logging.Formatter(FORMATTER))
        logging.getLogger().addHandler(mail_handler)
예제 #2
0
def email_hdlr(subject="You've got mail",
               host="localhost",
               port=587,
               **kwargs):
    """An email log handler

    Kwargs:
        subject (str): The email subject (default: You've got mail.).
        host (str): The email server host (default: localhost).
        port (str): The email sever port (default: 587).
        sender (str): The email sender (default: the system username at gmail).

        recipients (List[str]): The email recipients (default: the system
            username at gmail).

        username (str): The email sever username (default: None).
        password (str): The email sever password (default: None).

    Returns:
        New instance of :class:`logging.handlers.SMTPHandler`

    Examples:
        >>> email_hdlr('hello world')  # doctest: +ELLIPSIS
        <...SMTPHandler...>
    """
    address = (host, port) if port else host
    def_email = "*****@*****.**" % environ.get("USER")
    sender = kwargs.get("sender", def_email)
    recipients = kwargs.get("recipients", [def_email])
    username = kwargs.get("username")
    password = kwargs.get("password")

    args = (address, sender, recipients, subject)
    credentials = (username, password) if username or password else None
    return hdlrs.SMTPHandler(*args, credentials=credentials)
예제 #3
0
파일: base.py 프로젝트: miz060/pyoperant
    def log_config(self):

        self.log_file = os.path.join(self.parameters['experiment_path'],
                                     self.parameters['subject'] + '.log')

        if self.debug:
            self.log_level = logging.DEBUG
        else:
            self.log_level = logging.INFO

        sys.excepthook = _log_except_hook  # send uncaught exceptions to log file

        logging.basicConfig(
            filename=self.log_file,
            level=self.log_level,
            format='"%(asctime)s","%(levelname)s","%(message)s"')
        self.log = logging.getLogger()

        if 'email' in self.parameters['log_handlers']:
            from pyoperant.local import SMTP_CONFIG
            from logging import handlers
            SMTP_CONFIG['toaddrs'] = [
                self.parameters['experimenter']['email'],
            ]

            email_handler = handlers.SMTPHandler(**SMTP_CONFIG)
            email_handler.setLevel(logging.WARNING)

            heading = '%s\n' % (self.parameters['subject'])
            formatter = logging.Formatter(
                heading + '%(levelname)s at %(asctime)s:\n%(message)s')
            email_handler.setFormatter(formatter)

            self.log.addHandler(email_handler)
예제 #4
0
파일: notifier.py 프로젝트: wuyusen/avarice
 def Simulator():
     logger = logging.getLogger('simulator')
     logger.setLevel(logging.DEBUG)
     simsmtphandler = handlers.SMTPHandler(gc.Notifier.SMTP.Host,
                                           gc.Notifier.SMTP.From,
                                           gc.Notifier.SMTP.To,
                                           'Avarice ' + 'Simulator')
     simsmtphandler.setLevel(logging.DEBUG)
     logger.addHandler(simsmtphandler)
예제 #5
0
파일: notifier.py 프로젝트: wuyusen/avarice
 def Trader():
     logger = logging.getLogger('trader')
     logger.setLevel(logging.DEBUG)
     tradersmtphandler = handlers.SMTPHandler(gc.Notifier.SMTP.Host,
                                              gc.Notifier.SMTP.From,
                                              gc.Notifier.SMTP.To,
                                              'Avarice ' + 'Trader')
     tradersmtphandler.setLevel(logging.DEBUG)
     logger.addHandler(tradersmtphandler)
예제 #6
0
    def _init(self):
        if not self.init:
            self.config = {
                'datefmt':
                '%d/%m/%Y-%H:%M:%S',
                'format':
                '\n%(asctime)s - %(name)s - [%(levelname)s] : %(message)s'
            }

            self.config_file = {
                'filename': os.path.join(PATH, 'log/app_out.log'),
                'maxBytes': 1024 * 1024,
                'backupCount': 10
            }

            self.config_mail = {
                'mailhost': ('smtp.email.com.br', 25),  # (host, port) or host
                'fromaddr': '*****@*****.**',
                'toaddrs': ['*****@*****.**'
                            ],  # lista dos enderecos a serem enviados 
                'subject': 'Alerta / Erro no Sistema',
                'credentials': None,  # (user, passw)
                'secure': None,
            }
            # Passando as configuracoes para o log
            logging.basicConfig(**config)
            if not os.path.exists(os.path.join(PATH, 'log')):
                os.mkdir(os.path.join(os.path.join(PATH, 'log')))

            # Criando uma instancia de Logger com o nome do modulo especifico
            self._logger = logging.getLogger(__name__)
            # Setando o level do log
            self._logger.setLevel(logging.INFO)
            # Criando o handler na qual sera a saida do log com as configuracoes

            ## Handler para saida em arquivo, provendo rotatividade de acordo com o
            ## tamanho de limite em bytes definido
            handler_file = handlers.RotatingFileHandler(**self.config_file)

            ## Handler para envio da saida do log por email
            ## todas as configuracoes sao definidas em config_mail
            handler_mail = handlers.SMTPHandler(**self.config_mail)
            handler_mail.setLevel(logging.ERROR)

            # Criando uma instancia para formatar a saida do log
            formatter = logging.Formatter(
                self.config.get('format'))  # formato do texto em geral
            formatter.datefmt = self.config.get('datefmt')  # formato da data

            # Adicionando as configuracoes do handler e formatter
            handler_file.setFormatter(formatter)
            handler_mail.setFormatter(formatter)

            self._logger.addHandler(handler_file)
            if self._use_mail:
                self._logger.addHandler(handler_mail)
            self.init = True
예제 #7
0
def email_logger(subject='数字货币每日搬砖'):
    logger = logging.getLogger('email_logger')
    logger.setLevel(logging.DEBUG)
    # subject = "数字货币搬砖{}收益".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
    email_handler = handlers.SMTPHandler(HOST,
                                         FROM,
                                         TO,
                                         subject, (USERNAME, PASSWD),
                                         secure=None)
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    email_handler.setFormatter(formatter)
    logger.addHandler(email_handler)
    return logger
예제 #8
0
async def amain(*argv):  # pylint: disable=too-many-locals
    """Async entry point for arbitrary command line arguments"""
    # Parse args and process
    parser = create_parser()
    args = parser.parse_args(argv)

    tag = "" if args.tag is None else " " + args.tag

    stderr_handle = logging.StreamHandler(sys.stderr)
    stderr_handle.setLevel(50 - 10 * min(args.verbose, 4))
    stderr_handle.setFormatter(
        logging.Formatter("%(asctime)s {}{} %(message)s".format(
            args.method, tag)))
    log_handlers = [stderr_handle]

    # Email Logging
    if args.recipient:  # pragma: no cover
        smtp_host = "localhost"

        # We need to do this to match the from address to the local host name
        # otherwise, email logging will not work. This seems to vary somewhat
        # by machine
        with smtplib.SMTP(smtp_host) as server:
            smtp_fromaddr = "EGTA Online <egta_online@{host}>".format(
                host=server.local_hostname)

        email_handler = handlers.SMTPHandler(
            smtp_host,
            smtp_fromaddr,
            args.recipient,
            "EGTA Status for {}{}".format(args.method, tag),
        )
        email_handler.setLevel(50 - args.email_verbosity * 10)
        email_handler.setFormatter(logging.Formatter("%(message)s"))
        log_handlers.append(email_handler)

    logging.basicConfig(level=0, handlers=log_handlers)

    try:
        await args.method.run(args)

    except KeyboardInterrupt as ex:  # pragma: no cover
        logging.critical("execution interrupted by user")
        raise ex

    except Exception as ex:  # pragma: no cover
        exc_type, exc_value, exc_traceback = sys.exc_info()
        logging.critical("".join(
            traceback.format_exception(exc_type, exc_value, exc_traceback)))
        raise ex
예제 #9
0
파일: handlers.py 프로젝트: mypan/pygogo
def email_hdlr(subject=None, **kwargs):
    """An email log handler

    Args:
        subject (str): The email subject (default: You've got mail.).

        kwargs(dict): Keyword arguments.

    Kwargs:
        host (str): The email server host (default: localhost).

        port (str): The email sever port (default: None).

        sender (str): The email sender (default: the system username at gmail).

        recipients (List[str]): The email recipients (default: the system
            username at gmail).

        username (str): The email sever username (default: None).

        password (str): The email sever password (default: None).

    Returns:
        New instance of :class:`logging.handlers.SMTPHandler`

    Examples:
        >>> email_hdlr('hello world')  # doctest: +ELLIPSIS
        <logging.handlers.SMTPHandler object at 0x...>
    """
    host = kwargs.get('host', 'localhost')
    port = kwargs.get('port')
    address = (host, port) if port else host
    sender = kwargs.get('sender', '*****@*****.**' % environ.get('USER'))
    def_recipient = '*****@*****.**' % environ.get('USER')
    recipients = kwargs.get('recipients', [def_recipient])
    subject = kwargs.get('subject', "You've got mail")
    username = kwargs.get('username')
    password = kwargs.get('password')

    args = (address, sender, recipients, subject)
    credentials = (username, password) if username or password else None
    return hdlrs.SMTPHandler(*args, credentials=credentials)
예제 #10
0
    def init_app(cls, app):
        Config.init_app(app)

        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) is not None:
                secure = ()

            mail_handler = handlers.SMTPHandler(
                mailhost=(cls.MAIL_SERVER, cls.MAIL_PORT),
                fromaddr=cls.MAIL_SENDER,
                toaddrs=[cls.JOBS_ADMIN],
                subject=cls.MAIL_SUBJECT_PREFIX + ' 应用告警',
                credentials=credentials,
                secure=secure)

            mail_handler.setLevel(logging.ERROR)
            app.logger.addHandler(mail_handler)
def app_factory(config):
    app = flask.Flask(__name__)
    app.config.from_object(config)
    email_handler = handlers.SMTPHandler(config.EMAIL_SMTP_SERVER,
                                         config.EMAIL_SENDER_ADDRESS,
                                         config.EMAIL_RECIPIENT_ADDRESS,
                                         "Failure @ "
                                         "http://www.adamcunnington.info",
                                         secure=())
    email_handler.setFormatter(
        logging.Formatter("Error Type: %(levelname)s\n"
                          "Location: %(pathname)s: "
                          "%(lineno)d\n"
                          "Module: %(module)s\n"
                          "Function: %(funcName)s\n"
                          "Time: %(asctime)s\n"
                          "%(message)s"))
    email_handler.setLevel(logging.ERROR)
    file_handler = handlers.FileHandler(
        os.path.join(os.path.dirname(__file__), "..", ".log"))
    file_handler.setFormatter(
        logging.Formatter("%(asctime)s (%(levelname)s) "
                          "-> %(message)s "
                          "[in %(pathname)s: "
                          "%(lineno)d]"))
    file_handler.setLevel(logging.WARNING)
    for logger in (app.logger, logging.getLogger("sqlalchemy")):
        for handler in (email_handler, file_handler):
            logger.addHandler(handler)
    if config.USE_API:
        from .. import api
        app.register_blueprint(api.user, subdomain="api")
        app.register_blueprint(api.token)
        flask.g.db = db = api.models.db
    else:
        from flask.ext import sqlalchemy
        flask.g.db = db = sqlalchemy.SQLAlchemy()
    db.initapp(app)

    return app
예제 #12
0
def logger(name, null=False):
    # Create the logger.
    logger = logging.getLogger(name)

    if null:
        nh = logging.NullHandler()
        logger.addHandler(nh)
        return logger

    # Configure the logger.
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    if APP['DEBUG']:
        # Output to file, if DEBUG=True
        fh = logging.FileHandler(log_path)
        fh.setFormatter(formatter)
        logger.addHandler(fh)

        # Output to console.
        ch = logging.StreamHandler()
        ch.setFormatter(formatter)
        logger.addHandler(ch)

    else:
        # Output to email.
        mh = handlers.SMTPHandler(
            (APP['EMAIL_HOST'], APP['EMAIL_PORT']),
            APP['EMAIL_HOST_USER'],
            APP['ADMINS'],
            'Argos Error :(',
            credentials=(APP['EMAIL_HOST_USER'], APP['EMAIL_HOST_PASSWORD']),
            secure=())
        mh.setLevel(logging.ERROR)
        logger.addHandler(mh)

    return logger
예제 #13
0
while logger.hasHandlers():
    for i in logger.handlers:
        logger.removeHandler(i)
file_handler = logging.FileHandler(LogName, encoding='utf-8')
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)

# 控制台日志Handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)
console_handler.setLevel(logging.INFO)

# 邮件日志Handler
mail_handler = handlers.SMTPHandler(
    ("smtp.163.com", 25), '*****@*****.**',
    ['*****@*****.**', '*****@*****.**'],
    "logging from my app",
    credentials=('*****@*****.**', ""),
)
mail_handler.setFormatter(formatter)
mail_handler.setLevel(logging.ERROR)

memory_handler = handlers.MemoryHandler(100)
memory_handler.setFormatter(formatter)
memory_handler.setLevel(logging.ERROR)
memory_handler.setTarget(mail_handler)

# 添加Handler生效
logger.addHandler(console_handler)
logger.addHandler(file_handler)
# logger.addHandler(memory_handler)
예제 #14
0
def configure_logging(app):  # pragma: no cover
    """Configure logging."""
    if app.config.get('LOG_SQL'):
        sql_log_file = '/tmp/sql_log'
        sql_file_handler = handlers.RotatingFileHandler(sql_log_file,
                                                        maxBytes=1000000,
                                                        backupCount=20)
        sql_file_handler.setFormatter(
            logging.Formatter('%(asctime)s %(thread)d: %(message)s'))
        sql_log = logging.getLogger('sqlalchemy.engine')
        sql_log.setLevel(logging.INFO)
        sql_log.addHandler(sql_file_handler)

    if app.testing or not app.config.get('LOG_FOLDER', None):
        # Write logs to stdout by default and when testing
        return

    if not os.path.exists(app.config['LOG_FOLDER']):
        os.mkdir(app.config['LOG_FOLDER'])

    level = getattr(logging, app.config['LOG_LEVEL'].upper())

    info_log = os.path.join(app.config['LOG_FOLDER'], 'info.log')
    # For WSGI servers, the log file is only writable by www-data
    # This prevents users from being able to run other management
    # commands as themselves.  If current user can't write to the
    # info_log, bail out - relying on stdout/stderr
    try:
        with open(info_log, 'a+'):
            pass
    except IOError:
        print >> sys.stderr, "Can't open log file '%s', use stdout" %\
            info_log
        print >> sys.stderr,\
            "Set LOG_FOLDER to a writable directory in configuration file"
        return

    info_file_handler = handlers.RotatingFileHandler(info_log,
                                                     maxBytes=1000000,
                                                     backupCount=20)
    info_file_handler.setLevel(level)
    info_file_handler.setFormatter(
        logging.Formatter('%(asctime)s %(levelname)s: %(message)s '
                          '[in %(pathname)s:%(lineno)d]'))

    app.logger.setLevel(level)
    app.logger.addHandler(info_file_handler)

    # OAuth library logging tends to be helpful for connection
    # debugging
    for logger in ('oauthlib', 'flask_oauthlib'):
        log = logging.getLogger(logger)
        log.setLevel(level)
        log.addHandler(info_file_handler)

    from .tasks import logger as task_logger
    task_logger.setLevel(level)
    task_logger.addHandler(info_file_handler)

    # Configure Error Emails for high level log messages, only in prod mode
    ADMINS = app.config['ERROR_SENDTO_EMAIL']
    if not app.debug:
        mail_handler = handlers.SMTPHandler(
            '127.0.0.1', app.config['MAIL_DEFAULT_SENDER'], ADMINS,
            '{} Log Message'.format(app.config['SERVER_NAME']))
        mail_handler.setLevel(logging.ERROR)
        app.logger.addHandler(mail_handler)
        task_logger.addHandler(mail_handler)
예제 #15
0
파일: __init__.py 프로젝트: altai/focus
LOG.setLevel(logging.DEBUG if app.debug else logging.WARNING)
if app.config.get('LOG_FILE', '') != '':
    rotating_file_handler = handlers.RotatingFileHandler(
        app.config['LOG_FILE'],
        maxBytes=app.config['LOG_MAX_BYTES'],
        backupCount=app.config['LOG_BACKUP_COUNT'])
    rotating_file_handler.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]'
            ))
    LOG.addHandler(rotating_file_handler)
if not app.debug and len(app.config['ADMINS']):
    mail_handler = handlers.SMTPHandler(
        app.config['MAIL_SERVER'],
        app.config['DEFAULT_MAIL_SENDER'][1]
        if len(app.config['DEFAULT_MAIL_SENDER']) == 2
        else app.config['DEFAULT_MAIL_SENDER'],
        app.config['ADMINS'],
        'Focus At %s Failed' % socket.getfqdn())
    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.ERROR)
예제 #16
0
log = logging.getLogger()
log.setLevel(logging.DEBUG)

#---------------------------------------------------------------------------#
# This will send the error messages in the specified namespace to a file.
# The available namespaces in pymodbus are as follows:
#---------------------------------------------------------------------------#
# * pymodbus.*          - The root namespace
# * pymodbus.server.*   - all logging messages involving the modbus server
# * pymodbus.client.*   - all logging messages involving the client
# * pymodbus.protocol.* - all logging messages inside the protocol layer
#---------------------------------------------------------------------------#
logging.basicConfig()
log = logging.getLogger('pymodbus.server')
log.setLevel(logging.ERROR)

#---------------------------------------------------------------------------#
# This will send the error messages to the specified handlers:
# * docs.python.org/library/logging.html
#---------------------------------------------------------------------------#
log = logging.getLogger('pymodbus')
log.setLevel(logging.ERROR)
handlers = [
    Handlers.RotatingFileHandler("logfile", maxBytes=1024 * 1024),
    Handlers.SMTPHandler("mx.host.com", "*****@*****.**",
                         ["*****@*****.**"], "Pymodbus"),
    Handlers.SysLogHandler(facility="daemon"),
    Handlers.DatagramHandler('localhost', 12345),
]
[log.addHandler(h) for h in handlers]
예제 #17
0
파일: app.py 프로젝트: gniall12/shuff
from flask import Flask, redirect, url_for, request, session, abort, render_template, make_response

from .config import secret_key, mail_host, email_address, email_password
from .shuffler import shuffle
from .spotify_oauth import oauth, get_user_playlists

app = Flask(__name__)
oauth.init_app(app)
app.config['SECRET_KEY'] = secret_key
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))

smtp_handler = handlers.SMTPHandler(mailhost=(mail_host, 587),
                                    fromaddr=email_address,
                                    toaddrs=email_address,
                                    subject=u"Shuff error",
                                    credentials=(email_address,
                                                 email_password),
                                    secure=())

logger = logging.getLogger()
smtp_handler.setLevel(logging.ERROR)
logger.addHandler(smtp_handler)


@app.route('/', methods=['GET'])
def home():
    if ('access_token' not in session):
        return (redirect(url_for('login')))
    try:
        playlists = get_user_playlists()
예제 #18
0
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# Output to file, if DEBUG=True
fh = logging.FileHandler(log_path)
fh.setFormatter(formatter)
logger.addHandler(fh)

# Output to console.
ch = logging.StreamHandler()
ch.setFormatter(formatter)
logger.addHandler(ch)

# Output to email.
mh = handlers.SMTPHandler((config.MAIL_HOST, config.MAIL_PORT),
                          config.MAIL_USER,
                          config.ADMINS,
                          'Argos Corpora Error :(',
                          credentials=(config.MAIL_USER, config.MAIL_PASS),
                          secure=())
mh.setLevel(logging.ERROR)
logger.addHandler(mh)


def notify(subject, body):
    """
    Send an e-mail notification.
    """
    from_addr = config.MAIL_USER

    # Construct the message.
    msg = MIMEMultipart()
    msg['From'] = from_addr
예제 #19
0
def init_log_config(log_dir="",
                    file_prefix="debug",
                    file_size_limit=20 * 1024 * 1024,
                    backup_count=30,
                    use_mail=False,
                    console_level=LOG_CONSOLE_LEVEL,
                    file_level=LOG_FILE_LEVEL,
                    mail_level=LOG_MAIL_LEVEL,
                    when="midnight",
                    interval=1,
                    crated_time_in_file_name=False):
    '''
    Do basic configuration for the logging system. support ConsoleHandler, RotatingFileHandler and SMTPHandler
    :param log_dir: the dir where to save log files, default "{current_path}/logs"
    :param file_prefix: log file name prefix, default "debug"
    :param file_size_limit: log file size limit, default 10M
    :param backup_count: log file count, default 10
    :param use_mail: Whether to use the email notification function, default False
    :param console_level: the level of output log in console, default logging.DEBUG
    :param file_level: the level of log file, default logging.INFO
    :param mail_level: the level of log mail, default logging.ERROR
    :param when: rotating the log file at certain timed intervals. 'D'-days, 'H'-hours, 'M'-minutes
    :param interval: rotating the log file at certain timed intervals.
    :return: None
    '''

    try:
        logging.basicConfig(level=console_level,
                            format=FORMATTER,
                            datefmt=DATE_FORMAT)

        # log file directory
        if not log_dir:
            log_dir = os.path.join(sys.path[0], "logs")
            # log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
        if not os.path.isdir(log_dir):
            os.mkdir(log_dir)

        # default log file name like: debug_2018-08-27_15-40-52.log
        if crated_time_in_file_name:
            log_file_path = os.path.join(
                log_dir,
                "{}_{}.log".format(file_prefix,
                                   datetime.now().strftime("%Y%m%d_%H%M%S")))
        else:
            log_file_path = os.path.join(log_dir, "{}.log".format(file_prefix))

        # add rotating file handler
        # rf_handler = handlers.RotatingFileHandler(log_file_path, maxBytes=file_size_limit, backupCount=backup_count, encoding="utf-8")
        if when:
            rf_handler = handlers.TimedRotatingFileHandler(
                log_file_path,
                when=when,
                backupCount=backup_count,
                interval=interval,
                encoding="utf-8")
        else:
            rf_handler = handlers.RotatingFileHandler(log_file_path,
                                                      maxBytes=file_size_limit,
                                                      backupCount=backup_count,
                                                      encoding="utf-8")

        rf_handler.setLevel(file_level)
        formatter = logging.Formatter(FORMATTER)
        rf_handler.setFormatter(formatter)
        logging.getLogger().addHandler(rf_handler)

        # add smtp handler if use_mail is True
        if use_mail:
            mail_handler = handlers.SMTPHandler(mailhost=(MAIL_SERVER,
                                                          MAIL_PORT),
                                                fromaddr=FROM_ADDR,
                                                toaddrs=TO_ADDRS.split(";"),
                                                subject=SUBJECT,
                                                credentials=CREDENTIALS)
            mail_handler.setLevel(mail_level)
            mail_handler.setFormatter(logging.Formatter(FORMATTER))
            logging.getLogger().addHandler(mail_handler)
    except Exception as e:
        print("init log config catch exception:{}".format(e))
        return False

    return True
예제 #20
0
def logger(name, log_path=None, email_config={}, console=True, rotating=False, rotating_config={}):
    """
    Creates a logger.

    Can also log errors to email if a dict of the following form
    is passed in as `email_config`:

        {
            'host': 'smtp.gmail.com',
            'port': 587,
            'user': '******',
            'pass': '******',
            'admins': ['*****@*****.**']
        }
    """

    # Create the logger.
    logger = logging.getLogger(name)

    # Configure the logger.
    logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    # Output to file
    if log_path is not None:
        if rotating:
            # Add a rotating log handler
            rconfig = {
                'maxBytes': 10000,
                'backupCount': 5
            }
            rconfig.update(rotating_config)
            fh = handlers.RotatingFileHandler(log_path, **rconfig)
        else:
            fh = logging.FileHandler(log_path)
        fh.setFormatter(formatter)
        logger.addHandler(fh)

    # Output to console.
    if console:
        ch = logging.StreamHandler()
        ch.setFormatter(formatter)
        logger.addHandler(ch)


    if email_config:
        # Output to email.
        mh = handlers.SMTPHandler(
                (email_config['host'], email_config['port']),
                email_config['user'],
                email_config['admins'],
                '{} Error :('.format(name),
                credentials=(
                    email_config['user'],
                    email_config['pass']
                ),
                secure=()
        )
        mh.setLevel(logging.ERROR)
        logger.addHandler(mh)

    return logger
    SENDER = OPTIONS.get('mail_sender', '*****@*****.**')
    MAIL_FROM = '"Pytroll-zipcollector error" <' + str(SENDER) + '>'
    try:
        RECIPIENTS = OPTIONS.get("mail_subscribers").split()
    except AttributeError:
        print("Recipients must be set! Exit...")
        sys.exit(9)

    MAIL_TO = RECIPIENTS
    MAIL_SUBJECT = 'New Critical Event From the pytroll-zipcollector'

    from logging import handlers
    handler = logging.StreamHandler(sys.stderr)

    handler.setLevel(logging.DEBUG)
    formatter = logging.Formatter(fmt=_DEFAULT_LOG_FORMAT,
                                  datefmt=_DEFAULT_TIME_FORMAT)
    handler.setFormatter(formatter)
    logging.getLogger('').addHandler(handler)
    logging.getLogger('').setLevel(logging.DEBUG)
    logging.getLogger('posttroll').setLevel(logging.INFO)

    smtp_handler = handlers.SMTPHandler(MAIL_HOST, MAIL_FROM, MAIL_TO,
                                        MAIL_SUBJECT)
    smtp_handler.setLevel(logging.CRITICAL)
    logging.getLogger('').addHandler(smtp_handler)

    logger = logging.getLogger('zipcollector_runner')

    zipcollector_live_runner(OPTIONS)
import logging
import socket
import traceback
from logging import handlers

HOST = "localhost"
FROM = '"Application Alert" <*****@*****.**>'
TO = "*****@*****.**"
SUBJECT = "New critical Event from [APPLICATION]"

logging.basicConfig(level=logging.INFO)

handler = handlers.SMTPHandler(HOST, FROM, TO, SUBJECT)

email_logger = logging.getLogger("smtp.example")
email_logger.addHandler(handler)
email_logger.setLevel = logging.CRITICAL

logging.info("Roor logger output")

try:
    email_logger.critical(
        "critical Event Notification\n\nTraceback:\n%s",
        "".join(traceback.format_stack()),
    )
except socket.error as error:
    logging.critical("Could not send email via SMTPHandler: %r", error)
예제 #23
0
# __author__ = "Winter Ding"
# Email: [email protected]
import logging
from logging import handlers
import os

log_file = r'D:\test\pacfile_synclog\sync_log.txt'
log_folder = os.path.dirname(log_file)
if not os.path.exists(log_folder):
    os.mkdir(log_folder)

current_user = os.environ['USERNAME']

logger = logging.getLogger(current_user)
logger.setLevel(level=logging.INFO)

rotateLog = handlers.RotatingFileHandler(log_file, maxBytes=10*1024, backupCount=3)
rotateLog.setLevel(level=logging.INFO)

mail_log = handlers.SMTPHandler()
mail_log.setLevel(level=logging.WARNING)

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

logger.addHandler(rotateLog)
logger.addHandler(mail_log)


예제 #24
0
                      key_func=get_remote_address,
                      default_limits=["4800 per day", "200 per hour"])
    # toolbar
    toolbar = DebugToolbarExtension(app)
    toolbar.init_app(app)

    # dashboard
    dashboard.config.init_from(file='config.cfg')
    dashboard.bind(app)
    # blueprint import and registration
    from website.bp import *

    # logging
    mail_handler = handlers.SMTPHandler(
        mailhost='coding-for-kidz.herokuapp.com',
        fromaddr='*****@*****.**',
        toaddrs=['*****@*****.**'],
        subject='Application Error')

    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(
        logging.Formatter(
            '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'))

    if not app.debug:
        app.logger.addHandler(mail_handler)
    sentry_sdk.init(
        dsn=
        "https://[email protected]/5410703",
        integrations=[FlaskIntegration()],
        traces_sample_rate=1.0)
예제 #25
0
    file_handler = handlers.RotatingFileHandler(
        'coati_flask.log',
        maxBytes=10 * 1024 * 1024,
        backupCount=10
    )

    # Format: <DATE> <TIME> <LOG_LEVEL>: <MESSAGE> [in <FILE_PATH>:<LINE_NO>]
    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)

    # Configure error logging by email
    mail_handler = handlers.SMTPHandler(
        app.config.get('MAIL_SERVER'),
        app.config.get('MAIL_SERVER_ERROR_FROM'),
        app.config.get('ADMIN_EMAILS'),
        '[Coati] An error occurred'
    )
    mail_handler.setLevel(logging.ERROR)
    app.logger.addHandler(mail_handler)


if __name__ == '__main__':
    manager = Manager(app)
    manager.run()
예제 #26
0
import sys
load_dotenv(verbose=True)
env_path = rf"{os.path.split(__file__)[0]}\.env"
print(env_path)
load_dotenv(dotenv_path=env_path)
shape_path = os.path.dirname(os.path.realpath(__file__))
prefix = "/Users/leo/Dropbox/shape_dataset/"

logger = logging.getLogger("mylogger")
logger.setLevel(logging.DEBUG)
user = os.getenv("USER")
pwd = os.getenv("PASSWORD")
print(type(user), user, pwd)
em_handler = handlers.SMTPHandler(mailhost=("smtp.gmail.com", 587),
                                  fromaddr="*****@*****.**",
                                  toaddrs=["*****@*****.**"],
                                  subject="Shape Project New Logging Message",
                                  credentials=(user, pwd),
                                  secure=())
em_handler.setFormatter(
    logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
em_handler.setLevel(logging.DEBUG)
logger.addHandler(em_handler)

IMAGENET_DIR = r"D:\projects\shape_dataset\imagenet_val"
IMAGENET_16CAT_DIR = r"D:\projects\shape_dataset\imagenet_16categories"
CHECKERBOARD_PREP = r"D:\projects\shape_dataset\checkerboard_prep_new"

# CHECKERBOARD_DATASET_HUMAN = r"D:\projects\shape_dataset\checkerboard_dataset_human_png"
# CHECKERBOARD_DATASET_HUMAN_LATTICE_BLACK = r"D:\projects\shape_dataset\checkerboard_lattice_dataset_human_black"
# CHECKERBOARD_DATASET_HUMAN_LATTICE_GRAY = r"D:\projects\shape_dataset\checkerboard_lattice_dataset_human_gray"
# CHECKERBOARD_GRAY_DATASET_HUMAN = r"D:\projects\shape_dataset\checkerboard_gray_dataset_human_png"