Skip to content

Commit

Permalink
Feature/loguru (#31)
Browse files Browse the repository at this point in the history
* change logging to loguru
  • Loading branch information
livioribeiro authored Oct 23, 2023
1 parent f004c1e commit 1906d83
Show file tree
Hide file tree
Showing 27 changed files with 190 additions and 256 deletions.
3 changes: 2 additions & 1 deletion docs/controllers.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ be the first two parameters.
from asgikit.requests import Request, read_json
from asgikit.responses import respond_text, respond_redirect
from selva.web import controller, get, post
from loguru import logger


@controller
Expand All @@ -27,7 +28,7 @@ class IndexController:
class AdminController:
@post("send")
async def handle_data(self, request: Request):
print(await read_json(request))
logger.info(await read_json(request))
await respond_redirect(request.response, "/")
```

Expand Down
3 changes: 2 additions & 1 deletion docs/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ in the processing of the request:

from asgikit.requests import Request
from selva.web.middleware import Middleware
from loguru import logger


class TimingMiddleware(Middleware):
Expand All @@ -40,7 +41,7 @@ in the processing of the request:
request_end = datetime.now()

delta = request_end - request_start
print(f"Request time: {delta}")
logger.info("Request time: {}", delta)
```

1. Invoke the middleware chain to process the request
Expand Down
3 changes: 2 additions & 1 deletion examples/background_tasks/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from asgikit.requests import Request
from asgikit.responses import respond_json
from loguru import logger

from selva.web import controller, get

Expand All @@ -16,4 +17,4 @@ async def background_task(self, request: Request):
await respond_json(request.response, {"message": message})

await asyncio.sleep(5)
print(message)
logger.info(message)
9 changes: 9 additions & 0 deletions examples/database/application/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import sys

from loguru import logger

logger.remove()
logger.enable("selva")
logger.disable("databases")
logger.disable("aiosqlite")
logger.add(sys.stderr, level="DEBUG")
6 changes: 2 additions & 4 deletions examples/database/application/service.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
import logging
import os
from typing import Annotated

from databases import Database
from loguru import logger

from selva.configuration import Settings
from selva.di import Inject, service

logger = logging.getLogger(__name__)


@service
def database_factory(settings: Settings) -> Database:
Expand Down Expand Up @@ -44,5 +42,5 @@ async def test(self):
async def count(self) -> int:
await self.database.execute("update counter set value = value + 1")
result = await self.database.fetch_val("select value from counter")
logger.info("Current count: %d", result)
logger.info("Current count: {}", result)
return result
2 changes: 2 additions & 0 deletions examples/hello_world/application.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from asgikit.requests import Request, read_json
from asgikit.responses import respond_json
from loguru import logger
from pydantic import BaseModel

from selva.di import Inject, service
Expand Down Expand Up @@ -30,6 +31,7 @@ async def greet_query(
name: Annotated[str, FromQuery("name")] = "World",
number: Annotated[int, FromQuery] = 1,
):
logger.info("message")
greeting = self.greeter.greet(name)
await respond_json(request.response, {"greeting": greeting, "number": number})

Expand Down
12 changes: 5 additions & 7 deletions examples/middleware/application/middleware.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import base64
import logging
from datetime import datetime
from http import HTTPStatus

from asgikit.requests import Request
from asgikit.responses import respond_status
from loguru import logger

from selva.web.middleware import Middleware

logger = logging.getLogger(__name__)


class TimingMiddleware(Middleware):
async def __call__(self, chain, request: Request):
Expand All @@ -22,7 +20,7 @@ async def __call__(self, chain, request: Request):
request_end = datetime.now()

delta = request_end - request_start
logging.warning("Request time: %s", delta)
logger.warning("Request time: {}", delta)


class LoggingMiddleware(Middleware):
Expand All @@ -37,8 +35,8 @@ async def __call__(self, chain, request: Request):
request_line = f"{request.method} {request.path} HTTP/{request.http_version}"
status = request.response.status

logging.warning(
'%s "%s" %s %s', client, request_line, status.value, status.phrase
logger.warning(
'{} "{}" {} {}', client, request_line, status.value, status.phrase
)


Expand All @@ -56,7 +54,7 @@ async def __call__(self, chain, request: Request):

authn = authn.removeprefix("Basic")
user, password = base64.urlsafe_b64decode(authn).decode().split(":")
logging.info("User '%s' with password '%s'", user, password)
logger.info("User '{}' with password '{}'", user, password)
request["user"] = user

await chain(request, response)
12 changes: 5 additions & 7 deletions examples/websocket/application.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import logging
from pathlib import Path
from typing import Annotated

from asgikit.errors.websocket import WebSocketDisconnectError
from asgikit.requests import Request
from asgikit.responses import respond_file
from asgikit.websockets import WebSocket
from loguru import logger

from selva.configuration import Settings
from selva.di import Inject, service
from selva.web import controller, get, websocket
from selva.web.exception import WebSocketException

logger = logging.getLogger(__name__)


@service
class WebSocketService:
Expand All @@ -25,17 +23,17 @@ async def handle_websocket(self, request: Request):
ws = request.websocket
self.clients[client] = ws

logger.info("client connected: %s", client)
logger.info("client connected: {}", client)

while True:
try:
message = await ws.receive()
logger.info(
"client message: content=%s, client=%s", message, repr(client)
"client message: content={}, client={}", message, repr(client)
)
await self.broadcast(message)
except (WebSocketDisconnectError, WebSocketException):
logger.info("client disconnected: %s", repr(client))
logger.info("client disconnected: {}", repr(client))
del self.clients[client]
break

Expand All @@ -48,7 +46,7 @@ async def broadcast(self, message: str):
await ws.send(message)
except (WebSocketDisconnectError, WebSocketException):
del self.clients[client]
logger.info("client disconnected: %s", repr(client))
logger.info("client disconnected: {}", repr(client))


@controller
Expand Down
9 changes: 5 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ packages = [
python = "^3.12"
asgikit = "^0.5"
pydantic = "^2.4"
loguru = "^0.7"

[tool.poetry.group.dev]
optional = true
Expand All @@ -50,12 +51,12 @@ coverage = { version = "^7.3", extras = ["toml"] }
optional = true

[tool.poetry.group.lint.dependencies]
pylint = "^2.17"
black = "^23.9"
pylint = "^3.0"
black = "^23.10"
isort = "^5.12"
flake8 = "^6.1"
mypy = "^1.5"
ruff = "*"
mypy = "^1.6"
ruff = "^0.1"

[tool.poetry.group.docs]
optional = true
Expand Down
9 changes: 9 additions & 0 deletions src/selva/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from loguru import logger

from selva.logging.stdlib import setup_loguru_std_logging_interceptor

# disable asgikit and selva loggers by default
logger.disable("asgikit")
logger.disable("selva")

setup_loguru_std_logging_interceptor()
6 changes: 2 additions & 4 deletions src/selva/_util/maybe_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@
import functools
import inspect
from collections.abc import Awaitable, Callable
from typing import Any, ParamSpec
from typing import Any

P = ParamSpec("P")


async def maybe_async(
async def maybe_async[**P](
target: Awaitable | Callable[P, Any], *args: P.args, **kwargs: P.kwargs
) -> Any:
if inspect.isawaitable(target):
Expand Down
8 changes: 2 additions & 6 deletions src/selva/configuration/environment.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import json
import os
from collections.abc import Callable, Mapping, Sequence
from typing import Any, Optional, TypeVar

T = TypeVar("T")
from typing import Any, Optional

_UNSET = ()

Expand All @@ -18,9 +16,7 @@ def get_str(key: str, default: Optional[str] = _UNSET) -> str:
raise KeyError(f"Environment variable '{key}' is not defined")


def _get_env_and_convert(
key: str, default: Optional[T], converter: Callable[[str], T], type_name: str
) -> T:
def _get_env_and_convert[T](key: str, default: T | None, converter: Callable[[str], T], type_name: str) -> T:
value = get_str(key, None)
if value is None:
return default
Expand Down
45 changes: 0 additions & 45 deletions src/selva/configuration/logging.py

This file was deleted.

7 changes: 3 additions & 4 deletions src/selva/configuration/settings.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import importlib
import importlib.util
import inspect
import logging
import os
from pathlib import Path
from types import ModuleType, SimpleNamespace
from typing import Any

from loguru import logger

from selva.configuration import defaults

__all__ = ("Settings", "SettingsModuleError", "get_settings")
Expand All @@ -16,8 +17,6 @@

SELVA_ENV = "SELVA_ENV"

logger = logging.getLogger(__name__)


class SettingsModuleError(Exception):
def __init__(self, path: Path):
Expand Down Expand Up @@ -74,7 +73,7 @@ def get_settings_for_env(env: str = None) -> dict[str, Any]:
settings_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(settings_module)
except FileNotFoundError:
logger.info("settings module not found: %s", settings_module_path)
logger.info("settings module not found: {}", settings_module_path)
return {}
except (KeyError, ValueError):
raise
Expand Down
Loading

0 comments on commit 1906d83

Please sign in to comment.