本文整理汇总了Python中logging.handlers.WatchedFileHandler.setFormatter方法的典型用法代码示例。如果您正苦于以下问题:Python WatchedFileHandler.setFormatter方法的具体用法?Python WatchedFileHandler.setFormatter怎么用?Python WatchedFileHandler.setFormatter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类logging.handlers.WatchedFileHandler
的用法示例。
在下文中一共展示了WatchedFileHandler.setFormatter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def main():
# Set up our log level
try:
filename = config['server.logging_filename']
handler = WatchedFileHandler(filename)
except KeyError:
handler = StreamHandler()
handler.setFormatter(logging.Formatter(config['server.logging_format']))
root_logger = logging.getLogger('')
root_logger.setLevel(int(config['server.logging_level']))
root_logger.addHandler(handler)
settings = {
}
if 'debug' in config:
log.info('Enabling Tornado Web debug mode')
settings['debug'] = config['debug']
host = config['server.socket_host']
port = int(config['server.socket_port'])
application = tornado.web.Application([
(r"/event", EventHandler),
], **settings)
if config.get('dry-run'):
log.info('In dry-run mode')
log.info('Starting corgi server http://%s:%d/' % (host, port))
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(port, host)
tornado.ioloop.IOLoop.instance().start()
示例2: __init__
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def __init__(self, name):
self.name = name
self.plugins.register(self.name, self)
self._methods = {}
self.debug = bool('DEBUG-%s' % self.name in get_vim_buffers_names())
self.log = logging.getLogger(self.name)
self.log.setLevel(logging.DEBUG if self.debug else logging.INFO)
self.settings.option('LOG_PATH', default=None)
if self.settings['LOG_PATH']:
if not os.path.exists(self.settings['LOG_PATH']):
os.makedirs(self.settings['LOG_PATH'])
log_file_name = '%s.log' % os.path.join(self.settings['LOG_PATH'],
self.name)
handler = WatchedFileHandler(log_file_name, 'w')
else:
handler = logging.FileHandler('/dev/null')
fm = logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s',
'%H:%M:%S'
)
handler.setFormatter(fm)
self.log.addHandler(handler)
self.log.debug('Plugin name: %r', self.name)
示例3: getLogger
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def getLogger(name, level=logging.INFO, handlers=[]):
logger = logging.getLogger(name)
if len(handlers) != 0:
logger.setLevel(level)
if "console" in handlers:
strm = StreamHandler()
fmt = logging.Formatter('%(message)s')
strm.setLevel(level)
strm.setFormatter(fmt)
logger.addHandler(strm)
if "file" in handlers:
conf = handlers['file']
fl = WatchedFileHandler(conf['logfile'])
fl.setLevel(level)
fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fl.setFormatter(fmt)
logger.addHandler(fl)
if "syslog" in handlers:
sysl = SysLogHandler(address='/dev/log', facility=SysLogHandler.LOG_SYSLOG)
sysl.setLevel(level)
formatter = logging.Formatter('%(name)s[' + str(os.getpid()) + '] %(levelname)-8s: %(message)s')
sysl.setFormatter(formatter)
logger.addHandler(sysl)
return logger
示例4: __init__
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def __init__(self, application):
self.application = application
log_file = WatchedFileHandler(settings.API_LOG)
log_format = logging.Formatter(LOGFORMAT, DATEFORMAT)
log_file.setFormatter(log_format)
api_logger.setLevel(logging.DEBUG)
api_logger.addHandler(log_file)
示例5: get_logger
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def get_logger(logname, logfile, loglevel, propagate):
"""Create and return a logger object."""
stream_handlers = {
'STDOUT': sys.stdout,
'STDERR': sys.stderr,
}
try:
if logfile in stream_handlers:
logger_handler = logging.StreamHandler(stream_handlers[logfile])
else:
logger_handler = WatchedFileHandler(logfile)
except (PermissionError, FileNotFoundError) as err: # pytype: disable=name-error
print(err)
sys.exit(-1)
logger = logging.getLogger(logname)
log_fmt = '%(asctime)s %(name)-6s %(levelname)-8s %(message)s'
logger_handler.setFormatter(
logging.Formatter(log_fmt, '%b %d %H:%M:%S'))
logger.addHandler(logger_handler)
logger.propagate = propagate
logger.setLevel(loglevel)
return logger
示例6: _logger
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def _logger(level, out_stream, name=None, log_file=None,
log_file_level=logging.DEBUG, milliseconds=False):
"""Create the actual logger instance, logging at the given level
if name is None, it will get args[0] without the extension (e.g. gina).
'out_stream must be passed, the recommended value is sys.stderr'
"""
if name is None:
# Determine the logger name from the script name
name = sys.argv[0]
name = re.sub('.py[oc]?$', '', name)
# We install our custom handlers and formatters on the root logger.
# This means that if the root logger is used, we still get correct
# formatting. The root logger should probably not be used.
root_logger = logging.getLogger()
# reset state of root logger
reset_root_logger()
# Make it print output in a standard format, suitable for
# both command line tools and cron jobs (command line tools often end
# up being run from inside cron, so this is a good thing).
hdlr = logging.StreamHandler(out_stream)
# We set the level on the handler rather than the logger, so other
# handlers with different levels can be added for things like debug
# logs.
root_logger.setLevel(0)
hdlr.setLevel(level)
if milliseconds:
# Python default datefmt includes milliseconds.
formatter = LaunchpadFormatter(datefmt=None)
else:
# Launchpad default datefmt does not include milliseconds.
formatter = LaunchpadFormatter()
hdlr.setFormatter(formatter)
root_logger.addHandler(hdlr)
# Add an optional aditional log file.
if log_file is not None:
handler = WatchedFileHandler(log_file, encoding="UTF8")
handler.setFormatter(formatter)
handler.setLevel(log_file_level)
root_logger.addHandler(handler)
# Create our logger
logger = logging.getLogger(name)
# Set the global log
log._log = logger
# Inform the user the extra log file is in operation.
if log_file is not None:
log.info(
"Logging %s and higher messages to %s" % (
logging.getLevelName(log_file_level), log_file))
return logger
示例7: main
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def main(args):
log = logging.getLogger("addisonarches.web")
log.setLevel(args.log_level)
formatter = logging.Formatter(
"%(asctime)s %(levelname)-7s %(name)s|%(message)s")
ch = logging.StreamHandler()
if args.log_path is None:
ch.setLevel(args.log_level)
else:
fh = WatchedFileHandler(args.log_path)
fh.setLevel(args.log_level)
fh.setFormatter(formatter)
log.addHandler(fh)
ch.setLevel(logging.WARNING)
ch.setFormatter(formatter)
log.addHandler(ch)
loop = asyncio.SelectorEventLoop()
asyncio.set_event_loop(loop)
down = asyncio.Queue(loop=loop)
up = asyncio.Queue(loop=loop)
#TODO: Read service name from CLI
service = "dev" # Cf qa, demo, prod, etc
tok = token(args.connect, service, APP_NAME)
node = create_udp_node(loop, tok, down, up)
loop.create_task(node(token=tok))
app = aiohttp.web.Application()
assets = Assets(app, **vars(args))
reg = Registration(app, tok, down, up, **vars(args))
transitions = Transitions(app, **vars(args))
work = Workflow(app, tok, down, up, **vars(args))
for svc in (assets, reg, transitions, work):
log.info("{0.__class__.__name__} object serves {1}".format(
svc, ", ".join(svc.routes.keys())))
handler = app.make_handler()
f = loop.create_server(handler, args.host, args.port)
srv = loop.run_until_complete(f)
log.info("Serving on {0[0]}:{0[1]}".format(srv.sockets[0].getsockname()))
try:
loop.run_forever()
except KeyboardInterrupt:
pass
finally:
loop.run_until_complete(handler.finish_connections(1.0))
srv.close()
loop.run_until_complete(srv.wait_closed())
loop.run_until_complete(app.finish())
loop.close()
示例8: getDaemonLogger
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def getDaemonLogger(filePath, log_format=None, loglevel=logging.INFO):
logger = logging.getLogger()
logger.setLevel(loglevel)
try:
watchedHandler = WatchedFileHandler(filePath)
except Exception as e: # pylint: disable=broad-except
return e, None
watchedHandler.setFormatter(logging.Formatter(log_format or '%(asctime)s %(msg)s'))
logger.addHandler(watchedHandler)
return logger, watchedHandler
示例9: main
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def main():
if len(sys.argv) < 5:
usage(f = sys.stderr)
sys.exit(-1)
http_ip = sys.argv[1]
http_port = int(sys.argv[2])
socksip = sys.argv[3]
socksport = int(sys.argv[4])
opts, _ = getopt.gnu_getopt(sys.argv[5:], "hdp:l:",
["help", "debug", "pidfile=", "logfile="])
for o, a in opts:
if o == "-h" or o == "--help":
usage()
sys.exit()
if o == "-d" or o == "--debug":
options.logginglevel = logging.DEBUG
elif o == "-p" or o == "--pidfile":
options.daemonize = True
options.pidfile = a
elif o == "-l" or o == "--logfile":
options.daemonize = True
options.logfile = a
if options.daemonize:
pid = os.fork()
if pid != 0:
# write pidfile by father
f = open(options.pidfile, "w")
print >> f, pid
f.close()
sys.exit(0)
if options.daemonize:
logger = logging.getLogger()
logger.setLevel(options.logginglevel)
ch = WatchedFileHandler(options.logfile)
ch.setFormatter(logging.Formatter('[%(asctime)s][%(name)s][%(levelname)s] - %(message)s'))
logger.addHandler(ch)
else:
logging.basicConfig(
format='[%(asctime)s][%(name)s][%(levelname)s] - %(message)s',
datefmt='%Y-%d-%m %H:%M:%S',
level=options.logginglevel,
)
socks = SocksServer(socksip, socksport, SocksRelayFactory(), timeout=30, maxclient=500)
socks.start()
globalvars.socksip = socksip
globalvars.socksport = socksport
globalvars.sockstimeout = 60
WSGIServer((http_ip, http_port), meek_server_application, log=None).serve_forever()
示例10: main
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def main():
parser = argparse.ArgumentParser(description="Send out broker notifications")
parser.add_argument("-c", "--config", dest="config",
help="location of the broker configuration file")
parser.add_argument("--one_shot", action="store_true",
help="do just a single run and then exit")
parser.add_argument("--debug", action="store_true",
help="turn on debug logs on stderr")
opts = parser.parse_args()
config = Config(configfile=opts.config)
# These modules must be imported after the configuration has been
# initialized
from aquilon.aqdb.db_factory import DbFactory
db = DbFactory()
if opts.debug:
level = logging.DEBUG
logging.basicConfig(level=level, stream=sys.stderr,
format='%(asctime)s [%(levelname)s] %(message)s')
else:
level = logging.INFO
logfile = os.path.join(config.get("broker", "logdir"), "aq_notifyd.log")
handler = WatchedFileHandler(logfile)
handler.setLevel(level)
formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s')
handler.setFormatter(formatter)
rootlog = logging.getLogger()
rootlog.addHandler(handler)
rootlog.setLevel(level)
# Apply configured log settings
for logname, level in config.items("logging"):
if level not in logging._levelNames:
continue
logging.getLogger(logname).setLevel(logging._levelNames[level])
logger = logging.getLogger("aq_notifyd")
if opts.one_shot:
update_index_and_notify(config, logger, db)
else:
signal.signal(signal.SIGTERM, exit_handler)
signal.signal(signal.SIGINT, exit_handler)
run_loop(config, logger, db)
示例11: make_api_logger
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def make_api_logger():
"""Make logger for REST API writes logs to the file
"""
# Circular import dependency problem
# we import logger module in settings
from nailgun.settings import settings
logger = logging.getLogger("nailgun-api")
log_file = WatchedFileHandler(settings.API_LOG)
log_file.setFormatter(formatter)
logger.setLevel(logging.DEBUG)
logger.addHandler(log_file)
return logger
示例12: configure_logger
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def configure_logger(self):
logger = logging.getLogger(self.name)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(levelname)s %(asctime)s %(message)s')
logname = self.logname if hasattr(self, 'logname') else '{}.log'.format(self.name)
handler = WatchedFileHandler('{}/{}'.format(self.logging_folder, logname))
handler.setFormatter(formatter)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
return logger
示例13: main
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def main(args):
log = logging.getLogger(APP_NAME)
log.setLevel(args.log_level)
formatter = logging.Formatter(
"%(asctime)s %(levelname)-7s %(name)s|%(message)s")
ch = logging.StreamHandler()
if args.log_path is None:
ch.setLevel(args.log_level)
else:
fh = WatchedFileHandler(args.log_path)
fh.setLevel(args.log_level)
fh.setFormatter(formatter)
log.addHandler(fh)
ch.setLevel(logging.WARNING)
ch.setFormatter(formatter)
log.addHandler(ch)
loop = asyncio.SelectorEventLoop()
asyncio.set_event_loop(loop)
down = asyncio.Queue(loop=loop)
up = asyncio.Queue(loop=loop)
tok = token(args.connect, APP_NAME)
node = create_udp_node(loop, tok, down, up)
loop.create_task(node(token=tok))
loop.create_task(queue_logger(loop, up))
msg = parcel(
tok,
Alert(datetime.datetime.now(), "Hello World!"),
via=Address(tok.namespace, tok.user, tok.service, turberfield.ipc.demo.router.APP_NAME)
)
log.info("Sending message: {}".format(msg))
loop.call_soon_threadsafe(functools.partial(down.put_nowait, msg))
try:
loop.run_forever()
except KeyboardInterrupt:
for task in asyncio.Task.all_tasks(loop=loop):
task.cancel()
for resource in resources:
resource.close()
finally:
loop.close()
示例14: configure_logging
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def configure_logging(loglevel, logfile=None):
loglevel = loglevel.upper()
loglevels = ('DEBUG', 'INFO', 'WARNING', 'ERROR')
if loglevel not in loglevels:
raise Exception('Loglevel must be one of {}'.format(loglevels))
logger.setLevel(getattr(logging, loglevel))
if logfile:
handler = WatchedFileHandler(logfile)
else:
handler = StreamHandler()
handler.setFormatter(
logging.Formatter('[%(asctime)s] %(levelname)s - %(message)s',
'%m-%d %H:%M:%S'))
logger.addHandler(handler)
示例15: __init__
# 需要导入模块: from logging.handlers import WatchedFileHandler [as 别名]
# 或者: from logging.handlers.WatchedFileHandler import setFormatter [as 别名]
def __init__(self, name, level=None):
formatter = logging.Formatter(FORMAT)
logging.Logger.__init__(self, name,
logging.getLevelName(yagi.config.get('logging', 'default_level')))
handlers = []
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
handlers.append(stream_handler)
logfile = yagi.config.get('logging', 'logfile')
if logfile:
file_handler = WatchedFileHandler(filename=logfile)
file_handler.setFormatter(formatter)
handlers.append(file_handler)
for handler in handlers:
logging.Logger.addHandler(self, handler)