本文整理汇总了Python中logging.handlers方法的典型用法代码示例。如果您正苦于以下问题:Python logging.handlers方法的具体用法?Python logging.handlers怎么用?Python logging.handlers使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类logging
的用法示例。
在下文中一共展示了logging.handlers方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _EventLogUpload
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
def _EventLogUpload(self, source_log: Text):
"""Upload the log file contents to the local EventLog."""
event_handler = logging.handlers.NTEventLogHandler('GlazierBuildLog')
logger = logging.Logger('eventlogger')
logger.addHandler(event_handler)
logger.setLevel(logging.DEBUG)
try:
with open(source_log, 'r') as f:
content = f.readlines()
for line in content:
logger.info(line)
except IOError:
raise LogCopyError(
'Unable to open log file. It will not be imported into '
'the Windows Event Log.')
示例2: _handle_existing_loggers
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
def _handle_existing_loggers(existing, child_loggers, disable_existing):
"""
When (re)configuring logging, handle loggers which were in the previous
configuration but are not in the new configuration. There's no point
deleting them as other threads may continue to hold references to them;
and by disabling them, you stop them doing any logging.
However, don't disable children of named loggers, as that's probably not
what was intended by the user. Also, allow existing loggers to NOT be
disabled if disable_existing is false.
"""
root = logging.root
for log in existing:
logger = root.manager.loggerDict[log]
if log in child_loggers:
logger.level = logging.NOTSET
logger.handlers = []
logger.propagate = True
else:
logger.disabled = disable_existing
示例3: init_app
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
def init_app(cls, app):
Config.init_app(app)
# email errors to the administrators
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.CIRCULATE_MAIL_SENDER,
toaddrs=[cls.CIRCULATE_ADMIN],
subject=cls.CIRCULATE_MAIL_SUBJECT_PREFIX + ' Application Error',
credentials=credentials,
secure=secure)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
示例4: setupLogging
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
def setupLogging(self):
logger = logging.getLogger()
formatter = logging.Formatter('%(asctime)s [%(levelname)-8s] %(message)s')
path = userpath('logs', 'leaguedirector.log')
handler = logging.handlers.RotatingFileHandler(path, backupCount=20)
try:
handler.doRollover()
except Exception: pass
handler.setFormatter(formatter)
logger.addHandler(handler)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logging.info('Started League Director (%s)', leaguedirector.__version__)
qInstallMessageHandler(self.handleMessage)
示例5: setup_logger
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
def setup_logger(name, level=logging.INFO, maxBytes=25000000, backupCount=5, format=SHORT_FORMAT):
""" Set up a logging instance.
@param name: The log file name.
We recommend "$action_name$_modalert".
@param level: The logging level.
@param maxBytes: The maximum log file size before rollover.
@param backupCount: The number of log files to retain.
@return logger: Returns an instance of logger
"""
logfile = make_splunkhome_path(['var', 'log', 'splunk', name + '.log'])
logger = logging.getLogger(name)
logger.setLevel(level)
logger.propagate = False # Prevent the log messages from being duplicated in the python.log file
# Prevent re-adding handlers to the logger object, which can cause duplicate log lines.
handler_exists = any([True for h in logger.handlers if h.baseFilename == logfile])
if not handler_exists:
file_handler = logging.handlers.RotatingFileHandler(logfile, maxBytes=maxBytes, backupCount=backupCount)
formatter = logging.Formatter(format)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger
示例6: logger
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
def logger():
logger = logging.getLogger('testlog')
logHandler = TimedRotatingFileHandler(filename="logfile", when="midnight")
logFormatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
logHandler.setFormatter(logFormatter)
if not logger.handlers:
streamhandler = logging.StreamHandler()
streamhandler.setLevel(logging.ERROR)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(message)s')
streamhandler.setFormatter(formatter)
logger.addHandler(streamhandler)
logger.addHandler(logHandler)
# logger.error(message)
return logger
示例7: colorize_status
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
def colorize_status(text: Optional[Union[str, int]], status: Optional[Union[str, int, bool]] = False) -> str:
if status is False:
status = text
status_code = str(status) if status else None
if status_code and not logging.getLogger('transport.http').handlers:
output_text = str(text) if text else ''
color = None
if status_code == '101':
color = colorama.Fore.CYAN
elif status_code[0] == '2':
color = colorama.Fore.GREEN
elif status_code[0] == '3' or status_code == '499':
color = colorama.Fore.YELLOW
elif status_code[0] == '4':
color = colorama.Fore.RED
elif status_code[0] == '5':
color = colorama.Fore.WHITE + colorama.Back.RED
if color:
return '{}{}{}'.format(color, output_text, colorama.Style.RESET_ALL)
return output_text
return str(text) if text else ''
示例8: common_logger_config
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
def common_logger_config(self, logger, config, incremental=False):
"""
Perform configuration which is common to root and non-root loggers.
"""
level = config.get('level', None)
if level is not None:
logger.setLevel(_checkLevel(level))
if not incremental:
# Remove any existing handlers
for h in logger.handlers[:]:
logger.removeHandler(h)
handlers = config.get('handlers', None)
if handlers:
self.add_handlers(logger, handlers)
filters = config.get('filters', None)
if filters:
self.add_filters(logger, filters)
示例9: init_app
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
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_SENDER,
toaddrs=[cls.ADMINMAIL],
subject=cls.MAIL_SUBJECT_PREFIX + ' Application Error',
credentials=credentials,
secure=secure)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
示例10: configure
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
def configure(self, args):
""" Configure the loggers with the appropriate log level etc.
:param args: The arguments from the command line
:type args: list
"""
log_level = self._determine_log_level(args)
log_level_config = self.console_log_configs[log_level]
root_logger = logging.getLogger()
cli_logger = logging.getLogger(CLI_LOGGER_NAME)
# Set the levels of the loggers to lowest level.
# Handlers can override by choosing a higher level.
root_logger.setLevel(logging.DEBUG)
cli_logger.setLevel(logging.DEBUG)
cli_logger.propagate = False
if root_logger.handlers and cli_logger.handlers:
# loggers already configured
return
self._init_console_handlers(root_logger, cli_logger, log_level_config)
if self.file_log_enabled:
self._init_logfile_handlers(root_logger, cli_logger)
get_logger(__name__).debug("File logging enabled - writing logs to '%s'.", self.log_dir)
示例11: add_handler
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
def add_handler(cls, level, fmt, colorful, **kwargs):
"""Add a configured handlers to the global logger."""
global g_logger
if isinstance(level, str):
level = getattr(logging, level.upper(), logging.INFO)
handler = cls(**kwargs)
handler.setLevel(level)
if colorful:
formatter = ColoredFormatter(fmt)
else:
formatter = logging.Formatter(fmt)
handler.setFormatter(formatter)
g_logger.addHandler(handler)
return handler
示例12: init_app
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
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.FLASHCARD_MAIL_SENDER,
toaddrs=[cls.FLASHCARD_ADMIN],
subject=cls.FLASHCARD_MAIL_SUBJECT_PREFIX + 'Application Error',
credentials=credentials,
secure=secure)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
示例13: get_logger
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
def get_logger(cls, name, level='INFO', filepath=None, fmt=None):
'''
Return a new logger or an existing one, if any.
:param cls : The class as implicit first argument.
:param name : Return a logger with the specified name.
:param filepath: Path of the file, where logs will be saved. If it is not set,
redirects the log stream to `sys.stdout`.
:param fmt : A format string for the message as a whole, as well as a format
string for the date/time portion of the message.
Default: '%(asctime)s %(levelname)-8s %(name)-34s %(message)s'
:rtype : :class:`logging.Logger`
'''
logger = logging.getLogger(name)
# .............................if logger already exists, return it
if logger.handlers: return logger
if filepath:
# .........................rotate log file (1 rotation per 512KB
handler = RotatingFileHandler(filepath, maxBytes=524288, backupCount=8)
else:
handler = logging.StreamHandler(sys.stdout)
fmt = fmt or '%(asctime)s %(levelname)-8s %(name)-34s %(message)s'
handler.setFormatter(logging.Formatter(fmt))
try:
logger.setLevel(getattr(logging, level.upper() if level else 'INFO'))
except: logger.setLevel(logging.INFO)
logger.addHandler(handler)
return logger
示例14: handler_datapath
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
def handler_datapath(self, ev):
ryudp = ev.dp
dp = self.dps[ryudp.id]
# Set up a thread to poll for port stats
# TODO: set up threads to poll for other stats as well
# TODO: allow the different things to be polled for to be
# configurable
dp.running = True
if dp.dp_id not in self.pollers:
self.pollers[dp.dp_id] = {}
self.handlers[dp.dp_id] = {}
if dp.influxdb_stats:
port_state_handler = GaugePortStateInfluxDBLogger(
dp, ryudp, self.logname)
else:
port_state_handler = GaugePortStateLogger(
dp, ryudp, self.logname)
self.handlers[dp.dp_id]['port_state'] = port_state_handler
if dp.monitor_ports:
if dp.influxdb_stats:
port_stats_poller = GaugePortStatsInfluxDBPoller(
dp, ryudp, self.logname)
else:
port_stats_poller = GaugePortStatsPoller(
dp, ryudp, self.logname)
self.pollers[dp.dp_id]['port_stats'] = port_stats_poller
port_stats_poller.start()
if dp.monitor_flow_table:
if dp.influxdb_stats:
flow_table_poller = GaugeFlowTableInfluxDBPoller(
dp, ryudp, self.logname)
else:
flow_table_poller = GaugeFlowTablePoller(
dp, ryudp, self.logname)
self.pollers[dp.dp_id]['flow_table'] = flow_table_poller
flow_table_poller.start()
示例15: port_status_handler
# 需要导入模块: import logging [as 别名]
# 或者: from logging import handlers [as 别名]
def port_status_handler(self, ev):
rcv_time = time.time()
dp = self.dps[ev.msg.datapath.id]
self.handlers[dp.dp_id]['port_state'].update(rcv_time, ev.msg)