本文整理汇总了Python中twisted.logger.Logger类的典型用法代码示例。如果您正苦于以下问题:Python Logger类的具体用法?Python Logger怎么用?Python Logger使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Logger类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: start_control_server
def start_control_server():
import argparse
from twisted.internet import reactor
from twisted.logger import Logger, globalLogPublisher, STDLibLogObserver
from cheesepi.server.control import (CheeseRPCServerFactory,
CheeseRPCServer)
from cheesepi.server.storage.mongo import MongoDAO
# Argument parsing
parser = argparse.ArgumentParser()
parser.add_argument('--port', type=int, default=18080,
help='Port to listen on')
args = parser.parse_args()
init_logging()
# Make twisted logging write to pythons logging module
globalLogPublisher.addObserver(STDLibLogObserver(name="cheesepi.server.control"))
# Use twisted logger when in twisted
log = Logger()
# Logging
#log = Logger()
#globalLogPublisher.addObserver(PrintingObserver())
#dao = MongoDAO()
dao = MongoDAO('localhost', 27017)
control_server = CheeseRPCServer(dao).getStreamFactory(CheeseRPCServerFactory)
reactor.listenTCP(args.port, control_server)
log.info("Starting control server on port %d..." % args.port)
reactor.run()
示例2: HouseStatus
class HouseStatus(Service):
'''
classdocs
'''
version = (1, 0)
serviceType = 'urn:schemas-upnp-org:service:HouseStatus:1'
serviceId = 'urn:schemas-upnp-org:serviceId:HouseStatus'
serviceUrl = 'house'
type = 'House'
subscription_timeout_range = (None, None)
def __init__(self, xmlfile, client, name='Application'):
'''
Constructor
'''
super(HouseStatus, self).__init__(
self.type, self.serviceType, xml=xmlfile,
client=client, appname=name)
self.log = Logger()
self.client = client
self.client.houses.append(self)
self.occupancystate = 'Indeterminate'
self.activitylevel = 'Regular'
self.dormancylevel = 'Regular'
def upnp_event(self, evt, var):
self.log.debug('away event: %s ==> %s' % (var, evt))
setattr(self, var, evt)
示例3: start_upload_server
def start_upload_server():
import argparse
from twisted.internet import reactor
from twisted.logger import Logger, globalLogPublisher, STDLibLogObserver
from twisted.web.server import Site
from twisted.web.resource import Resource
from cheesepi.server.upload import UploadHandler
# Argument parsing
parser = argparse.ArgumentParser()
parser.add_argument('--port', type=int, default=18090,
help='Port to listen on')
args = parser.parse_args()
init_logging()
# Make twisted logging write to pythons logging module
globalLogPublisher.addObserver(STDLibLogObserver(name="cheesepi.server.upload"))
# Use twisted logger when in twisted
log = Logger()
root = Resource()
root.putChild("upload", UploadHandler())
upload_server = Site(root)
reactor.listenTCP(args.port, upload_server)
log.info("Starting upload server on port %d..." % args.port)
reactor.run()
示例4: Volume
class Volume(Service):
version = (1, 0)
serviceType = "urn:av-openhome-org:service:Volume:1"
serviceId = "urn:av-openhome-org:serviceId:Volume"
serviceUrl = "Volume"
type = 'Volume'
subscription_timeout_range = (None, None)
def __init__(self, xmlfile, client, name='Application'):
super(Volume, self).__init__(
self.type, self.serviceType, xml=xmlfile,
client=client, appname=name)
self.log = Logger()
self.client = client
self.client.oh_eventVOLUME = self.upnp_event
self.volumemax = self.client.max_volume
self.volumeunity = 3
self.volume = self.volumemax
self.volumesteps = self.volumemax
self.volumemillidbperstep = 600
self.balancemax = 10
self.balance = 0
self.fademax = 10
self.fade = 0
self.mute = 0
def upnp_event(self, evt, var):
self.log.debug('volume event: %s ==> %s' % (var, evt))
setattr(self, var, evt)
示例5: TemperatureSensor
class TemperatureSensor(Service):
'''
classdocs
'''
version = (1, 0)
serviceType = 'urn:schemas-upnp-org:service:TemperatureSensor:1'
serviceId = 'urn:schemas-upnp-org:serviceId:TemperatureSensor'
serviceUrl = 'temp'
type = 'Temperature'
subscription_timeout_range = (None, None)
def __init__(self, xmlfile, client, name='Application', system=False):
'''
Constructor
'''
super(TemperatureSensor, self).__init__(
self.type, self.serviceType, xml=xmlfile,
client=client, appname=name)
self.log = Logger()
self.client = client
if system:
self.application = 'Outdoor'
else:
self.application = 'Room'
self.client.UPNP_Temp_event = self.upnp_event
self.currenttemperature = 2000
self.name = name
def upnp_event(self, evt, var):
self.log.debug('temp event: %s ==> %s' % (var, evt))
setattr(self, var, evt)
示例6: FanOperatingMode
class FanOperatingMode(Service):
'''
classdocs
'''
version = (1, 0)
serviceType = 'urn:schemas-upnp-org:service:HVAC_FanOperatingMode:1'
serviceId = 'urn:schemas-upnp-org:serviceId:HVAC_FanOperatingMode'
serviceUrl = 'fanmode'
type = 'FanOperating'
subscription_timeout_range = (None, None)
def __init__(self, xmlfile, client, name='Application', system=False):
'''
Constructor
'''
super(FanOperatingMode, self).__init__(
self.type, self.serviceType, xml=xmlfile,
client=client, appname=name)
self.log = Logger()
self.client = client
self.client.UPNP_fan_event = self.upnp_event
self.mode = 'ContinuousOn'
self.fanstatus = 'Off'
self.name = name
def upnp_event(self, evt, var):
self.log.debug('fan event: %s ==> %s' % (var, evt))
setattr(self, var, evt)
示例7: i2cProtocol
class i2cProtocol(LineOnlyReceiver):
def __init__(self):
self.log = Logger()
self.__funcs = {}
def connectionMade(self):
self.log.debug('i2c connected')
def lineReceived(self, line):
line = line.strip()
called = line[:9].lstrip('0')
onoff = bool(int(line[-1]))
try:
call = self.__funcs[called]
except:
return
else:
call(onoff)
def send_on(self):
self.transport.write(self.factory.on_msg)
def send_off(self):
self.transport.write(self.factory.off_msg)
def addCallback(self, name, func):
self.__funcs[name] = func
def remCallback(self, name):
try:
del self.__funcs[name]
except KeyError:
return
示例8: Demo_light_factory
class Demo_light_factory(ReconnectingClientFactory, Client):
def __init__(self, long_address=b'\x00\x00\x00\x00\x00\x00\xFF\xFF',
address=b'\xFF\xFE', pin=0,
api_level=1, net_type=None, stateless=True):
self.long_address = long_address
self.address = address
self._pin = pin
self.pin = 'dio-' + bytes(pin)
self.status = False
self.proto = None
self.log = Logger()
self.callback = self.receive
self.stateless = stateless
'''
Remote functions
'''
def r_set_target(self, value):
if value is not self.status:
if value is True:
self.proto.remote_at(dest_addr_long=self.long_address,
command=b'D%d' % self._pin,
parameter=b'\x05')
else:
self.proto.remote_at(dest_addr_long=self.long_address,
command=b'D%d' % self._pin,
parameter=b'\x04')
if self.stateless:
self.status = value
self.event(value, 'status')
def r_get_target(self):
return self.status
def r_get_status(self):
return self.status
def set_status(self, status):
if status is not self.status:
self.log.debug('%r --> %s' % (self.long_address,
'jour!' if status else 'nuit!'))
self.status = status
self.event(status, 'status')
def receive(self, data):
if 'samples' in data:
for sample in data['samples']:
if self.pin in sample:
self.set_status(sample[self.pin])
elif 'parameter' in data:
for sample in data['parameter']:
if self.pin in sample:
self.set_status(sample[self.pin])
示例9: LoggingProcessProtocol
class LoggingProcessProtocol(ProcessProtocol, object):
"""
A ProcessProtocol that logs all output to a file
"""
def __init__(self, commandname, maxbackups=3):
log_name = commandname + ".log"
log_dir = os.path.join(fs.adirs.user_log_dir, "processes")
if not os.path.isdir(log_dir):
os.makedirs(log_dir)
log_name = os.path.join(log_dir, log_name)
_backup_logs(log_name, maxbackups)
self.log = Logger(observer=textFileLogObserver(io.open(log_name, "w")),
namespace="")
super(LoggingProcessProtocol, self).__init__()
def connectionMade(self):
self.finished = defer.Deferred()
def outReceived(self, data):
self.log.info("{data}", data=bytes_to_str(data.strip()))
def errReceived(self, data):
self.log.error("{data}", data=bytes_to_str(data.strip()))
def processEnded(self, reason):
if reason.check(ProcessDone):
self.finished.callback(True)
self.log.info("Process finished without error")
else:
self.finished.errback(reason)
self.log.error("Process ended with error: {reason!r}",
reason=reason)
示例10: test_logger_namespace
def test_logger_namespace(self):
"""
A `twisted.logger.Logger` with a namespace gets that namespace as a prefix.
"""
fout = StringIO()
log = Logger(namespace="ns", observer=FileLogObserver(fout, formatForSystemd))
log.info("info\n{more}", more="info")
log.error("err")
self.assertEqual((
"<6>[ns] info\n"
"<6> info\n"
"<3>[ns] err\n"
), fout.getvalue())
示例11: __init__
def __init__(self, accessList):
self.logger = Logger(observer=textFileLogObserver(sys.stdout))
self.accessList = [nick.lower() for nick in accessList]
if not os.path.exists(self.magicFile):
self.logger.info("Creating magic file")
try:
with open(self.magicFile, "a"):
pass
except Exception as ex:
self.logger.error("Unable to create magic file! {0}".format(ex.message))
reactor.stop()
self.markovGenerator = pymarkov.MarkovChainGenerator(self.magicFile)
self.channels = []
self.channelPhrasers = {}
self.logger.debug("Discord initialized")
# Maybe add hook/plugin system here?
self.commands = Commands.Commands(self)
示例12: __init__
def __init__(self, reactor, bus_addr, addr, speed):
self.random = False
self.log = Logger()
self.reactor = reactor
self.bus_addr = bus_addr
self.pair = addr
self.speed = speed
self.running = False
示例13: Fake_HE_endpoint
class Fake_HE_endpoint(object):
bus = None
clients = {}
def __init__(self, reactor, bus_addr, addr, speed):
self.random = False
self.log = Logger()
self.reactor = reactor
self.bus_addr = bus_addr
self.pair = addr
self.speed = speed
self.running = False
def connect(self, clientFactory):
proto = clientFactory.proto
proto.transport = self
if clientFactory.addr not in self.clients:
self.clients.update({clientFactory.addr: proto})
if not self.bus:
r = task.LoopingCall(self.check)
r.start(20)
clientFactory.doStart()
return defer.succeed(None)
def check(self):
if not self.running:
for client in self.clients.values():
client.connectionMade()
self.running = True
self.bus = True
self.random = not self.random
l = '162342660' + str(int(self.random))
ll = '334455660' + str(int(not self.random))
if l[:-1] in self.clients:
self.clients[l[:-1]].lineReceived(l)
if ll[:-1] in self.clients:
self.clients[ll[:-1]].lineReceived(ll)
def write(self, msg):
t = []
if len(msg) < 11:
for n in msg:
t.append(ord(n))
else:
raise Exception('too much data')
self.log.debug('send %s to i2c link' % t)
示例14: test_logger_namespace_failure
def test_logger_namespace_failure(self):
"""
An unexpected failure, logged as critical, is displayed across multiple
lines.
"""
fout = StringIO()
log = Logger(namespace="ns", observer=FileLogObserver(fout, formatForSystemd))
log.failure("Something went wrong", Failure(Exception("1\n2\n3")))
self.assertEqual((
"<2>[ns] Something went wrong\n"
"<2> Traceback (most recent call last):\n"
"<2> Failure: builtins.Exception: 1\n"
"<2> 2\n"
"<2> 3\n"
), fout.getvalue())
示例15: __init__
def __init__(self, commandname, maxbackups=3):
log_name = commandname + ".log"
log_dir = os.path.join(fs.adirs.user_log_dir, "processes")
if not os.path.isdir(log_dir):
os.makedirs(log_dir)
log_name = os.path.join(log_dir, log_name)
_backup_logs(log_name, maxbackups)
self.log = Logger(observer=textFileLogObserver(io.open(log_name, "w")),
namespace="")
super(LoggingProcessProtocol, self).__init__()