Add plugin logger utility (#3245)

This commit is contained in:
Timothée Mazzucotelli
2023-06-07 01:22:00 +02:00
committed by GitHub
parent 45c8b9669b
commit 18c01d2e74
2 changed files with 57 additions and 0 deletions

View File

@@ -474,6 +474,13 @@ class MyPlugin(BasePlugin):
...
```
### Logging in plugins
MkDocs provides a `get_plugin_logger` function which returns
a logger that can be used to log messages.
#### ::: mkdocs.plugins.get_plugin_logger
### Entry Point
Plugins need to be packaged as Python libraries (distributed on PyPI separate

View File

@@ -510,3 +510,53 @@ class PluginCollection(dict, MutableMapping[str, BasePlugin]):
if result is not None:
item = result
return item
class PrefixedLogger(logging.LoggerAdapter):
"""A logger adapter to prefix log messages."""
def __init__(self, prefix: str, logger: logging.Logger) -> None:
"""
Initialize the logger adapter.
Arguments:
prefix: The string to insert in front of every message.
logger: The logger instance.
"""
super().__init__(logger, {})
self.prefix = prefix
def process(self, msg: str, kwargs: MutableMapping[str, Any]) -> tuple[str, Any]:
"""
Process the message.
Arguments:
msg: The message:
kwargs: Remaining arguments.
Returns:
The processed message.
"""
return f"{self.prefix}: {msg}", kwargs
def get_plugin_logger(name: str) -> PrefixedLogger:
"""Return a logger for plugins.
Arguments:
name: The name to use with `logging.getLogger`.
Returns:
A logger configured to work well in MkDocs,
prefixing each message with the plugin package name.
Example:
```python
from mkdocs.plugins import get_plugin_logger
logger = get_plugin_logger(__name__)
logger.info("My plugin message")
```
"""
logger = logging.getLogger(f"mkdocs.plugins.{name}")
return PrefixedLogger(name.split(".", 1)[0], logger)