Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion server/alembic.ini
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ version_path_separator = os
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url = postgresql+psycopg://postgres:postgres@postgres:5432/pin_sphere
sqlalchemy.url = postgresql+psycopg://postgres:PJNJnJq40klQLP3u@db.wsynpmmfmzzmbryhseof.supabase.co:5432/postgres


[post_write_hooks]
Expand Down
9 changes: 6 additions & 3 deletions server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,16 @@ class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=Path(__file__).parent / ".env", env_file_encoding="utf-8"
)
POSTGRES_UESRNAME: str
POSTGRES_PASSWORD: str
POSTGRES_HOST: str
POSTGRES_PORT: int
POSTGRES_DATABASE: str

def get_database_dsn(self, driver: Literal["asyncpg", "psycopg"]) -> PostgresDsn:
return PostgresDsn(
f"postgresql+{driver}://postgres:postgres@postgres:5432/pin_sphere"
f"postgresql+{driver}://{self.POSTGRES_UESRNAME}:{self.POSTGRES_PASSWORD}@{self.POSTGRES_HOST}:{self.POSTGRES_PORT}/{self.POSTGRES_DATABASE}"
)


print(Path(__file__).parent / ".env")
settings = Settings() # type: ignore
print(settings)
137 changes: 137 additions & 0 deletions server/core/logging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import logging.config
import os
import uuid
from typing import Any

import structlog


Logger = structlog.stdlib.BoundLogger


class Logging[RendererType]:
"""Hubben logging configurator of `structlog` and `logging`.

Customized implementation inspired by the following documentation:
https://www.structlog.org/en/stable/standard-library.html#rendering-using-structlog-based-formatters-within-logging

"""

timestamper = structlog.processors.TimeStamper(fmt="iso")

@classmethod
def get_level(cls) -> str:
return os.environ.get("LOG_LEVEL", "INFO")

@classmethod
def get_processors(cls) -> list[Any]:
return [
structlog.contextvars.merge_contextvars,
structlog.stdlib.add_log_level,
structlog.stdlib.add_logger_name,
structlog.stdlib.PositionalArgumentsFormatter(),
cls.timestamper,
structlog.processors.UnicodeDecoder(),
structlog.processors.StackInfoRenderer(),
structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
]

@classmethod
def get_renderer(cls) -> RendererType:
raise NotImplementedError()

@classmethod
def configure_stdlib(cls) -> None:
level = cls.get_level()
logging.config.dictConfig(
{
"version": 1,
"disable_existing_loggers": True,
"formatters": {
"app": {
"()": structlog.stdlib.ProcessorFormatter,
"processors": [
structlog.stdlib.ProcessorFormatter.remove_processors_meta,
cls.get_renderer(),
],
"foreign_pre_chain": [
structlog.contextvars.merge_contextvars,
structlog.stdlib.add_log_level,
structlog.stdlib.add_logger_name,
structlog.stdlib.PositionalArgumentsFormatter(),
structlog.stdlib.ExtraAdder(),
cls.timestamper,
structlog.processors.UnicodeDecoder(),
structlog.processors.StackInfoRenderer(),
],
},
},
"handlers": {
"default": {
"level": level,
"class": "logging.StreamHandler",
"formatter": "app",
},
},
"loggers": {
"": {
"handlers": ["default"],
"level": level,
"propagate": False,
},
# Propagate third-party loggers to the root one
**{
logger: {
"handlers": [],
"propagate": True,
}
for logger in [
"uvicorn",
"sqlalchemy",
"dramatiq",
"authlib",
"apscheduler",
]
},
},
}
)

@classmethod
def configure_structlog(cls) -> None:
structlog.configure_once(
processors=cls.get_processors(),
logger_factory=structlog.stdlib.LoggerFactory(),
wrapper_class=structlog.stdlib.BoundLogger,
cache_logger_on_first_use=True,
)

@classmethod
def configure(
cls,
) -> None:
cls.configure_stdlib()
cls.configure_structlog()


class Development(Logging[structlog.dev.ConsoleRenderer]):
@classmethod
def get_renderer(cls) -> structlog.dev.ConsoleRenderer:
return structlog.dev.ConsoleRenderer(colors=True)


class Production(Logging[structlog.processors.JSONRenderer]):
@classmethod
def get_renderer(cls) -> structlog.processors.JSONRenderer:
return structlog.processors.JSONRenderer()


def configure() -> None:
if os.environ.get("ENV", "dev") == "dev":
Development.configure()
else:
Production.configure()


def generate_correlation_id() -> str:
return str(uuid.uuid4())
Loading