Python logging.handlers.SysLogHandler() Examples

The following are 29 code examples of logging.handlers.SysLogHandler(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module logging.handlers , or try the search function .
Example #1
Source File: args.py    From octodns with MIT License 7 votes vote down vote up
def _setup_logging(self, args, default_log_level):
        fmt = '%(asctime)s [%(thread)d] %(levelname)-5s %(name)s %(message)s'
        formatter = Formatter(fmt=fmt, datefmt='%Y-%m-%dT%H:%M:%S ')
        stream = stdout if args.log_stream_stdout else stderr
        handler = StreamHandler(stream=stream)
        handler.setFormatter(formatter)
        logger = getLogger()
        logger.addHandler(handler)

        if args.log_syslog:
            fmt = 'octodns[%(process)-5s:%(thread)d]: %(name)s ' \
                '%(levelname)-5s %(message)s'
            handler = SysLogHandler(address=args.syslog_device,
                                    facility=args.syslog_facility)
            handler.setFormatter(Formatter(fmt=fmt))
            logger.addHandler(handler)

        logger.level = DEBUG if args.debug else default_log_level

        # boto is noisy, set it to warn
        getLogger('botocore').level = WARN
        # DynectSession is noisy too
        getLogger('DynectSession').level = WARN 
Example #2
Source File: edge_logging.py    From gateway-workflows with Apache License 2.0 6 votes vote down vote up
def __init__(self, name, cfg):
        log_type = cfg.get_value(name, 'type')
        logger = logging.getLogger(cfg.get_value(name, 'logger_name'))
        formatter = logging.Formatter(cfg.get_value(name, 'logger_formatter'),
                                      cfg.get_value(name, 'time_formatter'))
        if log_type == 'file':
            logger.setLevel(cfg.get_value(name, 'log_level'))
            handler = logging.handlers.TimedRotatingFileHandler(
                cfg.get_value(name, 'file_name'), when="H", interval=24, backupCount=10)
        elif log_type == 'leef':
            protocol = cfg.get_value(name, 'protocol')
            socket_type = socket.SOCK_STREAM if protocol == 'tcp' else socket.SOCK_DGRAM
            logger.setLevel(logging.INFO)
            handler = SysLogHandler(address=(
                cfg.get_value(name, 'server'), cfg.get_value(name, 'port')),
                        facility=logging.handlers.SysLogHandler.LOG_LOCAL1, socktype=socket_type)
        else:
            raise NameError('No valid log_type ' + log_type + ', valid values are file or leef')
        logger.addHandler(handler)
        handler.setFormatter(formatter)
        self._store = logger
        self._handler = handler 
Example #3
Source File: logger.py    From hermes-audio-server with MIT License 6 votes vote down vote up
def get_logger(command, verbose, daemon):
    """Return a Logger object with the right level, formatter and handler."""

    if daemon:
        handler = SysLogHandler(address=get_domain_socket())
        formatter = logging.Formatter(fmt=DAEMON_FORMAT.format(command))
        logger = logging.getLogger(command)
    else:
        handler = colorlog.StreamHandler(stream=sys.stdout)
        formatter = colorlog.ColoredFormatter(INTERACTIVE_FORMAT,
                                              log_colors=LOG_COLORS)
        logger = colorlog.getLogger(command)

    if verbose:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    handler.setFormatter(formatter)
    logger.addHandler(handler)

    return logger 
Example #4
Source File: logger.py    From MozDef with Mozilla Public License 2.0 6 votes vote down vote up
def initLogger(options=None):
    logger.level = logging.INFO
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    formatter.formatTime = loggerTimeStamp

    output = ''
    try:
        output = options.output
    except Exception:
        output = 'stderr'

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

    if output == 'syslog':
        logger.addHandler(SysLogHandler(address=(options.sysloghostname, options.syslogport)))
    else:
        sh = logging.StreamHandler(sys.stderr)
        sh.setFormatter(formatter)
        logger.addHandler(sh) 
Example #5
Source File: _syslog.py    From insights-core with Apache License 2.0 6 votes vote down vote up
def __init__(self, broker, stream=None, archive=None):
        self.broker = broker
        self.exceptions = []
        self.rules = []
        self.user = getuser()
        self.pid = str(os.getpid())
        self.stream = stream
        self.archive = os.path.realpath(archive) if archive else None

        if not self.stream:
            self.logger = logging.getLogger('sysLogLogger')
            self.logger.propagate = False
            self.logger.setLevel(logging.INFO)

            address = '/dev/log'
            if not os.path.exists(address):
                address = 'localhost', 514

            self.handler = handlers.SysLogHandler(address)
            self.handler.formatter = logging.Formatter('%(message)s')
            self.logger.addHandler(self.handler) 
Example #6
Source File: common.py    From marathon-lb with Apache License 2.0 6 votes vote down vote up
def setup_logging(logger, syslog_socket, log_format, log_level='DEBUG'):
    log_level = log_level.upper()

    if log_level not in ['CRITICAL', 'ERROR', 'WARNING',
                         'INFO', 'DEBUG', 'NOTSET']:
        raise Exception('Invalid log level: {}'.format(log_level.upper()))

    logger.setLevel(getattr(logging, log_level))

    formatter = logging.Formatter(log_format)

    consoleHandler = logging.StreamHandler()
    consoleHandler.setFormatter(formatter)
    logger.addHandler(consoleHandler)

    if syslog_socket != '/dev/null':
        syslogHandler = SysLogHandler(syslog_socket)
        syslogHandler.setFormatter(formatter)
        logger.addHandler(syslogHandler) 
Example #7
Source File: neutron-ha-tool.py    From ansible-lxc-rpc with Apache License 2.0 5 votes vote down vote up
def setup_logging(args):
    level = logging.INFO
    if args.quiet:
        level = logging.WARN
    if args.debug:
        level = logging.DEBUG
    logging.basicConfig(level=level, format=LOG_FORMAT, date_fmt=LOG_DATE)
    handler = SysLogHandler(address='/dev/log')
    syslog_formatter = logging.Formatter('%(name)s: %(levelname)s %(message)s')
    handler.setFormatter(syslog_formatter)
    LOG.addHandler(handler) 
Example #8
Source File: utils.py    From storlets with Apache License 2.0 5 votes vote down vote up
def get_logger(logger_name, log_level, container_id):
    """
    Initialize logging of this process and set logger format

    :param logger_name: The name to report with
    :param log_level: The verbosity level. This should be selected
    :param container_id: container id
    """
    log_level = log_level.upper()

    # NOTE(takashi): currently logging.WARNING is defined as the same value
    #                as logging.WARN, so we can properly handle WARNING here
    try:
        level = getattr(logging, log_level)
    except AttributeError:
        level = logging.ERROR

    logger = logging.getLogger("CONT #" + container_id + ": " + logger_name)

    if log_level == 'OFF':
        logging.disable(logging.CRITICAL)
    else:
        logger.setLevel(level)

    log_handler = SysLogHandler('/dev/log')
    str_format = '%(name)-12s: %(levelname)-8s %(funcName)s' + \
                 ' %(lineno)s [%(process)d, %(threadName)s]' + \
                 ' %(message)s'
    formatter = logging.Formatter(str_format)
    log_handler.setFormatter(formatter)
    log_handler.setLevel(level)
    logger.addHandler(log_handler)
    return logger 
Example #9
Source File: config.py    From flasky-with-celery with MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # log to syslog
        import logging
        from logging.handlers import SysLogHandler
        syslog_handler = SysLogHandler()
        syslog_handler.setLevel(logging.WARNING)
        app.logger.addHandler(syslog_handler) 
Example #10
Source File: config.py    From flask-base with MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # Log to syslog
        import logging
        from logging.handlers import SysLogHandler
        syslog_handler = SysLogHandler()
        syslog_handler.setLevel(logging.WARNING)
        app.logger.addHandler(syslog_handler) 
Example #11
Source File: log.py    From snmpfwd with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def init(self, *priv):
        if len(priv) < 1:
            raise SnmpfwdError('Bad syslog params, need at least facility, also accept '
                               'host, port, socktype (tcp|udp)')
        if len(priv) < 2:
            priv = [priv[0], 'debug']
        if len(priv) < 3:
            # search for syslog local socket

            for dev in self.SYSLOG_SOCKET_PATHS:
                if os.path.exists(dev):
                    priv = [priv[0], priv[1], dev]
                    break
            else:
                priv = [priv[0], priv[1], 'localhost', 514, 'udp']

        if not priv[2].startswith('/'):
            if len(priv) < 4:
                priv = [priv[0], priv[1], priv[2], 514, 'udp']
            if len(priv) < 5:
                priv = [priv[0], priv[1], priv[2], 514, 'udp']
            priv = [priv[0], priv[1], priv[2], int(priv[3]), priv[4]]

        try:
            handler = handlers.SysLogHandler(
                address=priv[2].startswith('/') and priv[2] or (priv[2], int(priv[3])),
                facility=priv[0].lower(),
                socktype=len(priv) > 4 and priv[4] == 'tcp' and socket.SOCK_STREAM or socket.SOCK_DGRAM
            )

        except Exception:
            raise SnmpfwdError('Bad syslog option(s): %s' % sys.exc_info()[1])

        handler.setFormatter(logging.Formatter('%(asctime)s %(name)s: %(message)s'))

        self._logger.addHandler(handler) 
Example #12
Source File: config.py    From flasky-first-edition with MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # log to syslog
        import logging
        from logging.handlers import SysLogHandler
        syslog_handler = SysLogHandler()
        syslog_handler.setLevel(logging.WARNING)
        app.logger.addHandler(syslog_handler) 
Example #13
Source File: config.py    From penn-club-ratings with MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # Log to syslog
        import logging
        from logging.handlers import SysLogHandler
        syslog_handler = SysLogHandler()
        syslog_handler.setLevel(logging.WARNING)
        app.logger.addHandler(syslog_handler) 
Example #14
Source File: config.py    From braindump with MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # log to syslog
        import logging
        from logging.handlers import SysLogHandler
        syslog_handler = SysLogHandler()
        syslog_handler.setLevel(logging.WARNING)
        app.logger.addHandler(syslog_handler) 
Example #15
Source File: config.py    From BhagavadGita with GNU General Public License v3.0 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # Log to syslog
        import logging
        from logging.handlers import SysLogHandler
        syslog_handler = SysLogHandler()
        syslog_handler.setLevel(logging.WARNING)
        app.logger.addHandler(syslog_handler) 
Example #16
Source File: neutron-ha-tool.py    From ansible-lxc-rpc with Apache License 2.0 5 votes vote down vote up
def setup_logging(args):
    level = logging.INFO
    if args.quiet:
        level = logging.WARN
    if args.debug:
        level = logging.DEBUG
    logging.basicConfig(level=level, format=LOG_FORMAT, date_fmt=LOG_DATE)
    handler = SysLogHandler(address='/dev/log')
    syslog_formatter = logging.Formatter('%(name)s: %(levelname)s %(message)s')
    handler.setFormatter(syslog_formatter)
    LOG.addHandler(handler) 
Example #17
Source File: neutron-ha-tool.py    From ansible-lxc-rpc with Apache License 2.0 5 votes vote down vote up
def setup_logging(args):
    level = logging.INFO
    if args.quiet:
        level = logging.WARN
    if args.debug:
        level = logging.DEBUG
    logging.basicConfig(level=level, format=LOG_FORMAT, date_fmt=LOG_DATE)
    handler = SysLogHandler(address='/dev/log')
    syslog_formatter = logging.Formatter('%(name)s: %(levelname)s %(message)s')
    handler.setFormatter(syslog_formatter)
    LOG.addHandler(handler) 
Example #18
Source File: neutron-ha-tool.py    From ansible-lxc-rpc with Apache License 2.0 5 votes vote down vote up
def setup_logging(args):
    level = logging.INFO
    if args.quiet:
        level = logging.WARN
    if args.debug:
        level = logging.DEBUG
    logging.basicConfig(level=level, format=LOG_FORMAT, date_fmt=LOG_DATE)
    handler = SysLogHandler(address='/dev/log')
    syslog_formatter = logging.Formatter('%(name)s: %(levelname)s %(message)s')
    handler.setFormatter(syslog_formatter)
    LOG.addHandler(handler) 
Example #19
Source File: __init__.py    From supervisor-logging with Apache License 2.0 5 votes vote down vote up
def main():
    """
    Main application loop.
    """

    env = os.environ

    try:
        host = env['SYSLOG_SERVER']
        port = int(env['SYSLOG_PORT'])
        socktype = socket.SOCK_DGRAM if env['SYSLOG_PROTO'] == 'udp' \
            else socket.SOCK_STREAM
    except KeyError:
        sys.exit("SYSLOG_SERVER, SYSLOG_PORT and SYSLOG_PROTO are required.")

    handler = SysLogHandler(
        address=(host, port),
        socktype=socktype,
    )
    handler.setFormatter(PalletFormatter())

    for event_headers, event_data in supervisor_events(sys.stdin, sys.stdout):
        event = logging.LogRecord(
            name=event_headers['processname'],
            level=logging.INFO,
            pathname=None,
            lineno=0,
            msg=event_data,
            args=(),
            exc_info=None,
        )
        event.process = int(event_headers['pid'])
        handler.handle(event) 
Example #20
Source File: neutron-ha-tool.py    From ansible-lxc-rpc with Apache License 2.0 5 votes vote down vote up
def setup_logging(args):
    level = logging.INFO
    if args.quiet:
        level = logging.WARN
    if args.debug:
        level = logging.DEBUG
    logging.basicConfig(level=level, format=LOG_FORMAT, date_fmt=LOG_DATE)
    handler = SysLogHandler(address='/dev/log')
    syslog_formatter = logging.Formatter('%(name)s: %(levelname)s %(message)s')
    handler.setFormatter(syslog_formatter)
    LOG.addHandler(handler) 
Example #21
Source File: log.py    From conjure-up with MIT License 5 votes vote down vote up
def setup_logging(app, logfile, debug=True):
    old_factory = logging.getLogRecordFactory()

    def spell_record_factory(*args, **kwargs):
        record = old_factory(*args, **kwargs)
        if record.name != 'conjure-up':
            record.filename = '{}: {}'.format(record.name, record.filename)
        spell_name = app.config.get('spell', consts.UNSPECIFIED_SPELL)
        record.name = 'conjure-up/{}'.format(spell_name)
        return record

    logging.setLogRecordFactory(spell_record_factory)

    cmdslog = TimedRotatingFileHandler(logfile,
                                       when='D',
                                       interval=1,
                                       backupCount=7)
    cmdslog.setFormatter(logging.Formatter(
        "%(asctime)s [%(levelname)s] %(name)s - "
        "%(filename)s:%(lineno)d - %(message)s"))

    root_logger = logging.getLogger()
    app_logger = logging.getLogger('conjure-up')

    if debug:
        app_logger.setLevel(logging.DEBUG)
        root_logger.setLevel(logging.DEBUG)
    else:
        # always use DEBUG level for app, for now
        app_logger.setLevel(logging.DEBUG)
        root_logger.setLevel(logging.INFO)

    root_logger.addHandler(cmdslog)
    if os.path.exists('/dev/log'):
        st_mode = os.stat('/dev/log').st_mode
        if stat.S_ISSOCK(st_mode):
            syslog_h = SysLogHandler(address='/dev/log')
            syslog_h.set_name('conjure-up')
            app_logger.addHandler(syslog_h)

    return app_logger 
Example #22
Source File: alerta_logger.py    From alerta-contrib with MIT License 5 votes vote down vote up
def __init__(self, name=None):

        self.logger = logging.getLogger(name)

        if sys.platform == "darwin":
            socket = '/var/run/syslog'
        else:
            socket = '/dev/log'
        facility = LOGGER_SYSLOG_FACILITY

        syslog = SysLogHandler(address=socket, facility=facility)
        syslog.setFormatter(logging.Formatter(fmt=LOGGER_SYSLOG_FORMAT, datefmt=LOGGER_SYSLOG_DATE_FORMAT))
        self.logger.addHandler(syslog)

        super(Syslog, self).__init__(name) 
Example #23
Source File: config.py    From circleci-demo-python-flask with MIT License 5 votes vote down vote up
def init_app(cls, app):
        ProductionConfig.init_app(app)

        # log to syslog
        import logging
        from logging.handlers import SysLogHandler
        syslog_handler = SysLogHandler()
        syslog_handler.setLevel(logging.WARNING)
        app.logger.addHandler(syslog_handler) 
Example #24
Source File: __init__.py    From certidude with MIT License 5 votes vote down vote up
def __init__(self):
        app = falcon.API(middleware=NormalizeMiddleware())
        app.req_options.auto_parse_form_urlencoded = True
        self.attach(app)

        # Set up log handlers
        log_handlers = []
        if config.LOGGING_BACKEND == "sql":
            from certidude.mysqllog import LogHandler
            from certidude.api.log import LogResource
            uri = config.cp.get("logging", "database")
            log_handlers.append(LogHandler(uri))
        elif config.LOGGING_BACKEND == "syslog":
            from logging.handlers import SysLogHandler
            log_handlers.append(SysLogHandler())
            # Browsing syslog via HTTP is obviously not possible out of the box
        elif config.LOGGING_BACKEND:
            raise ValueError("Invalid logging.backend = %s" % config.LOGGING_BACKEND)
        from certidude.push import EventSourceLogHandler
        log_handlers.append(EventSourceLogHandler())

        for j in logging.Logger.manager.loggerDict.values():
            if isinstance(j, logging.Logger): # PlaceHolder is what?
                if j.name.startswith("certidude."):
                    j.setLevel(logging.DEBUG)
                    for handler in log_handlers:
                        j.addHandler(handler)

        self.server = make_server("127.0.1.1", self.PORT, app, WSGIServer)
        setproctitle("certidude: %s" % self.NAME) 
Example #25
Source File: __init__.py    From flask-pycon2014 with MIT License 4 votes vote down vote up
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    if not app.config['DEBUG'] and not app.config['TESTING']:
        # configure logging for production

        # email errors to the administrators
        if app.config.get('MAIL_ERROR_RECIPIENT') is not None:
            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['MAIL_PASSWORD'])
                if app.config['MAIL_USE_TLS'] is not None:
                    secure = ()
            mail_handler = SMTPHandler(
                mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
                fromaddr=app.config['MAIL_DEFAULT_SENDER'],
                toaddrs=[app.config['MAIL_ERROR_RECIPIENT']],
                subject='[Talks] Application Error',
                credentials=credentials,
                secure=secure)
            mail_handler.setLevel(logging.ERROR)
            app.logger.addHandler(mail_handler)

        # send standard logs to syslog
        import logging
        from logging.handlers import SysLogHandler
        syslog_handler = SysLogHandler()
        syslog_handler.setLevel(logging.WARNING)
        app.logger.addHandler(syslog_handler)

    bootstrap.init_app(app)
    db.init_app(app)
    moment.init_app(app)
    pagedown.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)

    from .talks import talks as talks_blueprint
    app.register_blueprint(talks_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    from .api_1_0 import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api/1.0')

    from app.emails import start_email_thread
    @app.before_first_request
    def before_first_request():
        start_email_thread()

    return app 
Example #26
Source File: log.py    From snmpsim with BSD 2-Clause "Simplified" License 4 votes vote down vote up
def init(self, *priv):
        if len(priv) < 1:
            raise SnmpsimError(
                'Bad syslog params, need at least facility, also accept '
                'host, port, socktype (tcp|udp)')

        if len(priv) < 2:
            priv = [priv[0], 'debug']

        if len(priv) < 3:
            # search for syslog local socket

            for dev in self.SYSLOG_SOCKET_PATHS:
                if os.path.exists(dev):
                    priv = [priv[0], priv[1], dev]
                    break

            else:
                priv = [priv[0], priv[1], 'localhost', 514, 'udp']

        if not priv[2].startswith('/'):
            if len(priv) < 4:
                priv = [priv[0], priv[1], priv[2], 514, 'udp']

            if len(priv) < 5:
                priv = [priv[0], priv[1], priv[2], 514, 'udp']

            priv = [priv[0], priv[1], priv[2], int(priv[3]), priv[4]]

        try:
            handler = handlers.SysLogHandler(
                address=(priv[2].startswith('/') and priv[2]
                         or (priv[2], int(priv[3]))),
                facility=priv[0].lower(),
                socktype=(len(priv) > 4 and priv[4] == 'tcp' and
                          socket.SOCK_STREAM or socket.SOCK_DGRAM))

        except Exception as exc:
            raise SnmpsimError('Bad syslog option(s): %s' % exc)

        handler.setFormatter(
            logging.Formatter('%(asctime)s %(name)s: %(message)s'))

        self._logger.addHandler(handler) 
Example #27
Source File: logging_utils.py    From cclyzer with MIT License 4 votes vote down vote up
def setup_logging(lvl=logging.INFO):
    """Configure logging.

    This creates a file handler to the application cache and a syslog
    handler. It also sets up log formatting and level.

    """

    # Get runtime environment and settings
    env = runtime.Environment()
    app_name = settings.APP_NAME

    # Get root logger and set its logging level
    root_logger = logging.getLogger()
    root_logger.setLevel(lvl)

    # Add rotating file handler
    file_log = env.user_log_file
    file_formatter = logging.Formatter("[PID %(process)d - %(asctime)s %(levelname)5.5s] "
                                       "%(pathname)s: Line %(lineno)d: %(message)s")
    file_handler = RotatingFileHandler(file_log, maxBytes=(2 ** 20), backupCount=7)
    file_handler.setFormatter(file_formatter)
    root_logger.addHandler(file_handler)

    # Add system log handler
    try:
        syslog_formatter = logging.Formatter("[{}] %(message)s".format(app_name))
        syslog_handler = SysLogHandler(address='/dev/log')
        syslog_handler.setFormatter(syslog_formatter)
        root_logger.addHandler(syslog_handler)
    except:
        root_logger.warning('Cannot add system logger')

    # Add stderr handler
    stderr_formatter = ConsoleFormatter("%(levelname)s (%(name)s): %(message)s")
    stderr_handler = StreamHandler(stream=sys.stderr)
    stderr_handler.setFormatter(stderr_formatter)
    stderr_handler.setLevel(logging.WARNING)
    root_logger.addHandler(stderr_handler)

    # Start executing task
    yield root_logger 
Example #28
Source File: args.py    From gitfs with Apache License 2.0 4 votes vote down vote up
def check_args(self, args):
        # check allow_other and allow_root
        if args.allow_other:
            args.allow_root = False
        else:
            args.allow_root = True

        # check log_level
        if args.debug:
            args.log_level = "debug"

        # setup logging
        if args.log != "syslog":
            if args.log in ("-", "/dev/stdout"):
                handler = StreamHandler(sys.stdout)
            else:
                handler = TimedRotatingFileHandler(args.log, when="midnight")
            handler.setFormatter(
                Formatter(
                    fmt="%(asctime)s %(threadName)s: " "%(message)s",
                    datefmt="%B-%d-%Y %H:%M:%S",
                )
            )
        else:
            if sys.platform == "darwin":
                handler = SysLogHandler(address="/var/run/syslog")
            else:
                handler = SysLogHandler(address="/dev/log")
            logger_fmt = (
                "GitFS on {mount_point} [%(process)d]: %(threadName)s: "
                "%(message)s".format(mount_point=args.mount_point)
            )
            handler.setFormatter(Formatter(fmt=logger_fmt))

        if args.sentry_dsn != "":
            from raven.conf import setup_logging
            from raven.handlers.logging import SentryHandler

            sentry_handler = SentryHandler(
                args.sentry_dsn,
                tags={
                    "owner": args.user,
                    "remote": args.remote_url,
                    "mountpoint": args.mount_point,
                },
            )
            sentry_handler.setLevel("ERROR")
            setup_logging(sentry_handler)
            log.addHandler(sentry_handler)

        handler.setLevel(args.log_level.upper())
        log.setLevel(args.log_level.upper())
        log.addHandler(handler)

        # set cache size
        lru_cache.maxsize = args.cache_size

        # return absolute repository's path
        args.repo_path = os.path.abspath(args.repo_path)

        return args 
Example #29
Source File: handlers.py    From pygogo with MIT License 4 votes vote down vote up
def syslog_hdlr(host="localhost", port=None, tcp=False, **kwargs):
    """A syslog log handler

    Args:
        host (string): The host name (default: localhost). Set to None to use
            the platform dependent domain socket.

        port (int): The port (default: `logging.handlers` default).

        tcp (bool): Create a TCP connection instead of UDP (default: False).

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

    Examples:
        >>> syslog_hdlr()  # doctest: +ELLIPSIS
        <...SysLogHandler...>
    """
    # http://stackoverflow.com/a/13874620/408556
    DEF_SOCKETS = {"linux2": "/dev/log", "darwin": "/var/run/syslog"}

    if tcp:
        def_port = hdlrs.SYSLOG_TCP_PORT
        socktype = socket.SOCK_STREAM
    else:
        def_port = hdlrs.SYSLOG_UDP_PORT
        socktype = socket.SOCK_DGRAM

    if kwargs.get("address"):
        address = kwargs["address"]
    elif host:
        address = (host, port or def_port)
    elif sys.platform in DEF_SOCKETS:
        address = DEF_SOCKETS[sys.platform]
    else:
        msg = "Domain socket location for {} is not supported."
        raise ValueError(msg.format(sys.platform))

    if kwargs.get("facility"):
        facility = kwargs["facility"]
    elif kwargs.get("local_num") and 8 > kwargs["local_num"] >= 0:
        # http://unix.stackexchange.com/a/146993
        value = "LOG_LOCAL{}".format(kwargs["facility"])
        facility = getattr(hdlrs.SysLogHandler, value)
    else:
        facility = hdlrs.SysLogHandler.LOG_USER

    return hdlrs.SysLogHandler(address, facility=facility, socktype=socktype)