From 845a3142502598e9ab5c0d4c7646679f824359e4 Mon Sep 17 00:00:00 2001 From: Gergely Polonkai Date: Mon, 16 Jan 2017 08:56:58 +0100 Subject: [PATCH] Update documentation, and a bit of the functionality --- .gitignore | 4 + docs/Makefile | 20 ++++ docs/conf.py | 165 +++++++++++++++++++++++++++++++ docs/index.rst | 22 +++++ flask_logging_extras/__init__.py | 65 +++++++++++- 5 files changed, 272 insertions(+), 4 deletions(-) create mode 100644 .gitignore create mode 100644 docs/Makefile create mode 100644 docs/conf.py create mode 100644 docs/index.rst diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dc0133a --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/.venv/ +/docs/_build +__pycache__/ +*.pyc diff --git a/docs/Makefile b/docs/Makefile new file mode 100644 index 0000000..468a426 --- /dev/null +++ b/docs/Makefile @@ -0,0 +1,20 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SPHINXPROJ = Flask-Logging-Extended +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..226bac1 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,165 @@ +# -*- coding: utf-8 -*- +# +# Flask-Logging-Extended documentation build configuration file, created by +# sphinx-quickstart on Sun Jan 15 17:29:58 2017. +# +# This file is execfile()d with the current directory set to its +# containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +# +import os +import sys +sys.path.insert(0, os.path.abspath('..')) + + +# -- General configuration ------------------------------------------------ + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + 'sphinx.ext.autodoc', + 'sphinx.ext.intersphinx', + 'sphinx.ext.coverage', + 'sphinx.ext.viewcode', + 'sphinx.ext.autosummary' +] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = '.rst' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = 'Flask-Logging-Extended' +copyright = '2017, Gergely Polonkai' +author = 'Gergely Polonkai' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.1' +# The full version, including alpha/beta/rc tags. +release = '0.1.1' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +html_theme = 'flask' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +# +# html_theme_options = {} + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + + +# -- Options for HTMLHelp output ------------------------------------------ + +# Output file base name for HTML help builder. +htmlhelp_basename = 'Flask-Logging-Extendeddoc' + + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, 'Flask-Logging-Extended.tex', 'Flask-Logging-Extended Documentation', + 'Gergely Polonkai', 'manual'), +] + + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + (master_doc, 'flask-logging-extended', 'Flask-Logging-Extended Documentation', + [author], 1) +] + + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + (master_doc, 'Flask-Logging-Extended', 'Flask-Logging-Extended Documentation', + author, 'Flask-Logging-Extended', 'One line description of project.', + 'Miscellaneous'), +] + + + + +# Example configuration for intersphinx: refer to the Python standard library. +intersphinx_mapping = {'https://docs.python.org/': None} diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..0c2f81d --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,22 @@ +.. Flask-Logging-Extended documentation master file, created by + sphinx-quickstart on Sun Jan 15 17:29:58 2017. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +Welcome to Flask-Logging-Extended's documentation! +================================================== + +.. toctree:: + :maxdepth: 2 + :caption: Contents: + + +.. automodule:: flask_logging_extras + :members: + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/flask_logging_extras/__init__.py b/flask_logging_extras/__init__.py index bd92679..027ce2b 100644 --- a/flask_logging_extras/__init__.py +++ b/flask_logging_extras/__init__.py @@ -16,6 +16,34 @@ __copyright__ = '(c) 2015 GT2' class FlaskExtraLogger(logging.getLoggerClass()): """ A logger class that is capable of adding extra keywords to log formatters + + Usage: + + .. code-block:: python + + import logging + + from flask_logging_extras import register_logger_class + + # This must be done before the app is initialized! + register_logger_class(cls=FlaskExtraLogger) + + app = Flask(__name__) + app.config['FLASK_LOGGING_EXTRAS_KEYWORDS'] = ['category'] + app.logger.init_app() + + formatter = logging.Formatter( + '[%(asctime)s] [%(levelname)s] [%(category)s] %(message)s') + handler = logging.FileHandler('app.log', mode='a') + handler.setFormatter(formatter) + handler.setLevel(logging.INFO) + + app.logger.addHandler(handler) + + app.logger.info('The message', category='my category') + + # This will produce something like this in app.log: + # [TIMESTAMP2017-01-16 08:44:48.944] [INFO] [my category] The message """ def __init__(self, *args, **kwargs): @@ -38,11 +66,25 @@ class FlaskExtraLogger(logging.getLoggerClass()): super(FlaskExtraLogger, self)._log(*args, **kwargs) def init_app(self, app): - self.app = app + """ + Intialize the logger class with a Flask application - self.app.config.setdefault('FLASK_LOGGING_EXTRAS_KEYWORDS', []) + The class reads its necessary configuration from the config of this + application. - for kw in self.app.config['FLASK_LOGGING_EXTRAS_KEYWORDS']: + If the application doesn’t call this, or doesn’t have the + `FLASK_LOGGING_EXTRAS_KEYWORDS` in its config, no extra + functionality will be added. + + :param app: a Flask application + :type app: Flask + :raises ValueError: if the app tries to register a keyword that is + reserved for internal use + """ + + app.config.setdefault('FLASK_LOGGING_EXTRAS_KEYWORDS', []) + + for kw in app.config['FLASK_LOGGING_EXTRAS_KEYWORDS']: if kw in ['exc_info', 'extra', 'stack_info']: raise ValueError( '"{keyword}" member of FLASK_LOGGING_EXTRAS_KEYWORDS is ' @@ -53,15 +95,30 @@ def register_logger_class(cls=FlaskExtraLogger): """ Register a new logger class - It is effectively a wrapper around logging.setLoggerClass(), with an + It is effectively a wrapper around `logging.setLoggerClass()`, with an added check to make sure the class can be used as a logger. To use the extra features of the logger class in a Flask app, you must call it before the app is instantiated. + + This function returns the logger class that was the default before + calling. This might be useful if you only want to use `cls` in the + Flask app object, but not anywhere else in your code. In this case, + simply call `register_logger_class()` again with the return value from + the first invocation. + + :param cls: a logger class to register as the default one + :type cls: class(logging.Logger) + :returns: the old default logger class + :rtype: class + :raises TypeError: if the class is not a subclass of `logging.Logger` """ if not issubclass(cls, logging.Logger): raise TypeError( "The logger class must be a subclass of logging.Logger!") + old_class = logging.get_logger_class() logging.setLoggerClass(cls) + + return old_class