Skip to content

Commit

Permalink
feat: Add template debugging/logging
Browse files Browse the repository at this point in the history
Issue: #83
  • Loading branch information
pawamoy committed Sep 29, 2020
1 parent 409f93e commit 33b32c1
Show file tree
Hide file tree
Showing 18 changed files with 117 additions and 3 deletions.
2 changes: 1 addition & 1 deletion docs/handlers/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ See the documentation for

## Available handlers

- [Python][mkdocstrings.handlers.python]
- [Python](../python)
12 changes: 12 additions & 0 deletions docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,18 @@ The *Material* theme provides the following template structure:
- `properties.html`: to render the properties of an object (`staticmethod`, `read-only`, etc.)
- `signature.html`: to render functions and methods signatures

#### Debugging

Every template has access to a `log` function, allowing to log messages as usual:

```jinja
{{ log.debug("A DEBUG message.") }}
{{ log.info("An INFO message.") }}
{{ log.warning("A WARNING message.") }}
{{ log.error("An ERROR message.") }}
{{ log.critical("A CRITICAL message.") }}
```

### CSS classes

The *Material* theme uses the following CSS classes in the HTML:
Expand Down
3 changes: 3 additions & 0 deletions src/mkdocstrings/handlers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
from markdown import Markdown
from pymdownx.highlight import Highlight

from mkdocstrings.logging import get_template_logger

handlers_cache: Dict[str, Any] = {}


Expand Down Expand Up @@ -128,6 +130,7 @@ def __init__(self, directory: str, theme: str, custom_templates: Optional[str] =
self.env = Environment(autoescape=True, loader=FileSystemLoader(paths)) # type: ignore
self.env.filters["highlight"] = do_highlight
self.env.filters["any"] = do_any
self.env.globals["log"] = get_template_logger()

@abstractmethod
def render(self, data: Any, config: dict) -> str:
Expand Down
89 changes: 87 additions & 2 deletions src/mkdocstrings/logging.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
"""Utility functions."""
"""Logging functions."""

import logging
from typing import Callable, Optional

from jinja2 import contextfunction
from jinja2.runtime import Context
from mkdocs.utils import warning_filter


Expand Down Expand Up @@ -33,7 +36,79 @@ def process(self, msg, kwargs):
return f"{self.prefix}: {msg}", kwargs


def get_logger(name):
class TemplateLogger:
"""
A wrapper class to allow logging in templates.
Attributes:
debug: Function to log a DEBUG message.
info: Function to log an INFO message.
warning: Function to log a WARNING message.
error: Function to log an ERROR message.
critical: Function to log a CRITICAL message.
"""

def __init__(self, logger: LoggerAdapter):
"""
Initialize the object.
Arguments:
logger: A logger adapter.
"""
self.debug = get_template_logger_function(logger.debug)
self.info = get_template_logger_function(logger.info)
self.warning = get_template_logger_function(logger.warning)
self.error = get_template_logger_function(logger.error)
self.critical = get_template_logger_function(logger.critical)


def get_template_logger_function(logger_func: Callable) -> Callable:
"""
Create a wrapper function that automatically receives the Jinja template context.
Arguments:
logger_func: The logger function to use within the wrapper.
Returns:
A function.
"""

@contextfunction # noqa: WPS430 (nested function)
def wrapper(context: Context, msg: Optional[str] = None) -> str:
"""
Log a message.
Arguments:
context: The template context, automatically provided by Jinja.
msg: The message to log.
Returns:
An empty string.
"""
template_path = get_template_path(context)
logger_func(f"{template_path}: {msg or 'Rendering'}")
return ""

return wrapper


def get_template_path(context: Context) -> str:
"""
Return the path to the template currently using the given context.
Arguments:
context: The template context.
Returns:
The relative path to the template.
"""
template = context.environment.get_template(context.name)
if template.filename:
return template.filename.rsplit("/templates/", 1)[1]
return context.name


def get_logger(name: str) -> LoggerAdapter:
"""
Return a pre-configured logger.
Expand All @@ -46,3 +121,13 @@ def get_logger(name):
logger = logging.getLogger(f"mkdocs.plugins.{name}")
logger.addFilter(warning_filter)
return LoggerAdapter(name, logger)


def get_template_logger() -> TemplateLogger:
"""
Return a logger usable in templates.
Returns:
A template logger.
"""
return TemplateLogger(get_logger("mkdocstrings.templates"))
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/attribute.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
{% if config.show_if_no_docstring or attribute.has_contents %}

<div class="doc doc-object doc-attribute">
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/attributes.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
<p><strong>Attributes:</strong></p>
<table>
<thead>
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/children.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
{% if obj.children %}

<div class="doc doc-children">
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/class.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
{% if config.show_if_no_docstring or class.has_contents %}

<div class="doc doc-object doc-class">
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/docstring.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
{% if docstring_sections %}
{% for section in docstring_sections %}
{% if section.type == "markdown" %}
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/examples.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
<p><strong>Examples:</strong></p>
{% for section_type, sub_section in examples %}
{% if section_type == "markdown" %}
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/exceptions.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
<p><strong>Exceptions:</strong></p>
<table>
<thead>
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/function.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
{% if config.show_if_no_docstring or function.has_contents %}

<div class="doc doc-object doc-function">
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/method.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
{% if config.show_if_no_docstring or method.has_contents %}

<div class="doc doc-object doc-method">
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/module.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
{% if config.show_if_no_docstring or module.has_contents %}

<div class="doc doc-object doc-module">
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/parameters.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
<p><strong>Parameters:</strong></p>
<table>
<thead>
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/properties.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
{% if properties %}
<span class="doc doc-properties">
{% for property in properties %}
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/return.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
<p><strong>Returns:</strong></p>
<table>
<thead>
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/templates/python/material/signature.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{{ log.debug() }}
{% if signature %}
{% with %}
{% set ns = namespace(render_pos_only_separator=True, render_kw_only_separator=True, equal="=") %}
Expand Down

0 comments on commit 33b32c1

Please sign in to comment.