我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用tornado.log()。
def _get_master_secret(self, passphrase, salt, time, backup_file=None, encrypt_master_secret=True): """Restore/generate master secret. Restore from backup_file if such is provided, generate new otherwise. Set backup_file=None for in memory master_secret. """ if not backup_file: log.info('Master Secret Share not backed up to file') return self._generate_master_secret(), time if not os.path.exists(backup_file): log.info('Master Secret backup file doesn\'t exists. Generate new.') master_secret = self._generate_master_secret() backup_master_secret( master_secret, encrypt_master_secret, passphrase, salt, backup_file, time, self.rng) return master_secret, time log.info('Restore Master Secret Share from file') return self._restore_master_secret( backup_file, encrypt_master_secret, passphrase, salt)
def _get_certivox_server_secret_share(self, expires): method = options.certivoxServerSecret methods = { 'dta': self._get_certivox_server_secret_share_dta, 'credentials.json': self._get_certivox_server_secret_share_credentials, 'manual': lambda x: raw_input('MIRACL server secret share:'), 'config': lambda x: options.certivoxServerSecret } func = methods[method if method in methods else 'config'] certivox_server_secret_hex = func(expires) try: return certivox_server_secret_hex.decode("hex") except TypeError as e: log.error(e) raise SecretsError('Invalid CertiVox server secret share')
def on_pong(self, timestamp): """ Records the latency of clients (from the server's perspective) via a log message. .. note:: This is the ``pong`` specified in the WebSocket protocol itself. The `pong` method is a Gate One-specific implementation. """ self.latency_count += 1 latency = int(time.time() * 1000) - int(timestamp) if latency < 0: return # Something went wrong; skip this one self.timestamps.append(latency) if len(self.timestamps) > 10: self.timestamps.pop(0) self.latency = sum(self.timestamps)/len(self.timestamps) if self.latency_count > 12: # Only log once a minute self.latency_count = 0 #self.logger.info(_("WebSocket Latency: {0}ms").format(self.latency))
def _generate_master_secret(self): """Generate the M-Pin Master Secret.""" try: return crypto.mpin_random_generate(self.rng) except crypto.CryptoError as e: log.error(e) raise SecretsError('M-Pin Master Secret Generation Failed')
def get_server_secret(self): """Generate server secret.""" try: return crypto.get_server_secret(self.master_secret) except crypto.CryptoError as e: log.error(e) raise SecretsError('Server Secret generation failed')
def get_client_secret(self, mpin_id): """Generate client secret.""" try: return crypto.get_client_multiple(self.master_secret, mpin_id) except crypto.CryptoError as e: log.error(e) raise SecretsError('Client secret generation failed')
def get_time_permits(self, mpin_id, count): """Generate client time permit.""" start_date = crypto.today() try: return dict( (date, crypto.get_time_permit(self.master_secret, mpin_id, date)) for date in range(start_date, start_date + count)) except crypto.CryptoError as e: log.error(e) raise SecretsError('M-Pin Time Permit Generation Failed')
def _get_server_secret(self): expires = Time.syncedISO(seconds=SIGNATURE_EXPIRES_OFFSET_SECONDS) certivox_server_secret = self._get_certivox_server_secret_share(expires) customer_server_secret = self._get_customer_server_secret_share(expires) try: server_secret_hex = crypto.mpin_recombine_g2(certivox_server_secret, customer_server_secret) except crypto.CryptoError as e: log.error(e) raise SecretsError('M-Pin Server Secret Generation Failed') return server_secret_hex.decode("hex")
def get_pass1_value(self): """Return pass1 value.""" try: random_number = crypto.mpin_random_generate(self.rng) except crypto.CryptoError as e: log.error(e) raise SecretsError('Pass 1 - failed to generate Y') return random_number.encode('hex')
def cleanup_old_sessions(): """ Cleans up old session directories inside the `session_dir`. Any directories found that are older than the `auth_timeout` (global gateone setting) will be removed. The modification time is what will be checked. """ logging.debug("cleanup_old_sessions()") disabled = timedelta(0) # If the user sets auth_timeout to "0" session_dir = define_options()['session_dir'] #settings = get_settings(options.settings_dir) settings = get_settings(define_options()['settings_dir']) expiration_str = settings['*']['gateone'].get('auth_timeout', "14d") expiration = convert_to_timedelta(expiration_str) if expiration != disabled: #for session in os.listdir(options.session_dir): for session in os.listdir(session_dir): # If it's in the SESSIONS dict it's still valid for sure if session not in SESSIONS: if len(session) != 45: # Sessions are always 45 characters long. This check allows # us to skip the 'broadcast' file which also lives in the # session_dir. Why not just check for 'broacast'? Just in # case we put something else there in the future. continue #session_path = os.path.join(options.session_dir, session) session_path = os.path.join(session_dir, session) mtime = time.localtime(os.stat(session_path).st_mtime) # Convert to a datetime object for easier comparison mtime = datetime.fromtimestamp(time.mktime(mtime)) if datetime.now() - mtime > expiration: import shutil from applications.utils import kill_session_processes # The log is older than expiration, remove it and kill any # processes that may be remaining. kill_session_processes(session) logger.info(_( "Removing old session files due to age (>%s old): %s" % (expiration_str, session_path))) shutil.rmtree(session_path, ignore_errors=True)
def start(self, run_loop=True): self.log.info("BinderHub starting on port %i", self.port) self.http_server = self.tornado_app.listen(self.port) if run_loop: tornado.ioloop.IOLoop.current().start()
def main(): hdlf = logging.FileHandler('../log.log') hdlf.setFormatter(tornado.log.LogFormatter()) logging.getLogger().addHandler(hdlf) tornado.options.parse_command_line() http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(options.port) tornado.ioloop.IOLoop.current().start()
def _get_customer_server_secret_share(self, expires): path = 'serverSecret' url_params = url_concat( '{0}/{1}'.format(options.DTALocalURL, path), { 'app_id': self.app_id, 'expires': expires, 'signature': signMessage('{0}{1}{2}'.format(path, self.app_id, expires), self.app_key) }) log.debug('customer server secret request: {0}'.format(url_params)) httpclient = tornado.httpclient.HTTPClient() import socket # Make at most 30 attempts to get server secret from local TA for attempt in range(30): try: response = httpclient.fetch(url_params) except (tornado.httpclient.HTTPError, socket.error) as e: log.error(e) log.error( 'Unable to get Server Secret from the customer TA server. ' 'Retying...') time.sleep(2) continue httpclient.close() break else: # Max attempts reached raise SecretsError( 'Unable to get Server Secret from the customer TA server.') try: data = json.loads(response.body) except ValueError: raise SecretsError('TA server response contains invalid JSON') if 'serverSecret' not in data: raise SecretsError('serverSecret not in response from TA server') return data["serverSecret"].decode("hex")
def cleanup_user_logs(): """ Cleans up all user logs (everything in the user's 'logs' directory and subdirectories that ends in 'log') older than the `user_logs_max_age` setting. The log directory is assumed to be: *user_dir*/<user>/logs ...where *user_dir* is whatever Gate One happens to have configured for that particular setting. """ logging.debug("cleanup_user_logs()") disabled = timedelta(0) # If the user sets user_logs_max_age to "0" #settings = get_settings(options.settings_dir) settings = get_settings(define_options()['settings_dir']) user_dir = settings['*']['gateone']['user_dir'] #if 'user_dir' in options: # NOTE: options is global #user_dir = options.user_dir default = "30d" max_age_str = settings['*']['gateone'].get('user_logs_max_age', default) #if 'user_logs_max_age' in list(options): #max_age_str = options.user_logs_max_age max_age = convert_to_timedelta(max_age_str) def descend(path): """ Descends *path* removing logs it finds older than `max_age` and calls :func:`descend` on any directories. """ for fname in os.listdir(path): log_path = os.path.join(path, fname) if os.path.isdir(log_path): descend(log_path) continue if not log_path.endswith('log'): continue mtime = time.localtime(os.stat(log_path).st_mtime) # Convert to a datetime object for easier comparison mtime = datetime.fromtimestamp(time.mktime(mtime)) if datetime.now() - mtime > max_age: # The log is older than max_age, remove it logger.info(_("Removing log due to age (>%s old): %s" % ( max_age_str, log_path))) os.remove(log_path) if max_age != disabled: for user in os.listdir(user_dir): logs_path = os.path.abspath(os.path.join(user_dir, user, 'logs')) if not os.path.exists(logs_path): # Nothing to do continue descend(logs_path)
def log_message(self, log_obj): """ Attached to the `go:log` WebSocket action; logs the given *log_obj* via :meth:`ApplicationWebSocket.client_log`. The *log_obj* should be a dict (JSON object, really) in the following format:: { "level": "info", # Optional "message": "Actual log message here" } If a "level" is not given the "info" level will be used. *Supported Levels:* "info", "error", "warning", "debug", "fatal", "critical". .. note:: The "critical" and "fatal" log levels both use the `logging.Logger.critical` method. """ if not self.current_user: return # Don't let unauthenticated users log messages. # NOTE: We're not using the authenticated() check here so we don't # end up logging a zillion error messages when an unauthenticated # user's client has debug logging enabled. if "message" not in log_obj: return # Nothing to do log_obj["level"] = log_obj.get("level", "info") # Default to "info" loggers = { "info": self.client_log.info, "warning": self.client_log.warning, "error": self.client_log.error, "debug": self.client_log.debug, "fatal": self.client_log.critical, # Python doesn't use "fatal" "critical": self.client_log.critical, } if isinstance(log_obj["message"], bytes): log_msg = log_obj["message"] else: log_msg = log_obj["message"].encode('utf-8') loggers[log_obj["level"].lower()]( "Client Logging: {0}".format(log_msg))