Skip to content

Commit 64c5ae2

Browse files
feat: Drop loguru and use builtin logging (#1133)
* Configure simple builtin logging Changed the 2 existing `print` in the `private_gpt` code base into actual python logging, stop using loguru (dependency will be dropped in a later commit). Try to use the `key=value` logging convention in logs (to indicate what dynamic values represents, and what is dynamic vs not). Using `%s` log style, so that the string formatting is pushed inside the logger, giving the ability to the logger to determine if the string need to be formatted or not (i.e. strings from debug logs might not be formatted if the log level is not debug) The (basic) builtin log configuration have been placed in `private_gpt/__init__.py` in order to initialize the logging system even before we start to launch any python code in `private_gpt` package (ensuring we get any initialization log formatted as we want to) Disabled `uvicorn` custom logging format, resulting in having uvicorn logs being outputted in our formatted. Some more concise format could be used if we want to, especially: ``` COMPACT_LOG_FORMAT = '%(asctime)s.%(msecs)03d [%(levelname)s] %(name)s - %(message)s' ``` Python documentation and cookbook on logging for reference: * https://docs.python.org/3/library/logging.html * https://docs.python.org/3/howto/logging.html * Removing loguru from the dependencies Result of `poetry remove loguru` * PR feedback: using `logger` variable name instead of `log` --------- Co-authored-by: Louis Melchior <louis@jaris.io>
1 parent 24cfddd commit 64c5ae2

File tree

7 files changed

+23
-54
lines changed

7 files changed

+23
-54
lines changed

poetry.lock

+1-33
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

private_gpt/__init__.py

+10
Original file line numberDiff line numberDiff line change
@@ -1 +1,11 @@
11
"""private-gpt."""
2+
import logging
3+
4+
# Set to 'DEBUG' to have extensive logging turned on, even for libraries
5+
ROOT_LOG_LEVEL = "INFO"
6+
7+
PRETTY_LOG_FORMAT = (
8+
"%(asctime)s.%(msecs)03d [%(levelname)-8s] %(name)+25s - %(message)s"
9+
)
10+
logging.basicConfig(level=ROOT_LOG_LEVEL, format=PRETTY_LOG_FORMAT, datefmt="%H:%M:%S")
11+
logging.captureWarnings(True)

private_gpt/__main__.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,7 @@
55
from private_gpt.main import app
66
from private_gpt.settings.settings import settings
77

8-
uvicorn.run(app, host="0.0.0.0", port=settings.server.port)
8+
# Set log_config=None to do not use the uvicorn logging configuration, and
9+
# use ours instead. For reference, see below:
10+
# https://github.com/tiangolo/fastapi/discussions/7457#discussioncomment-5141108
11+
uvicorn.run(app, host="0.0.0.0", port=settings.server.port, log_config=None)

private_gpt/components/llm/custom/sagemaker.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import io
55
import json
6+
import logging
67
from typing import TYPE_CHECKING, Any
78

89
import boto3 # type: ignore
@@ -26,6 +27,8 @@
2627
CompletionResponseGen,
2728
)
2829

30+
logger = logging.getLogger(__name__)
31+
2932

3033
class LineIterator:
3134
r"""A helper class for parsing the byte stream input from TGI container.
@@ -81,7 +84,7 @@ def __next__(self) -> Any:
8184
continue
8285
raise
8386
if "PayloadPart" not in chunk:
84-
print("Unknown event type:" + chunk)
87+
logger.warning("Unknown event type=%s", chunk)
8588
continue
8689
self.buffer.seek(0, io.SEEK_END)
8790
self.buffer.write(chunk["PayloadPart"]["Bytes"])

private_gpt/main.py

-17
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
"""FastAPI app creation, logger configuration and main API routes."""
2-
import sys
32
from typing import Any
43

54
import llama_index
65
from fastapi import FastAPI
76
from fastapi.openapi.utils import get_openapi
8-
from loguru import logger
97

108
from private_gpt.paths import docs_path
119
from private_gpt.server.chat.chat_router import chat_router
@@ -16,21 +14,6 @@
1614
from private_gpt.server.ingest.ingest_router import ingest_router
1715
from private_gpt.settings.settings import settings
1816

19-
# Remove pre-configured logging handler
20-
logger.remove(0)
21-
# Create a new logging handler same as the pre-configured one but with the extra
22-
# attribute `request_id`
23-
logger.add(
24-
sys.stdout,
25-
level="INFO",
26-
format=(
27-
"<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | "
28-
"<level>{level: <8}</level> | "
29-
"<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | "
30-
"ID: {extra[request_id]} - <level>{message}</level>"
31-
),
32-
)
33-
3417
# Add LlamaIndex simple observability
3518
llama_index.set_global_handler("simple")
3619

private_gpt/settings/settings_loader.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import functools
2+
import logging
23
import os
34
import sys
45
from pathlib import Path
@@ -9,6 +10,8 @@
910
from private_gpt.constants import PROJECT_ROOT_PATH
1011
from private_gpt.settings.yaml import load_yaml_with_envvars
1112

13+
logger = logging.getLogger(__name__)
14+
1215
_settings_folder = os.environ.get("PGPT_SETTINGS_FOLDER", PROJECT_ROOT_PATH)
1316

1417
# if running in unittest, use the test profile
@@ -41,7 +44,7 @@ def load_profile(profile: str) -> dict[str, Any]:
4144

4245
def load_active_profiles() -> dict[str, Any]:
4346
"""Load active profiles and merge them."""
44-
print(f"Starting application with profiles: {active_profiles}")
47+
logger.info("Starting application with profiles=%s", active_profiles)
4548
loaded_profiles = [load_profile(profile) for profile in active_profiles]
4649
merged: dict[str, Any] = functools.reduce(deep_update, loaded_profiles, {})
4750
return merged

pyproject.toml

-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ authors = ["Zylon <hi@zylon.ai>"]
77
[tool.poetry.dependencies]
88
python = ">=3.11,<3.12"
99
fastapi = { extras = ["all"], version = "^0.103.1" }
10-
loguru = "^0.7.2"
1110
boto3 = "^1.28.56"
1211
injector = "^0.21.0"
1312
pyyaml = "^6.0.1"

0 commit comments

Comments
 (0)