Python logger.exception() Examples

The following are 15 code examples of logger.exception(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module logger , or try the search function .
Example #1
Source File: db_helper.py    From ns4_chatbot with Apache License 2.0 7 votes vote down vote up
def init(config):
	try:
		global __connection_pool
		__connection_pool = PooledDB(
				creator=MySQLdb,
				mincached=1,
				maxcached=20,
				host=config.db_host,
				port=config.db_port,
				user=config.db_user,
				passwd=config.db_pass,
				db=config.db_database,
				use_unicode=False,
				charset="utf8",
				cursorclass=DictCursor)

		return True
	except Exception as e:
		logger.exception(e,"Mysql数据库初始化失败:host=%s,user=%s,pass=%s,db=%s",config.db_host,config.db_user,config.db_pass,config.db_database)
		return False 
Example #2
Source File: appetite_core.py    From appetite with Apache License 2.0 6 votes vote down vote up
def from_object(self, obj):
        """Populate application from object"""
        loaded_obj = obj

        if isinstance(obj, str):
            try:
                loaded_obj = json.loads(obj)
            except Exception as exception:
                logger.exception("Problem loading json apps object", exception,
                                 err_message=exception.message,
                                 trace=json.dumps(traceback.format_exc()))
                sys.exit(1)

        for key, value in loaded_obj.items():
            self.__dict__[key] = value

        if self.commit_log:
            for key, value in consts.RENAME_COMMIT_LOG_KEYS.items():
                if key in self.commit_log:
                    self.commit_log[value] = self.commit_log.pop(key, None)

        return self 
Example #3
Source File: web_client.py    From ns4_chatbot with Apache License 2.0 6 votes vote down vote up
def send(apiUrl,data,method=None):
    logger.debug("调用内部系统[%s],data[%r]",apiUrl,data)
    try:
        data_json = json.dumps(data)
        headers = {'Content-Type': 'application/json'} # 设置数据为json格式,很重要
        request = urllib2.Request(url=apiUrl, headers=headers, data=data_json)
        if method is not None:
            request.get_method = method

        response = urllib2.urlopen(request)
        result = {'code':response.getcode(),'content':response.read()}
        logger.debug("调用[%s]返回结果:%r",apiUrl,result)
        return result
    except Exception as e:
        #traceback.print_stack()
        logger.exception(e,"调用内部系统[%s],data[%r],发生错误[%r]", apiUrl, data,e)
        return None 
Example #4
Source File: _dns.py    From admin4 with Apache License 2.0 6 votes vote down vote up
def ReadStatistics(self):
    if not self.server.settings.get('statsport'):
      return None
    try:
      response=requests.get("http://%s:%d" % (self.server.settings['host'], self.server.settings['statsport']), timeout=self.server.settings.get('timeout', 1.))
      response.raise_for_status()
      txt=response.text
    except Exception as _e:
      return None

    try:
      root=xmltree.fromstring(txt)
    except Exception as _e:
      import logger, adm, time
      fname="%s/xml-%s_%s.xml" % (adm.loaddir, self.server.settings['host'], time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())))
      logger.exception("Error parsing BIND response %s", fname)
      f=open(fname, "w")
      f.write(txt)
      f.close() 
      return None
    return root 
Example #5
Source File: notification_handler.py    From Tautulli with GNU General Public License v3.0 6 votes vote down vote up
def process_queue():
    queue = plexpy.NOTIFY_QUEUE
    while True:
        params = queue.get()
        
        if params is None:
            break
        elif params:
            try:
                if 'newsletter' in params:
                    notify_newsletter(**params)
                elif 'notification' in params:
                    notify(**params)
                else:
                    add_notifier_each(**params)
            except Exception as e:
                logger.exception("Tautulli NotificationHandler :: Notification thread exception: %s" % e)

        queue.task_done()

    logger.info("Tautulli NotificationHandler :: Notification thread exiting...") 
Example #6
Source File: helpers.py    From appetite with Apache License 2.0 5 votes vote down vote up
def create_path(path, is_dir=False):
    """Create Path"""
    try:
        split_path = path if is_dir else os.path.split(path)[0]
        if not os.path.exists(split_path):
            os.makedirs(split_path)
    except Exception as e:
        logger.exception("Problem creating folder", e, path=path)
        return False
    return True 
Example #7
Source File: helpers.py    From appetite with Apache License 2.0 5 votes vote down vote up
def delete_path(path):
    """Delete path including content"""
    try:
        if os.path.exists(path):
            shutil.rmtree(path)
    except Exception as e:
        logger.exception("Problem deleting folder", e, path=path)
        return False
    return True 
Example #8
Source File: data_provider.py    From lighttrack with MIT License 5 votes vote down vote up
def _aggregate_batch(data_holder, use_list=False):
        size = len(data_holder[0])
        result = []
        for k in range(size):
            if use_list:
                result.append(
                    [x[k] for x in data_holder])
            else:
                dt = data_holder[0][k]
                if type(dt) in [int, bool]:
                    tp = 'int32'
                elif type(dt) == float:
                    tp = 'float32'
                else:
                    try:
                        tp = dt.dtype
                    except AttributeError:
                        raise TypeError("Unsupported type to batch: {}".format(type(dt)))
                try:
                    result.append(
                        np.asarray([x[k] for x in data_holder], dtype=tp))
                except Exception as e:  # noqa
                    logger.exception("Cannot batch data. Perhaps they are of inconsistent shape?")
                    if isinstance(dt, np.ndarray):
                        s = pprint.pformat([x[k].shape for x in data_holder])
                        logger.error("Shape of all arrays to be batched: " + s)
                    try:
                        # open an ipython shell if possible
                        import IPython as IP; IP.embed()    # noqa
                    except ImportError:
                        pass
        return result 
Example #9
Source File: common.py    From ns4_chatbot with Apache License 2.0 5 votes vote down vote up
def send_sms(content,mobile_num = None):
    # logger.debug("调用内部系统[%s],data[%r]",apiUrl,data)

    try:

        data = {"merchId": config.sms_merchId,
                "orderId": config.sms_orderId,
                "smsTypeNo": config.sms_smsTypeNo,
                "mobile": config.admin_mobile,
                "stp_content": str(content)}
        data_urlencode = urllib.urlencode(data)
        request = urllib2.Request(url=config.sms_server, data=data_urlencode)
        response = urllib2.urlopen(request,timeout=3)
        result = {'code': response.getcode(), 'content':json.loads(response.read())}
        if result['content']['retCode'] == '0000':
            logger.info("短信发送成功")
        else:
            logger.info("短信发送失败:状态[%s],原因[%s]",result['content']['retCode'],result['content']['retInfo'])
        # 返回'content' 的内容
        # {
        #     "retCode": "0000",
        #     "retInfo": "提交成功",
        #     "data": {}
        # }
        return result['content']
    except Exception as e:
        #这里不能用logger.error或者logger.exception,否则,容易形成死循环
        logger.info("短信发送失败:content=%s",content)
        logger.info("短信失败原因:%s", str(e))
        return None 
Example #10
Source File: Update.py    From admin4 with Apache License 2.0 5 votes vote down vote up
def run(self):
    update=OnlineUpdate()
    if update.IsValid():
      adm.updateInfo=update
      if update.UpdateAvailable():
        wx.CallAfter(self.frame.OnUpdate)
    elif update.exception:
      wx.CallAfter(wx.MessageBox,
                   xlt("Connection error while trying to retrieve update information from the update server.\nCheck network connectivity and proxy settings!"), 
                   xlt("Communication error"), wx.ICON_EXCLAMATION) 
Example #11
Source File: Update.py    From admin4 with Apache License 2.0 5 votes vote down vote up
def __init__(self):
    self.info=None
    self.message=None
    self.exception=None
    
    if not Crypto:
      self.message=xlt("No Crypto lib available.")
      return
    modsUsed={}
    for server in adm.config.getServers():
      mod=server.split('/')[0]
      modsUsed[mod] = modsUsed.get(mod, 0) +1
      
    try:
      info = "?ver=%s&rev=%s&mods=%s" % (admVersion.version, admVersion.revDate.replace(' ', '_'), ",".join(modsUsed.keys()))
      response=HttpGet("https://www.admin4.org/update.xml%s" % info)
      xmlText=response.text
      sigres=HttpGet("https://www.admin4.org/update.sign")
      signature=sigres.content
      
    except Exception as ex:
      self.exception = ex
      self.message=xlt("Online update check failed.\n\nError reported:\n  %s") % str(ex)
      return

    if True: # we want to check the signature
      f=open(os.path.join(adm.loaddir, 'admin4.pubkey'))
      keyBytes=f.read()
      f.close()

      # https://www.dlitz.net/software/pycrypto/api/current/Crypto-module.html
      pubkey=Crypto.PublicKey.RSA.importKey(keyBytes)
      verifier = Crypto.Signature.PKCS1_v1_5.new(pubkey)
      hash=Crypto.Hash.SHA.new(xmlText)

      if not verifier.verify(hash, signature):
        self.message = xlt("Online update check failed:\nupdate.xml cryptographic signature not valid.")
        return
    
    self.info=XmlDocument.parse(xmlText)
    adm.config.Write('LastUpdateCheck', time.time()) 
Example #12
Source File: Update.py    From admin4 with Apache License 2.0 5 votes vote down vote up
def DoInstall(self, tmpDir, source):
    if not os.path.isdir(source):
      try:
        zip=zipfile.ZipFile(source)
        zipDir=zip.namelist()[0]
        zip.extractall(tmpDir)
        zip.close()
      except Exception as _e:
        self.ModuleInfo = xlt("Error extracting\n%s") % source
        logger.exception("Error extracting %s", source)
        return False

      source = os.path.join(tmpDir, zipDir)

    if self.modname == "Core":
      destination=adm.loaddir
    else:
      destination=os.path.join(adm.loaddir, self.modid)
      
    copytree(source, destination)
    try: shutil.rmtree(tmpDir)
    except: pass
    
    if self.modname == "Core":
      try:
        # Make start file executable for unpackaged files
        startFile=sys.argv[0] # usually admin4.py
        st=os.stat(startFile)
        os.chmod(startFile, st.st_mode | stat.S_IXUSR|stat.S_IXGRP|stat.S_IXOTH)
      except: pass
    return True 
Example #13
Source File: data_provider.py    From video-to-pose3D with MIT License 5 votes vote down vote up
def _aggregate_batch(data_holder, use_list=False):
        size = len(data_holder[0])
        result = []
        for k in range(size):
            if use_list:
                result.append(
                    [x[k] for x in data_holder])
            else:
                dt = data_holder[0][k]
                if type(dt) in [int, bool]:
                    tp = 'int32'
                elif type(dt) == float:
                    tp = 'float32'
                else:
                    try:
                        tp = dt.dtype
                    except AttributeError:
                        raise TypeError("Unsupported type to batch: {}".format(type(dt)))
                try:
                    result.append(
                        np.asarray([x[k] for x in data_holder], dtype=tp))
                except Exception as e:  # noqa
                    logger.exception("Cannot batch data. Perhaps they are of inconsistent shape?")
                    if isinstance(dt, np.ndarray):
                        s = pprint.pformat([x[k].shape for x in data_holder])
                        logger.error("Shape of all arrays to be batched: " + s)
                    try:
                        # open an ipython shell if possible
                        import IPython as IP; IP.embed()    # noqa
                    except ImportError:
                        pass
        return result 
Example #14
Source File: common.py    From ns4_chatbot with Apache License 2.0 4 votes vote down vote up
def send_email(email,subject,content,attach_file_path=None):

    if not email: email = config.admin_email

    msg = MIMEMultipart()
    msg['Subject'] = subject
    msg['From'] = config.email_user
    msg['To'] = email

    to_users = email.split(',')

    # 构造文字内容
    text_plain = MIMEText(content, 'plain', 'utf-8')
    msg.attach(text_plain)

    # jpg类型附件
    if attach_file_path is not None:
        part = MIMEApplication(open(attach_file_path, 'rb').read())
        part.add_header('Content-Disposition', 'attachment', filename=attach_file_path)
        msg.attach(part)

    try:

        if config.email_SSL:
            s = smtplib.SMTP_SSL(config.email_server, config.email_port)  # 邮件服务器及端口号
        else:
            s = smtplib.SMTP(config.email_server, config.email_port)  # 邮件服务器及端口号
        s.login(config.email_user, config.email_passwd)
        s.sendmail(config.email_user,to_users, msg.as_string())
        logger.debug("邮件发送完毕:title=%s,content=%s", subject, content)
        s.quit()
        return True
    except Exception as e:
        #这里不能用logger.error或者logger.exception,否则,容易形成死循环
        logger.info("邮件发送失败:title=%s,content=%s",subject,content)
        logger.info("邮件失败原因:%s", str(e))
        logger.info("邮件配置信息:server=%s,user=%s,pass=%s,to=%s",
                    config.email_server,
                    config.email_user,
                    config.email_passwd,
                    config.admin_email)
        return False 
Example #15
Source File: web_socket.py    From Tautulli with GNU General Public License v3.0 4 votes vote down vote up
def process(opcode, data):
    if opcode not in opcode_data:
        return False

    try:
        data = data.decode('utf-8')
        logger.websocket_debug(data)
        info = json.loads(data)
    except Exception as e:
        logger.warn("Tautulli WebSocket :: Error decoding message from websocket: %s" % e)
        logger.websocket_error(data)
        return False

    info = info.get('NotificationContainer', info)
    info_type = info.get('type')

    if not info_type:
        return False

    if info_type == 'playing':
        time_line = info.get('PlaySessionStateNotification', info.get('_children', {}))

        if not time_line:
            logger.debug("Tautulli WebSocket :: Session found but unable to get timeline data.")
            return False

        try:
            activity = activity_handler.ActivityHandler(timeline=time_line[0])
            activity.process()
        except Exception as e:
            logger.exception("Tautulli WebSocket :: Failed to process session data: %s." % e)

    if info_type == 'timeline':
        time_line = info.get('TimelineEntry', info.get('_children', {}))

        if not time_line:
            logger.debug("Tautulli WebSocket :: Timeline event found but unable to get timeline data.")
            return False

        try:
            activity = activity_handler.TimelineHandler(timeline=time_line[0])
            activity.process()
        except Exception as e:
            logger.exception("Tautulli WebSocket :: Failed to process timeline data: %s." % e)

    return True