-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: unified log formats of application and uvicorn (#85)
- Loading branch information
Showing
2 changed files
with
41 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
import logging | ||
import sys | ||
|
||
from uvicorn.logging import DefaultFormatter | ||
|
||
logger = logging.getLogger("app") | ||
|
||
|
||
def configure_loggers(): | ||
# Delegate uvicorn logs to the root logger | ||
# to achieve uniform log formatting | ||
for name, log in logging.getLogger().manager.loggerDict.items(): | ||
if isinstance(log, logging.Logger) and name.startswith("uvicorn"): | ||
log.handlers = [] | ||
log.propagate = True | ||
|
||
# Setting up log levels | ||
logger.setLevel(logging.DEBUG) | ||
|
||
# Configuring the root logger | ||
root = logging.getLogger() | ||
root.setLevel(logging.INFO) | ||
|
||
root_has_stderr_handler = any( | ||
isinstance(handler, logging.StreamHandler) | ||
and handler.stream == sys.stderr | ||
for handler in root.handlers | ||
) | ||
|
||
# Do not override the existing stderr handlers | ||
# if they are already configured | ||
if not root_has_stderr_handler: | ||
formatter = DefaultFormatter( | ||
fmt="%(asctime)s [%(levelname)s] - %(message)s" | ||
) | ||
|
||
handler = logging.StreamHandler(sys.stderr) | ||
handler.setFormatter(formatter) | ||
root.addHandler(handler) |