• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python logger.Logger类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twisted.logger.Logger的典型用法代码示例。如果您正苦于以下问题:Python Logger类的具体用法?Python Logger怎么用?Python Logger使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Logger类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()
开发者ID:haf,项目名称:cheesepi,代码行数:35,代码来源:utils.py


示例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)
开发者ID:bverdu,项目名称:onDemand,代码行数:28,代码来源:house_status.py


示例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()
开发者ID:haf,项目名称:cheesepi,代码行数:31,代码来源:utils.py


示例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)
开发者ID:bverdu,项目名称:onDemand,代码行数:29,代码来源:ohvolume.py


示例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)
开发者ID:bverdu,项目名称:onDemand,代码行数:31,代码来源:temperature_sensor.py


示例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)
开发者ID:lazytech-org,项目名称:onDemand,代码行数:28,代码来源:hvac_fan_operating_mode.py


示例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
开发者ID:bverdu,项目名称:onDemand,代码行数:34,代码来源:i2c.py


示例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])
开发者ID:bverdu,项目名称:onDemand,代码行数:57,代码来源:demo_light.py


示例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)
开发者ID:DefaultUser,项目名称:PyTIBot,代码行数:32,代码来源:async_process.py


示例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())
开发者ID:twm,项目名称:yarrharr,代码行数:15,代码来源:test_application.py


示例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)		
开发者ID:TunnelBlanket,项目名称:Discord,代码行数:26,代码来源:Discord.py


示例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
开发者ID:bverdu,项目名称:onDemand,代码行数:8,代码来源:i2c.py


示例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)
开发者ID:bverdu,项目名称:onDemand,代码行数:46,代码来源:i2c.py


示例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())
开发者ID:twm,项目名称:yarrharr,代码行数:17,代码来源:test_application.py


示例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__()
开发者ID:DefaultUser,项目名称:PyTIBot,代码行数:10,代码来源:async_process.py


示例16: __init__

 def __init__(self):
     """
     doc
     """
     self.log = Logger()
     self.delimiter = "\n"
     self.deferreds = []
     self.buff = {}
     self.idle = False
     self.list_index = 0
开发者ID:bverdu,项目名称:onDemand,代码行数:10,代码来源:mpd.py


示例17: test_log_converter

def test_log_converter(handler, framework):
    pytest.importorskip("twisted.logger")
    # this checks that we can convert a plain Twisted Logger calling
    # failure() into a traceback on our observers.
    from twisted.logger import Logger
    from txaio.tx import _LogObserver

    out = six.StringIO()
    observer = _LogObserver(out)
    logger = Logger(observer=observer)

    try:
        raise RuntimeError("failed on purpose")
    except:
        logger.failure(None)

    output = out.getvalue()
    assert "failed on purpose" in output
    assert "Traceback" in output
开发者ID:koobs,项目名称:txaio,代码行数:19,代码来源:test_logging.py


示例18: __init__

 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):
     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
开发者ID:bverdu,项目名称:onDemand,代码行数:11,代码来源:demo_switch.py


示例19: _relaying_test

    def _relaying_test(self, eliot_logger, observer):
        """
        Publish an event using ``twisted.logger`` with ``observer`` hooked up and
        assert that the event ends up being seen by ``eliot_logger``.
        """
        twisted_logger = TwistedLogger(observer=observer)
        twisted_logger.info("Hello, world.")

        [event] = eliot_logger.messages
        self.assertThat(
            event,
            ContainsDict(dict(
                # A couple things from the Twisted side of the fence.
                log_namespace=Equals("lae_util.test.test_eliot"),
                log_format=Equals("Hello, world."),
                # And also some Eliot stuff.
                task_uuid=IsInstance(unicode),
                task_level=IsInstance(list),
            )),
        )
开发者ID:LeastAuthority,项目名称:leastauthority.com,代码行数:20,代码来源:test_eliot.py


示例20: __init__

 def __init__(self, sid, callback, timeout):
     self.log = Logger()
     self.sid = sid
     self.callback_addr = callback
     self.timeout = timeout
     self.last_subscribe = time.time()
     self.next_notify_key = 0
     self.expired = False  # subscription has been flagged for deletion
     self.agent = Agent(reactor)
     self.pending_events = {}
     self.pending = False
开发者ID:lazytech-org,项目名称:onDemand,代码行数:11,代码来源:event.py



注:本文中的twisted.logger.Logger类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python globalLogBeginner.beginLoggingTo函数代码示例发布时间:2022-05-27
下一篇:
Python logger.formatEvent函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap