Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
mar10 committed Apr 21, 2018
1 parent 1d623ad commit d79fe14
Show file tree
Hide file tree
Showing 15 changed files with 137 additions and 89 deletions.
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@


## 'logging' branch
- Use configurable python logger
- **Refactor logging**
- Library:
- Remove configurable python logger
- Remove enable_loggers option
- Remove util.note(), .status(), ...

## 2.3.0 / 2018-04-06

Expand Down
26 changes: 22 additions & 4 deletions doc/sphinx/_templates/autosummary/module.rst
Original file line number Diff line number Diff line change
@@ -1,31 +1,49 @@
{{ fullname | escape | underline }}

..
Custom formatting of module doc layout
https://stackoverflow.com/questions/48074094/use-sphinx-autosummary-recursively-to-generate-api-documentation
TODO: how can we add the documented module attribuets (constants, ...)?
.. rubric:: Description

.. automodule:: {{ fullname }}

.. currentmodule:: {{ fullname }}


{% if classes %}
.. rubric:: Classes

.. autosummary::
:toctree: .

{% for class in classes %}
{{ class }}
{% for item in classes %}
{{ item }}
{% endfor %}

{% endif %}


{% if functions %}
.. rubric:: Functions

.. autosummary::
:toctree: .
{% for function in functions %}
{{ function }}
{% for item in functions %}
{{ item }}
{% endfor %}

{% endif %}


{% if exceptions %}
.. rubric:: Exceptions

.. autosummary::
:toctree: .
{% for item in exceptions %}
{{ item }}
{% endfor %}

{% endif %}
2 changes: 1 addition & 1 deletion doc/sphinx/reference_guide_architecture.rst
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ interface is implemented.
Applications
============

.. inheritance-diagram:: wsgidav.middleware wsgidav.dir_browser wsgidav.debug_filter wsgidav.dav_error wsgidav.error_printer wsgidav.rw_lock wsgidav.wsgidav_app wsgidav.request_server wsgidav.request_resolver
.. inheritance-diagram:: wsgidav.middleware wsgidav.dir_browser wsgidav.debug_filter wsgidav.dav_error wsgidav.error_printer wsgidav.http_authenticator wsgidav.rw_lock wsgidav.wsgidav_app wsgidav.request_server wsgidav.request_resolver
:parts: 2
:private-bases:

Expand Down
16 changes: 6 additions & 10 deletions doc/sphinx/user_guide_configure.rst
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,13 @@ The options described below can be defined for the CLI either
Verbosity Level
---------------

.. todo:: TODO
The verbosity level can have a value from 0 to 3::

..
The verbosity level can have a value from 0 to 6::
0: quiet
1: show errors only
2: show conflicts and 1 line summary only
3: show write operations
4: show equal files
5: diff-info and benchmark summary
0 - no output (excepting application exceptions)
1 - show single line request summaries (for HTTP logging)
2 - show additional events
3 - show full request/response header info (HTTP Logging)
request body and GET response bodies not shown


Sample ``wsgidav.conf``
Expand Down
1 change: 1 addition & 0 deletions doc/sphinx/user_guide_lib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ and replaced like so::
set_wsgidav_logger(custom_logger)



.. note::

The CLI calls ``set_wsgidav_logger(None)`` on startup, so it logs to stdout
Expand Down
75 changes: 52 additions & 23 deletions tests/test_logging
Original file line number Diff line number Diff line change
@@ -1,31 +1,60 @@
import logging

# _logger = logging.getLogger("wsgidav")
_logger = logging.getLogger(__name__)
logger = logging.getLogger("wsgidav")

# _logger = logging.getLogger(__name__)

# logging.basicConfig(level=logging.DEBUG,
# format='%(asctime)s %(name)-15s %(levelname)-8s %(message)s',
# # datefmt='%Y-%m-%d %H:%M:%S',
# )

_logger.addHandler(logging.NullHandler())
_logger2 = logging.getLogger("wsgidav.server")


def test_logger(logger, msg=""):
logger.debug("Debug {}".format(msg))
logger.info("Info {}".format(msg))
logger.warn("Warn {}".format(msg))
logger.error("Error {}".format(msg))


def setLogger():
pass

test_logger(_logger, "1")
test_logger(_logger2, "2")

_logger.setLevel(logging.WARN)
test_logger(_logger, "1w")
test_logger(_logger2, "2w")

# _logger.addHandler(logging.NullHandler())
# _logger2 = logging.getLogger("wsgidav.server")
#
#
# def test_logger(logger, msg=""):
# logger.debug("Debug {}".format(msg))
# logger.info("Info {}".format(msg))
# logger.warn("Warn {}".format(msg))
# logger.error("Error {}".format(msg))
#
#
# def setLogger():
# pass
#
# test_logger(_logger, "1")
# test_logger(_logger2, "2")
#
# _logger.setLevel(logging.WARN)
# test_logger(_logger, "1w")
# test_logger(_logger2, "2w")

import sys
from cheroot import wsgi

from wsgidav.wsgidav_app import DEFAULT_CONFIG, WsgiDAVApp
from wsgidav.fs_dav_provider import FilesystemProvider

provider = FilesystemProvider("/Users/martin/pub")
config = DEFAULT_CONFIG.copy()
config.update({
"host": "0.0.0.0",
"port": 8080,
# "mount_path": "/dav",
"provider_mapping": {"/": provider},
"verbose": 3,
})

app = WsgiDAVApp(config)

server_args = {
"bind_addr": (config["host"], config["port"]),
"wsgi_app": app,
}
server = wsgi.Server(**server_args)
try:
server.start()
except KeyboardInterrupt:
print("END?")
sys.exit(1)
6 changes: 4 additions & 2 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def setUp(self):
rootLogger.addHandler(self.logHandler)

def tearDown(self):
rootLogger = logging.getLoggxer()
rootLogger = logging.getLogger()
rootLogger.setLevel(self.prevLogLevel)
rootLogger.removeHandler(self.logHandler)

Expand All @@ -120,7 +120,9 @@ def testLogging(self):
print(output)

assert "# Log output buffer start" in output
assert False

# assert False

# Create and use a custom logger
# custom_logger = wsgidav.getLogger("wsgidav_test")
# log_path = os.path.join(PYFTPSYNC_TEST_FOLDER, "pyftpsync.log")
Expand Down
1 change: 1 addition & 0 deletions wsgidav/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@

# Initialize a silent 'wsgidav' logger
# http://docs.python-guide.org/en/latest/writing/logging/#logging-in-a-library
# https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library
import logging
logging.getLogger(__name__).addHandler(logging.NullHandler())
2 changes: 1 addition & 1 deletion wsgidav/addons/stream_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def write(self, chunk):
self.queue.put(o)

def close(self):
print("FileLikeQueue.close()")
# print("FileLikeQueue.close()")
self.is_closed = True

# TODO: we may also implement iterator functionality, but this should be
Expand Down
31 changes: 17 additions & 14 deletions wsgidav/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@

__docformat__ = "reStructuredText"


#: True if we are running on Python 2.x
PY2 = sys.version_info < (3, 0)

#: True if we are running on Python 3
PY3 = not PY2

_filesystemencoding = sys.getfilesystemencoding()


Expand Down Expand Up @@ -55,34 +58,34 @@
from cgi import escape as html_escape

def is_basestring(s):
"""Return True for any string type, i.e. for str/unicode on Py2 and bytes/str on Py3."""
"""Return True for any string type (for str/unicode on Py2 and bytes/str on Py3)."""
return isinstance(s, basestring)

def is_bytes(s):
"""Return True for bytestrings, i.e. for str on Py2 and bytes on Py3."""
"""Return True for bytestrings (for str on Py2 and bytes on Py3)."""
return isinstance(s, str)

def is_native(s):
"""Return True for native strings, i.e. for str on Py2 and Py3."""
"""Return True for native strings (for str on Py2 and Py3)."""
return isinstance(s, str)

def is_unicode(s):
"""Return True for unicode strings, i.e. for unicode on Py2 and str on Py3."""
"""Return True for unicode strings (for unicode on Py2 and str on Py3)."""
return isinstance(s, unicode)

def to_bytes(s, encoding="utf8"):
"""Convert unicode (text strings) to binary data, i.e. str on Py2 and bytes on Py3."""
"""Convert unicode (text strings) to binary data (str on Py2 and bytes on Py3)."""
if type(s) is unicode:
s = s.encode(encoding)
elif type(s) is not str:
s = str(s)
return s

to_native = to_bytes
"""Convert data to native str type, i.e. bytestring on Py2 and unicode on Py3."""
"""Convert data to native str type (bytestring on Py2 and unicode on Py3)."""

def to_unicode(s, encoding="utf8"):
"""Convert data to unicode text, i.e. unicode on Py2 and str on Py3."""
"""Convert data to unicode text (unicode on Py2 and str on Py3)."""
if type(s) is not unicode:
s = unicode(s, encoding)
return s
Expand All @@ -94,29 +97,29 @@ def to_unicode(s, encoding="utf8"):
from html import escape as html_escape

def is_basestring(s):
"""Return True for any string type, i.e. for str/unicode on Py2 and bytes/str on Py3."""
"""Return True for any string type (for str/unicode on Py2 and bytes/str on Py3)."""
return isinstance(s, (str, bytes))

def is_bytes(s):
"""Return True for bytestrings, i.e. for str on Py2 and bytes on Py3."""
"""Return True for bytestrings (for str on Py2 and bytes on Py3)."""
return isinstance(s, bytes)

def is_native(s):
"""Return True for native strings, i.e. for str on Py2 and Py3."""
"""Return True for native strings (for str on Py2 and Py3)."""
return isinstance(s, str)

def is_unicode(s):
"""Return True for unicode strings, i.e. for unicode on Py2 and str on Py3."""
"""Return True for unicode strings (for unicode on Py2 and str on Py3)."""
return isinstance(s, str)

def to_bytes(s, encoding="utf8"):
"""Convert a text string (unicode) to bytestring, i.e. str on Py2 and bytes on Py3."""
"""Convert a text string (unicode) to bytestring (str on Py2 and bytes on Py3)."""
if type(s) is not bytes:
s = bytes(s, encoding)
return s

def to_native(s, encoding="utf8"):
"""Convert data to native str type, i.e. bytestring on Py2 and unicode on Py3."""
"""Convert data to native str type (bytestring on Py2 and unicode on Py3)."""
# print("to_native", s)
if type(s) is bytes:
s = str(s, encoding)
Expand Down
18 changes: 6 additions & 12 deletions wsgidav/dav_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
from wsgidav import __version__, compat, xml_tools
from wsgidav.xml_tools import etree # @UnusedImport

if False:
from xml.etree import ElementTree as etree # @Reimport @UnresolvedImport

__docformat__ = "reStructuredText"

Expand Down Expand Up @@ -130,7 +128,11 @@


class DAVErrorCondition(object):
"""May be embedded in :class:`DAVError` instances to store additional data.
Args:
conditionCode (str): Should be PRECONDITION_CODE_...
"""
def __init__(self, conditionCode):
self.conditionCode = conditionCode
self.hrefs = []
Expand Down Expand Up @@ -167,6 +169,7 @@ def as_string(self):
# you want (or you can catch an abstract superclass to get any of them)

class DAVError(Exception):
"""General error class that is used to signal HTTP and WEBDAV errors."""
# TODO: Ian Bicking proposed to add an additional 'comment' arg, but
# couldn't we use the existing 'contextinfo'?
# @@: This should also take some message value, for a detailed error message.
Expand Down Expand Up @@ -276,16 +279,7 @@ def asDAVError(e):
if isinstance(e, DAVError):
return e
elif isinstance(e, Exception):
# print >>sys.stderr, "asDAVError: %s" % e
# traceback.print_exception(type(e), e)
traceback.print_exc()
# traceback.print_exc()
return DAVError(HTTP_INTERNAL_ERROR, srcexception=e)
else:
return DAVError(HTTP_INTERNAL_ERROR, "%s" % e)


if __name__ == "__main__":
dec = DAVErrorCondition(PRECONDITION_CODE_LockConflict)
print(dec.as_string())
dec.add_href("/dav/a")
print(dec.as_string())
4 changes: 3 additions & 1 deletion wsgidav/debug_filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
Configured like::
debug_methods = ["PROPPATCH", "PROPFIND", "GET", "HEAD", "DELETE",
debug_methods = ["PROPPATCH", "PROPFIND", "GET", "HEAD", "DELET E",
"PUT", "COPY", "MOVE", "LOCK", "UNLOCK",
]
Expand All @@ -62,6 +62,8 @@

__docformat__ = "reStructuredText"

logger = util.getModuleLogger(__name__)


class WsgiDavDebugFilter(BaseMiddleware):

Expand Down
2 changes: 1 addition & 1 deletion wsgidav/http_authenticator.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def __call__(self, environ, start_response):
elif self._acceptbasic:
return self.sendBasicAuthResponse(environ, start_response)

util.log(
_logger.warn(
"HTTPAuthenticator: respond with 400 Bad request; Auth-Method: %s" % authmethod)

start_response("400 Bad Request", [("Content-Length", "0"),
Expand Down
Loading

0 comments on commit d79fe14

Please sign in to comment.