How to use the sphinx.util.logging function in Sphinx

To help you get started, we’ve selected a few Sphinx examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github numba / numba / docs / source / _ext / ghfiles.py View on Github external
import os.path as path
import subprocess
import shlex
from sphinx.util import logging
from docutils import nodes
logger = logging.getLogger(__name__)


# use an old git trick, to get the top-level, could have used ../ etc.. but
# this will be fine..
top = subprocess.check_output(shlex.split(
    "git rev-parse --show-toplevel")).strip().decode("utf-8")


def make_ref(text):
    """ Make hyperlink to Github """
    full_path = path.join(top, text)
    if path.isfile(full_path):
        ref = "https://www.github.com/numba/numba/blob/master/" + text
    elif path.isdir(full_path):
        ref = "https://www.github.com/numba/numba/tree/master/" + text
    else:
github sphinx-doc / sphinx / sphinx / writers / texinfo.py View on Github external
from sphinx import addnodes, __display_version__
from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.domains import IndexEntry
from sphinx.errors import ExtensionError
from sphinx.locale import admonitionlabels, _, __
from sphinx.util import logging
from sphinx.util.docutils import SphinxTranslator
from sphinx.util.i18n import format_date
from sphinx.writers.latex import collected_footnote

if False:
    # For type annotation
    from sphinx.builders.texinfo import TexinfoBuilder


logger = logging.getLogger(__name__)


COPYING = """\
@quotation
%(project)s %(release)s, %(date)s

%(author)s

Copyright @copyright{} %(copyright)s
@end quotation
"""

TEMPLATE = """\
\\input texinfo   @c -*-texinfo-*-
@c %%**start of header
@setfilename %(filename)s
github sphinx-doc / sphinx / sphinx / config.py View on Github external
from sphinx.errors import ConfigError, ExtensionError
from sphinx.locale import _, __
from sphinx.util import logging
from sphinx.util.i18n import format_date
from sphinx.util.osutil import cd
from sphinx.util.pycompat import execfile_
from sphinx.util.typing import NoneType

if False:
    # For type annotation
    from typing import Callable, Dict, Generator, Iterator, List, Set, Tuple  # NOQA
    from sphinx.application import Sphinx  # NOQA
    from sphinx.environment import BuildEnvironment  # NOQA
    from sphinx.util.tags import Tags  # NOQA

logger = logging.getLogger(__name__)

CONFIG_FILENAME = 'conf.py'
UNSERIALIZABLE_TYPES = (type, types.ModuleType, types.FunctionType)
copyright_year_re = re.compile(r'^((\d{4}-)?)(\d{4})(?=[ ,])')

ConfigValue = NamedTuple('ConfigValue', [('name', str),
                                         ('value', Any),
                                         ('rebuild', Union[bool, str])])


def is_serializable(obj):
    # type: (Any) -> bool
    """Check if object is serializable or not."""
    if isinstance(obj, UNSERIALIZABLE_TYPES):
        return False
    elif isinstance(obj, dict):
github epruesse / ymp / src / ymp / sphinxext.py View on Github external
from sphinx.application import Sphinx
from sphinx.directives import ObjectDescription
from sphinx.domains import Domain, ObjType
from sphinx.environment import BuildEnvironment
from sphinx.environment.collectors import EnvironmentCollector
from sphinx.roles import XRefRole
from sphinx.util import logging, ws_re
from sphinx.util.nodes import make_refnode

import ymp
from ymp.snakemake import ExpandableWorkflow
from ymp.snakemakelexer import SnakemakeLexer
from ymp.stage import Stage

try:
    logger = logging.getLogger(__name__)
except AttributeError:
    # Fall back to normal logging
    import logging as _logging
    logger = _logging.getLogger(__name__)

#: str: Path in which YMP package is located
BASEPATH = os.path.dirname(os.path.dirname(ymp.__file__))


def relpath(path: str) -> str:
    """Make absolute path relative to BASEPATH

    Args:
      path: absolute path

    Returns:
github sphinx-doc / sphinx / sphinx / environment / collectors / asset.py View on Github external
from docutils.utils import relative_path

from sphinx import addnodes
from sphinx.environment.collectors import EnvironmentCollector
from sphinx.locale import __
from sphinx.util import logging
from sphinx.util.i18n import get_image_filename_for_language, search_image_for_language
from sphinx.util.images import guess_mimetype

if False:
    # For type annotation
    from typing import Dict, List, Set  # NOQA
    from sphinx.sphinx import Sphinx  # NOQA
    from sphinx.environment import BuildEnvironment  # NOQA

logger = logging.getLogger(__name__)


class ImageCollector(EnvironmentCollector):
    """Image files collector for sphinx.environment."""

    def clear_doc(self, app, env, docname):
        # type: (Sphinx, BuildEnvironment, str) -> None
        env.images.purge_doc(docname)

    def merge_other(self, app, env, docnames, other):
        # type: (Sphinx, BuildEnvironment, Set[str], BuildEnvironment) -> None
        env.images.merge_other(docnames, other.images)

    def process_doc(self, app, doctree):
        # type: (Sphinx, nodes.document) -> None
        """Process and rewrite image URIs."""
github sphinx-doc / sphinx / sphinx / ext / viewcode.py View on Github external
from docutils import nodes
from docutils.nodes import Element, Node

import sphinx
from sphinx import addnodes
from sphinx.application import Sphinx
from sphinx.config import Config
from sphinx.deprecation import RemovedInSphinx30Warning
from sphinx.environment import BuildEnvironment
from sphinx.locale import _, __
from sphinx.pycode import ModuleAnalyzer
from sphinx.util import get_full_modname, logging, status_iterator
from sphinx.util.nodes import make_refnode


logger = logging.getLogger(__name__)


def _get_full_modname(app: Sphinx, modname: str, attribute: str) -> str:
    try:
        return get_full_modname(modname, attribute)
    except AttributeError:
        # sphinx.ext.viewcode can't follow class instance attribute
        # then AttributeError logging output only verbose mode.
        logger.verbose('Didn\'t find %s in %s', attribute, modname)
        return None
    except Exception as e:
        # sphinx.ext.viewcode follow python domain directives.
        # because of that, if there are no real modules exists that specified
        # by py:function or other directives, viewcode emits a lot of warnings.
        # It should be displayed only verbose mode.
        logger.verbose(traceback.format_exc().rstrip())
github gwpy / gwpy / docs / conf.py View on Github external
def write_citing_rst(_):
    logger = logging.getLogger('zenodo')
    here = os.path.dirname(__file__)
    with open(os.path.join(here, 'citing.rst.in'), 'r') as fobj:
        citing = fobj.read()
    citing += '\n' + zenodo.format_citations(597016)
    out = os.path.join(here, 'citing.rst')
    with open(out, 'w') as f:
        f.write(citing)
    logger.info('[zenodo] wrote {0}'.format(out))
github astropy / astropy / docs / conf.py View on Github external
def setup(app):
        msg = ('The sphinx_gallery extension is not installed, so the '
               'gallery will not be built.  You will probably see '
               'additional warnings about undefined references due '
               'to this.')
        try:
            app.warn(msg)
        except AttributeError:
            # Sphinx 1.6+
            from sphinx.util import logging
            logger = logging.getLogger(__name__)
            logger.warning(msg)
github RunestoneInteractive / RunestoneComponents / runestone / fitb / fitb.py View on Github external
def depart_fitb_node(self, node):
    # If there were fewer blanks than feedback items, add blanks at the end of the question.
    blankCount = 0
    for _ in node.traverse(BlankNode):
        blankCount += 1
    while blankCount < len(node.feedbackArray):
        visit_blank_node(self, None)
        blankCount += 1

    # Warn if there are fewer feedback items than blanks.
    if len(node.feedbackArray) < blankCount:
        # Taken from the example in the `logging API `_.
        logger = logging.getLogger(__name__)
        logger.warning(
            "Not enough feedback for the number of blanks supplied.", location=node
        )

    # Generate the HTML.
    json_feedback = json.dumps(node.feedbackArray)
    # Some nodes (for example, those in a timed node) have their ``document == None``. Find a valid ``document``.
    node_with_document = node
    while not node_with_document.document:
        node_with_document = node_with_document.parent
    # Supply client-side grading info if we're not grading on the server.
    node.fitb_options["json"] = (
        "false"
        if node_with_document.document.settings.env.config.runestone_server_side_grading
        else json_feedback
    )
github coq / coq / doc / sphinx / conf.py View on Github external
def copy_formatspecific_files(app):
    ext = ".{}.rst".format(app.builder.name)
    for fname in sorted(os.listdir(app.srcdir)):
        if fname.endswith(ext):
            src = os.path.join(app.srcdir, fname)
            dst = os.path.join(app.srcdir, fname[:-len(ext)] + ".rst")
            logger = sphinx.util.logging.getLogger(__name__)
            if readbin(src) == readbin(dst):
                logger.info("Skipping {}: {} is up to date".format(src, dst))
            else:
                logger.info("Copying {} to {}".format(src, dst))
                copyfile(src, dst)