Эх сурвалжийг харах

Add LoggerInjector, and some TODOs

Kirk Trombley 4 жил өмнө
parent
commit
4f10f80f82

+ 3 - 1
lib/rollbot/bot.py

@@ -1,13 +1,14 @@
 from dataclasses import dataclass
 from dataclasses import dataclass
 from typing import Any, Generic, TypeVar
 from typing import Any, Generic, TypeVar
 import asyncio
 import asyncio
+import logging
 
 
 import aiosqlite
 import aiosqlite
 import aiohttp
 import aiohttp
 
 
 from .types import CommandConfiguration, Message, Response, Context, Command
 from .types import CommandConfiguration, Message, Response, Context, Command
 
 
-# TODO logging
+# TODO logging config
 
 
 
 
 RawMsg = TypeVar("RawMsg")
 RawMsg = TypeVar("RawMsg")
@@ -24,6 +25,7 @@ class Rollbot(Generic[RawMsg]):
             respond=self.respond,
             respond=self.respond,
             request=aiohttp.ClientSession(),
             request=aiohttp.ClientSession(),
             database=lambda: aiosqlite.connect(self.database_file),
             database=lambda: aiosqlite.connect(self.database_file),
+            logger=logging.getLogger(__name__),
         )
         )
 
 
     def read_config(self, key: str) -> Any:
     def read_config(self, key: str) -> Any:

+ 11 - 1
lib/rollbot/decorators/as_command.py

@@ -1,6 +1,7 @@
 from collections.abc import Callable, AsyncGenerator
 from collections.abc import Callable, AsyncGenerator
 from typing import Union, Any
 from typing import Union, Any
 from functools import wraps
 from functools import wraps
+from logging import Logger
 import inspect
 import inspect
 
 
 from ..types import (
 from ..types import (
@@ -10,7 +11,14 @@ from ..types import (
     CommandType,
     CommandType,
     Response,
     Response,
 )
 )
-from ..injection import Injector, inject_all, MessageInjector, ContextInjector, CommandInjector
+from ..injection import (
+    Injector,
+    inject_all,
+    MessageInjector,
+    ContextInjector,
+    CommandInjector,
+    LoggerInjector,
+)
 from .error_handling import with_failure_handling
 from .error_handling import with_failure_handling
 
 
 decorated_commands: dict[str, CommandType] = {}
 decorated_commands: dict[str, CommandType] = {}
@@ -54,6 +62,8 @@ def _get_injectors(fn: Callable[..., Any]) -> list[Injector]:
             injectors.append(ContextInjector)
             injectors.append(ContextInjector)
         elif annot == Command:
         elif annot == Command:
             injectors.append(CommandInjector)
             injectors.append(CommandInjector)
+        elif annot == Logger:
+            injectors.append(LoggerInjector)
         elif isinstance(annot, Injector):
         elif isinstance(annot, Injector):
             injectors.append(annot)
             injectors.append(annot)
         else:
         else:

+ 5 - 1
lib/rollbot/injection/util.py

@@ -1,6 +1,7 @@
 from collections.abc import Callable, Coroutine
 from collections.abc import Callable, Coroutine
 from typing import TypeVar, Any
 from typing import TypeVar, Any
 from datetime import datetime
 from datetime import datetime
+from logging import Logger
 
 
 from aiohttp import ClientSession
 from aiohttp import ClientSession
 
 
@@ -8,7 +9,6 @@ from ..types import Message, Context, Attachment, Command
 from .base import Injector, InjectorWithCleanup, Simple
 from .base import Injector, InjectorWithCleanup, Simple
 
 
 __all__ = [
 __all__ = [
-    "Lazy",
     "MessageInjector",
     "MessageInjector",
     "ContextInjector",
     "ContextInjector",
     "Origin",
     "Origin",
@@ -22,7 +22,9 @@ __all__ = [
     "CommandInjector",
     "CommandInjector",
     "Request",
     "Request",
     "Respond",
     "Respond",
+    "LoggerInjector",
     "Config",
     "Config",
+    "Lazy",
 ]
 ]
 
 
 MessageInjector = Simple[Message](lambda m, c: m)
 MessageInjector = Simple[Message](lambda m, c: m)
@@ -38,6 +40,8 @@ Attachments = Simple[list[Attachment]](lambda m, c: m.attachments)
 CommandInjector = Simple[Command](lambda m, c: m.command)
 CommandInjector = Simple[Command](lambda m, c: m.command)
 Request = Simple[ClientSession](lambda m, c: c.request)
 Request = Simple[ClientSession](lambda m, c: c.request)
 Respond = Simple[Callable[[], Coroutine[None, None, None]]](lambda m, c: c.respond)
 Respond = Simple[Callable[[], Coroutine[None, None, None]]](lambda m, c: c.respond)
+# TODO might be nice to auto format with command name
+LoggerInjector = Simple[Logger](lambda m, c: c.logger)
 
 
 
 
 class Config(Injector[Any]):
 class Config(Injector[Any]):

+ 2 - 0
lib/rollbot/types.py

@@ -1,5 +1,6 @@
 from __future__ import annotations
 from __future__ import annotations
 
 
+from logging import Logger
 from dataclasses import dataclass, field
 from dataclasses import dataclass, field
 from datetime import datetime
 from datetime import datetime
 from collections.abc import Callable, Coroutine, Container
 from collections.abc import Callable, Coroutine, Container
@@ -104,6 +105,7 @@ class Context:
     respond: Callable[[], Coroutine[None, None, None]]
     respond: Callable[[], Coroutine[None, None, None]]
     request: ClientSession
     request: ClientSession
     database: Callable[[], Coroutine[None, None, Connection]]
     database: Callable[[], Coroutine[None, None, Connection]]
+    logger: Logger
 
 
 
 
 CommandType = Callable[[Message, Context], Coroutine[None, None, None]]
 CommandType = Callable[[Message, Context], Coroutine[None, None, None]]

+ 3 - 0
repl_driver.py

@@ -1,4 +1,5 @@
 from datetime import datetime
 from datetime import datetime
+from logging import Logger
 import asyncio
 import asyncio
 
 
 import rollbot
 import rollbot
@@ -92,6 +93,7 @@ async def count_improved(
     name: Subcommand.Arg(0, required=False, default="main"),
     name: Subcommand.Arg(0, required=False, default="main"),
     counter: Data(MyCounter).For(Subcommand.Arg(0, required=False, default="main")),
     counter: Data(MyCounter).For(Subcommand.Arg(0, required=False, default="main")),
     store: Data(MyCounter),
     store: Data(MyCounter),
+    log: Logger,
 ):
 ):
     if subc.name == "up":
     if subc.name == "up":
         counter.one += 1
         counter.one += 1
@@ -101,6 +103,7 @@ async def count_improved(
         counter.two -= 2
         counter.two -= 2
     elif subc.name == "show":
     elif subc.name == "show":
         yield f"{name} = {counter}"
         yield f"{name} = {counter}"
+    log.info(f"Saving {counter} under {name}")
     await store.save(name, counter)
     await store.save(name, counter)