def get_logger(): LOG_ROOT = os.path.join(sys._MEIPASS, "logs") if getattr( sys, 'frozen', False) else './logs' formatter = logging.Formatter( "[%(asctime)s.%(msecs)03d] %(levelname)s [%(thread)d] - %(message)s", "%Y-%m-%d %H:%M:%S") info_handler = RotatingFileHandler(f'{LOG_ROOT}/info.log', backupCount=0) error_handler = RotatingFileHandler(f'{LOG_ROOT}/error.log', backupCount=0) logging.getLogger().setLevel(logging.NOTSET) _logger.addHandler(info_handler) _logger.addHandler(error_handler) info_handler.setFormatter(formatter) error_handler.setFormatter(formatter) return _logger
# custom log formatter class OneLineExceptionFormatter(logging.Formatter): def formatException(self, exc_info): result = super(OneLineExceptionFormatter, self).formatException(exc_info) return repr(result) # or format into one line however you want to def format(self, record): s = super(OneLineExceptionFormatter, self).format(record) if record.exc_text: s = s.replace('\n', '') + '|' return s # defining log levels # LOG_LEVEL = logging.ERROR # Configuring Logs # db_logger = logging.getLogger() # db_logger.setLevel(LOG_LEVEL) # add database handler handler = SQLALCHAMYHandler() # db_logger.addHandler(handler) gunicorn_logger = logging.getLogger("gunicorn.error") fastapi_logger.setLevel(gunicorn_logger.level) # add database handler fastapi_logger.addHandler(handler)
lw = LoggerWrapper() logger = logging.getLogger(LOGGER_MAIN_NAME) logger = lw.set_logger( logger=logger, log_ex=SETTING_CONTAINER.settings_local['LOGGER_FILE'], verbose=False, log_level=SETTING_CONTAINER.settings_local['LOG_LEVEL'], console=False, ) uvicorn_access_logger = logging.getLogger('uvicorn.access') add_hnd = lw.create_tech_handler( log_file=SETTING_CONTAINER.settings_local['LTECH_FILE'], log_level=SETTING_CONTAINER.settings_local['LTECH_LEVEL'], ) uvicorn_access_logger.addHandler(add_hnd) fastapi_logger.addHandler(add_hnd) if __name__ != 'main': fastapi_logger.setLevel(add_hnd.level) uvicorn_access_logger.setLevel(add_hnd.level) else: fastapi_logger.setLevel(logging.DEBUG) uvicorn_access_logger.setLevel(logging.INFO) logger.info("Server started at {}".format(datetime.now())) # ---- routers section app = FastAPI( title=SETTING_CONTAINER.settings['API_TITLE'], description=SETTING_CONTAINER.settings['API_DESCRIPTION'], version=SETTING_CONTAINER.settings['API_MAIN_VERSION'],
from starlette.middleware.base import RequestResponseEndpoint from starlette.requests import Request from .libs.database import client as db from .libs.logging import JsonFormatter from .routers import router DB_HOST = os.environ["DB_HOST"] DB_USER = os.environ["DB_USER"] DB_PASSWORD = os.environ["DB_PASSWORD"] DB_NAME = os.environ["DB_NAME"] APP_LOG_LEVEL = os.getenv("APP_LOG_LEVEL", "INFO") handler = logging.StreamHandler() handler.setFormatter(JsonFormatter()) logger.addHandler(handler) logger.setLevel(APP_LOG_LEVEL) app = FastAPI() app.include_router(router, prefix="/v1") @app.on_event("startup") async def db_startup() -> None: await db.init( host=DB_HOST, user=DB_USER, password=DB_PASSWORD, db=DB_NAME, ) logger.info("DB client successfully connected.")
app = FastAPI() app.add_websocket_route("/ws/{token}", websocket.EndPoint) app.add_websocket_route("/ws-battle", websocket.BattleEndPoint) app.add_middleware( CORSMiddleware, allow_origins=["*"], # FIXME for production allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) fh = logging.FileHandler('log.log') logger.addHandler(fh) connections = ''#websocket.Connections() logger.info(f'Object ID - {id(connections)}') class VkLaunchParams(BaseModel): vk_user_id: int vk_app_id: int vk_is_app_user: bool vk_are_notifications_enabled: bool vk_language: str vk_ref: str vk_access_token_settings: str async def token_auth(x_auth: str = Header(None)):