本文整理汇总了Python中logging.handlers.SysLogHandler方法的典型用法代码示例。如果您正苦于以下问题:Python handlers.SysLogHandler方法的具体用法?Python handlers.SysLogHandler怎么用?Python handlers.SysLogHandler使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类logging.handlers
的用法示例。
在下文中一共展示了handlers.SysLogHandler方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_logger
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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
示例2: _setup_logging
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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
示例3: __init__
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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)
示例4: setup_logging
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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)
示例5: initLogger
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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)
示例6: __init__
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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
示例7: main
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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)
示例8: __init__
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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)
示例9: init_app
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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)
示例10: __init__
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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)
示例11: setup_logging
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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
示例12: setup_logging
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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)
示例13: init_app
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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)
示例14: init
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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)
示例15: get_logger
# 需要导入模块: from logging import handlers [as 别名]
# 或者: from logging.handlers import SysLogHandler [as 别名]
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