Skip to content

Commit

Permalink
Add plugin logger utility (#3245)
Browse files Browse the repository at this point in the history
  • Loading branch information
pawamoy committed Jun 6, 2023
1 parent 45c8b96 commit 18c01d2
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
7 changes: 7 additions & 0 deletions docs/dev-guide/plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
50 changes: 50 additions & 0 deletions mkdocs/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,3 +510,53 @@ def run_event(self, name: str, item=None, **kwargs):
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)

0 comments on commit 18c01d2

Please sign in to comment.