def serve(self, port: int = 5000, n_process: int = None): if n_process is None: n_process = 1 if sys.platform == 'win32' else 8 fmt = LogFormatter(fmt='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', color=True) root_logger = logging.getLogger() console_handler = logging.StreamHandler() file_handler = logging.FileHandler('server.log') console_handler.setFormatter(fmt) file_handler.setFormatter(fmt) root_logger.addHandler(console_handler) root_logger.addHandler(file_handler) app_log.setLevel(logging.INFO) gen_log.setLevel(logging.INFO) access_log.setLevel(logging.INFO) app_log.info("Model is loading...") app_log.info("Model Has Been Loaded!") app = Application([(r"/.*", LTPHandler, dict(ltp=self))]) server = HTTPServer(app) server.bind(port) server.start(n_process) ioloop.IOLoop.instance().start()
def main(): #sys.argv.append('--log_file_prefix=./test.log') #sys.argv.append('--log_file_num_backups=4') #sys.argv.append('--log_file_max_size=16777216') #16M parse_command_line() gen_log.setLevel(logging.INFO) gen_log.info('http_test start ...,listen on port:%d'%options.port) set_manager.location = options.store_path settings = dict( debug = options.debug ) app = tornado.web.Application([ (r"/testsets/", http_test_handler.TestSetsHandler), (r"/testsets/([0-9]+)", http_test_handler.SetHandler), (r"/testsets/(.+)/interface/([0-9]*)", http_test_handler.SetInterfaceHandler), ], **settings, ) app.listen(options.port) set_manager.init() tornado.ioloop.IOLoop.current().start()
def server_thread(): from tornado.log import access_log, app_log, gen_log access_log.setLevel(logging.ERROR) app_log.setLevel(logging.ERROR) gen_log.setLevel(logging.ERROR) loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) set_ioloop(tornado.ioloop.IOLoop.current()) # to enable bokeh app port = 0 if os.environ.get("PYWEBIO_SCRIPT_MODE_PORT"): port = int(os.environ.get("PYWEBIO_SCRIPT_MODE_PORT")) server, port = _setup_server(webio_handler=SingleSessionWSHandler, port=port, host='localhost') tornado.ioloop.IOLoop.current().spawn_callback( partial(wait_to_stop_loop, server=server)) if "PYWEBIO_SCRIPT_MODE_PORT" not in os.environ: tornado.ioloop.IOLoop.current().spawn_callback( open_webbrowser_on_server_started, 'localhost', port) tornado.ioloop.IOLoop.current().start() logger.debug('Tornado server exit')
def init_logger(cls, port): formatter = LogFormatter(fmt=cls.__fmt.format(port=port), datefmt="", color=False) access_log_handler = ConcurrentRotatingFileHandler( filename=os.path.join(ServerConfig["log_dir"], "access.log")) access_log_handler.setFormatter(formatter) access_log.addHandler(access_log_handler) server_log_handler = ConcurrentRotatingFileHandler( filename=os.path.join(ServerConfig['log_dir'], 'server.log'), maxBytes=128 * 1024 * 1024, backupCount=5, encoding='utf8') server_log_handler.setFormatter(formatter) gen_log.addHandler(server_log_handler) app_log.addHandler(server_log_handler) access_log.setLevel(logging.INFO) gen_log.setLevel(getattr(logging, ServerConfig['log_level'].upper())) app_log.setLevel(getattr(logging, ServerConfig['log_level'].upper())) access_log.propagate = app_log.propagate = gen_log.propagate = False return
def configure(path, uid=None): """Configures the tornado logging streams with application specific customizatons, including configuring the application to log to the specified directory. Throws: OSError -- if the given directory doesn't exist and cannot be created, or if it exists but cannot be written to Args: path -- a directory to create and write logs to Keyword Args: uid -- If provided, the uid that should own the current, non-rotated version of each log is owned by the given system user. This is useful if we plan on dropping down to a less privilaged user on application run """ # First, create the specified logging directory if it does not already # exist. If we don't have permissions to create the directory, # then OSError will be thrown if not os.path.isdir(path): os.mkdir(path) # Next, make sure that the current process has the needed permissions # to write to the specified logging directory. If not, throw an # exception, to prevent log-less execution if not os.access(path, os.W_OK | os.X_OK): error = "Unable to write to logging directory {0}".format("path") raise OSError(error) # Otherwise, if we're sure we can write to the specified logging # directory, configure the built in tornado loggers to use that # directory instead of the system wide one format = "%(created)f|%(message)s" tornado_logs = (('access.log', access_log), ('application.log', app_log), ('general.log', gen_log)) for log_name, logger in tornado_logs: log_path = os.path.join(path, log_name) handler = TimedRotatingFileHandler(log_path, when="midnight") formatter = logging.Formatter(format) handler.setFormatter(formatter) logger.addHandler(handler) # Allow application errors to propogate up, so that serious errors # can wind up on STDERR or other useful places if logger is not app_log: logger.propagate = False if uid: os.chown(log_path, uid, -1) tornado.log.enable_pretty_logging() # Finally, write a simple start up message, both to test that we're # able to write as expected, and to get a start time in the logs gen_log.setLevel(logging.INFO) gen_log.info("Starting webserver (pid:{0}).".format(os.getpid()))
def set_tornado_log(): handler = logging.StreamHandler(sys.stdout) handler.setFormatter(formatter) gen_log.addHandler(handler) gen_log.setLevel(logging.INFO) access_log.addHandler(handler) access_log.setLevel(logging.INFO) app_log.addHandler(handler) access_log.setLevel(logging.INFO)
def main(): parse_command_line() gen_log.setLevel(logging.INFO) gen_log.info('long poll start ...,listen on port:%d' % options.port) settings = dict(debug=options.debug) app = tornado.web.Application( [ (r"/longpoll/(.+)/message", channel_handler.MessageHandler), (r"/longpoll/", channel_handler.CreateChannelHandler), (r"/longpoll/(.+)", channel_handler.SessionHandler), ], **settings, ) app.listen(options.port) channel_manager.start_period_check() tornado.ioloop.IOLoop.current().start()
def main(): parse_command_line() handlers = find_all_handlers("handlers") settings = get_settings() # Enable debug log. # Tornado set the log level to INFO default. if settings.get("debug", False): gen_log.setLevel("DEBUG") pprint.pprint(handlers) pprint.pprint(settings) app = Application(handlers, **settings) server = HTTPServer(app) server.bind(PORT, HOST) print("Server run at " + HOST + ":" + str(PORT)) server.start(1) IOLoop.current().start()
def enable_tornado_log(): """开启 Tornado 内置日志信息 * ``tornado.access``: Per-request logging for Tornado's HTTP servers (and potentially other servers in the future) * ``tornado.application``: Logging of errors from application code (i.e. uncaught exceptions from callbacks) * ``tornado.general``: General-purpose logging, including any errors or warnings from Tornado itself. """ try: access_log.addHandler(filehandler) access_log.setLevel(logger.level) app_log.addHandler(filehandler) app_log.setLevel(logger.level) gen_log.addHandler(filehandler) gen_log.setLevel(logger.level) except Exception: error_msg = traceback.format_exc() logger.warning(f'enable tornado log fail.\t{error_msg}') logger.error(f'enable tornado log fail.')
# if message[:6] == 'init|<': # c = RunCommand(handler=self, tag='start', command="start") # c.run() # Here we're starting the server after having initialized it. # See also below. if __name__ == "__main__": #rp5lk# # See DummyHandler above. # Create a primary postgres database on startup (in dev only) # c = RunCommand(handler=DummyHandler(), tag='init', command="init_primary -1") # c.run() # Set up Tornado logging gen_log.setLevel(DEBUG) # create formatter and add it to the handlers formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') ch = logging.StreamHandler() ch.setFormatter(formatter) gen_log.addHandler(ch) # add the handlers to the logger # Define a tornado application application = tornado.web.Application([ (r"/pgnode", MainHandler), ]) lib_dir = '/certs' # Listen on 0.0.0.0:8888. We'll handle addr & port mapping. application.listen(8888, "0.0.0.0", ssl_options=dict(
from server.class_calander import ClassTime from server.handlers import handlers from server.setting import project_dir, term_start_date from server.tools import set_logger_to_file define("port", default=5000, help="run on the given port", type=int) dev = bool(os.environ.get('DEV')) if __name__ == "__main__": tornado.options.parse_command_line() ClassTime.set_startday(term_start_date.year, term_start_date.month, term_start_date.day) if not dev: # 线上环境配置 access_log.disabled = True log_file = '%s/../app-%s.log' % (project_dir, options.port) set_logger_to_file(app_log, filename=log_file) set_logger_to_file(gen_log, filename=log_file) else: access_log.setLevel(logging.DEBUG) app_log.setLevel(logging.DEBUG) gen_log.setLevel(logging.DEBUG) logging.info('Dev environment') app = tornado.web.Application(handlers=handlers, debug=dev) http_server = tornado.httpserver.HTTPServer(app, xheaders=True) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()