瀏覽代碼

Add LoggerInjector, and some TODOs

Kirk Trombley 4 年之前
父節點
當前提交
4f10f80f82
共有 5 個文件被更改,包括 24 次插入3 次删除
  1. 3 1
      lib/rollbot/bot.py
  2. 11 1
      lib/rollbot/decorators/as_command.py
  3. 5 1
      lib/rollbot/injection/util.py
  4. 2 0
      lib/rollbot/types.py
  5. 3 0
      repl_driver.py

+ 3 - 1
lib/rollbot/bot.py

@@ -1,13 +1,14 @@
 from dataclasses import dataclass
 from typing import Any, Generic, TypeVar
 import asyncio
+import logging
 
 import aiosqlite
 import aiohttp
 
 from .types import CommandConfiguration, Message, Response, Context, Command
 
-# TODO logging
+# TODO logging config
 
 
 RawMsg = TypeVar("RawMsg")
@@ -24,6 +25,7 @@ class Rollbot(Generic[RawMsg]):
             respond=self.respond,
             request=aiohttp.ClientSession(),
             database=lambda: aiosqlite.connect(self.database_file),
+            logger=logging.getLogger(__name__),
         )
 
     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 typing import Union, Any
 from functools import wraps
+from logging import Logger
 import inspect
 
 from ..types import (
@@ -10,7 +11,14 @@ from ..types import (
     CommandType,
     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
 
 decorated_commands: dict[str, CommandType] = {}
@@ -54,6 +62,8 @@ def _get_injectors(fn: Callable[..., Any]) -> list[Injector]:
             injectors.append(ContextInjector)
         elif annot == Command:
             injectors.append(CommandInjector)
+        elif annot == Logger:
+            injectors.append(LoggerInjector)
         elif isinstance(annot, Injector):
             injectors.append(annot)
         else:

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

@@ -1,6 +1,7 @@
 from collections.abc import Callable, Coroutine
 from typing import TypeVar, Any
 from datetime import datetime
+from logging import Logger
 
 from aiohttp import ClientSession
 
@@ -8,7 +9,6 @@ from ..types import Message, Context, Attachment, Command
 from .base import Injector, InjectorWithCleanup, Simple
 
 __all__ = [
-    "Lazy",
     "MessageInjector",
     "ContextInjector",
     "Origin",
@@ -22,7 +22,9 @@ __all__ = [
     "CommandInjector",
     "Request",
     "Respond",
+    "LoggerInjector",
     "Config",
+    "Lazy",
 ]
 
 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)
 Request = Simple[ClientSession](lambda m, c: c.request)
 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]):

+ 2 - 0
lib/rollbot/types.py

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

+ 3 - 0
repl_driver.py

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