aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorWaylan Limberg <waylan@gmail.com>2011-04-28 22:22:32 -0400
committerWaylan Limberg <waylan@gmail.com>2011-04-28 22:22:32 -0400
commit08b9b6f879ad81f296abb22b3752a3092b57ee03 (patch)
tree75c506145cc0238866a3ea57a3ecb890f4a98f31
parent51afaf9a75d06a6ef632ca33ec317d1c023607fe (diff)
parent31ba5bec2170fff6cbf32eb6fb6c1e7782428f9d (diff)
downloadmarkdown-08b9b6f879ad81f296abb22b3752a3092b57ee03.tar.gz
markdown-08b9b6f879ad81f296abb22b3752a3092b57ee03.tar.bz2
markdown-08b9b6f879ad81f296abb22b3752a3092b57ee03.zip
Clean up merge of logging
-rw-r--r--markdown/__init__.py39
-rw-r--r--markdown/blockprocessors.py7
-rw-r--r--markdown/commandline.py9
-rw-r--r--markdown/etree_loader.py12
-rw-r--r--markdown/extensions/__init__.py3
-rw-r--r--markdown/extensions/headerid.py7
-rw-r--r--markdown/md_logging.py36
-rw-r--r--tests/test_apis.py27
8 files changed, 42 insertions, 98 deletions
diff --git a/markdown/__init__.py b/markdown/__init__.py
index 0774174..2bc7061 100644
--- a/markdown/__init__.py
+++ b/markdown/__init__.py
@@ -35,8 +35,7 @@ version_info = (2,1,0, "Dev")
import re
import codecs
-from logging import DEBUG, INFO, WARN, ERROR, CRITICAL
-from md_logging import message
+import logging
import util
from preprocessors import build_preprocessors
from blockprocessors import build_block_parser
@@ -51,6 +50,8 @@ import html4
# party code might need to access them here.
from util import *
+logger = logging.getLogger('MARKDOWN')
+
class Markdown:
"""Convert Markdown to HTML."""
@@ -139,13 +140,10 @@ class Markdown:
if isinstance(ext, basestring):
ext = self.build_extension(ext, configs.get(ext, []))
if isinstance(ext, Extension):
- try:
- ext.extendMarkdown(self, globals())
- except NotImplementedError, e:
- message(ERROR, e)
+ # might raise NotImplementedError, but that's the extension author's problem
+ ext.extendMarkdown(self, globals())
else:
- message(ERROR,
- 'Extension "%s.%s" must be of type: "markdown.Extension".' \
+ raise ValueError('Extension "%s.%s" must be of type: "markdown.Extension".' \
% (ext.__class__.__module__, ext.__class__.__name__))
return self
@@ -179,17 +177,18 @@ class Markdown:
try: # Old style (mdx_<extension>)
module = __import__(module_name_old_style)
except ImportError:
- message(WARN, "Failed loading extension '%s' from '%s' or '%s'"
- % (ext_name, module_name_new_style, module_name_old_style))
- # Return None so we don't try to initiate none-existant extension
- return None
+ logger.warn("Failed loading extension '%s' from '%s' or '%s'"
+ % (ext_name, module_name_new_style, module_name_old_style))
+ # Return None so we don't try to initiate none-existant extension
+ return None
# If the module is loaded successfully, we expect it to define a
# function called makeExtension()
try:
return module.makeExtension(configs.items())
except AttributeError, e:
- message(CRITICAL, "Failed to initiate extension '%s': %s" % (ext_name, e))
+ logger.warn("Failed to initiate extension '%s': %s" % (ext_name, e))
+ return None
def registerExtension(self, extension):
""" This gets called by the extension """
@@ -214,8 +213,7 @@ class Markdown:
try:
self.serializer = self.output_formats[format.lower()]
except KeyError:
- message(CRITICAL,
- 'Invalid Output Format: "%s". Use one of %s.' \
+ raise KeyError('Invalid Output Format: "%s". Use one of %s.' \
% (format, self.output_formats.keys()))
return self
@@ -244,12 +242,13 @@ class Markdown:
# Fixup the source text
if not source.strip():
return u"" # a blank unicode string
+
try:
source = unicode(source)
- except UnicodeDecodeError:
- message(CRITICAL,
- 'UnicodeDecodeError: Markdown only accepts unicode or ascii input.')
- return u""
+ except UnicodeDecodeError, e:
+ # Customise error message while maintaining original trackback
+ e.reason += '. -- Note: Markdown only accepts unicode input!'
+ raise
source = source.replace(util.STX, "").replace(util.ETX, "")
source = source.replace("\r\n", "\n").replace("\r", "\n") + "\n\n"
@@ -283,7 +282,7 @@ class Markdown:
output = ''
else:
# We have a serious problem
- message(CRITICAL, 'Failed to strip top level tags.')
+ raise ValueError('Markdown failed to strip top-level tags. Document=%r' % output.strip())
# Run the text post-processors
for pp in self.postprocessors.values():
diff --git a/markdown/blockprocessors.py b/markdown/blockprocessors.py
index 77fbc71..2f15578 100644
--- a/markdown/blockprocessors.py
+++ b/markdown/blockprocessors.py
@@ -12,11 +12,12 @@ as they need to alter how markdown blocks are parsed.
"""
+import logging
import re
import util
from blockparser import BlockParser
-from logging import CRITICAL
-from md_logging import message
+
+logger = logging.getLogger('MARKDOWN')
def build_block_parser(md_instance, **kwargs):
@@ -408,7 +409,7 @@ class HashHeaderProcessor(BlockProcessor):
blocks.insert(0, after)
else:
# This should never happen, but just in case...
- message(CRITICAL, "We've got a problem header!")
+ logger.warn("We've got a problem header: %r" % block)
class SetextHeaderProcessor(BlockProcessor):
diff --git a/markdown/commandline.py b/markdown/commandline.py
index 049d2be..3f2e009 100644
--- a/markdown/commandline.py
+++ b/markdown/commandline.py
@@ -7,8 +7,11 @@ COMMAND-LINE SPECIFIC STUFF
import markdown
import sys
import optparse
+
import logging
-from logging import DEBUG, INFO, WARN, ERROR, CRITICAL
+from logging import DEBUG, INFO, CRITICAL
+
+logger = logging.getLogger('MARKDOWN')
# default logging level for command-line use
COMMAND_LINE_LOGGING_LEVEL = CRITICAL
@@ -69,8 +72,8 @@ def run():
# Parse options and adjust logging level if necessary
options, logging_level = parse_options()
- if not options: sys.exit(0)
- if logging_level: logging.getLogger('MARKDOWN').setLevel(logging_level)
+ if not options: sys.exit(2)
+ if logging_level: logger.setLevel(logging_level)
# Run
markdown.markdownFromFile(**options)
diff --git a/markdown/etree_loader.py b/markdown/etree_loader.py
index e1edcc3..f605aa2 100644
--- a/markdown/etree_loader.py
+++ b/markdown/etree_loader.py
@@ -1,6 +1,3 @@
-from logging import CRITICAL
-from md_logging import message
-import sys
## Import
def importETree():
@@ -20,18 +17,15 @@ def importETree():
try: # An earlier version of Python with Python ElementTree?
import elementtree.ElementTree as etree
except ImportError:
- message(CRITICAL, "Failed to import ElementTree")
- sys.exit(1)
+ raise ImportError("Failed to import ElementTree")
if etree_in_c:
if etree_in_c.VERSION < "1.0.5":
- message(CRITICAL, "cElementTree version 1.0.5 or higher is required.")
- sys.exit(1)
+ raise RuntimeError("cElementTree version 1.0.5 or higher is required.")
# Third party serializers (including ours) test with non-c Comment
etree_in_c.test_comment = Comment
return etree_in_c
elif etree.VERSION < "1.1":
- message(CRITICAL, "ElementTree version 1.1 or higher is required")
- sys.exit(1)
+ raise RuntimeError("ElementTree version 1.1 or higher is required")
else:
return etree
diff --git a/markdown/extensions/__init__.py b/markdown/extensions/__init__.py
index 1cc4762..4c1dcba 100644
--- a/markdown/extensions/__init__.py
+++ b/markdown/extensions/__init__.py
@@ -1,6 +1,3 @@
-from markdown.md_logging import message
-from logging import DEBUG, INFO, WARN, ERROR, CRITICAL
-
"""
Extensions
-----------------------------------------------------------------------------
diff --git a/markdown/extensions/headerid.py b/markdown/extensions/headerid.py
index 5e9793e..390a8ba 100644
--- a/markdown/extensions/headerid.py
+++ b/markdown/extensions/headerid.py
@@ -67,10 +67,11 @@ Dependencies:
import markdown
from markdown.util import etree
-from logging import CRITICAL
-from markdown.md_logging import message
import re
from string import ascii_lowercase, digits, punctuation
+import logging
+
+logger = logging.getLogger('MARKDOWN')
ID_CHARS = ascii_lowercase + digits + '-_'
IDCOUNT_RE = re.compile(r'^(.*)_([0-9]+)$')
@@ -121,7 +122,7 @@ class HeaderIdProcessor(markdown.blockprocessors.BlockProcessor):
blocks.insert(0, after)
else:
# This should never happen, but just in case...
- message(CRITICAL, "We've got a problem header!")
+ logger.warn("We've got a problem header: %r" % block)
def _get_meta(self):
""" Return meta data suported by this ext as a tuple """
diff --git a/markdown/md_logging.py b/markdown/md_logging.py
deleted file mode 100644
index 463be15..0000000
--- a/markdown/md_logging.py
+++ /dev/null
@@ -1,36 +0,0 @@
-# -*- coding: utf-8 -*-
-import logging
-from logging import DEBUG, INFO, WARN, ERROR, CRITICAL
-import sys
-import warnings
-
-#
-# Exceptions
-#
-
-class MarkdownException(Exception):
- """ A Markdown Exception. """
- pass
-
-
-class MarkdownWarning(Warning):
- """ A Markdown Warning. """
- pass
-
-
-#
-# Global functions
-#
-
-def message(level, text):
- """ A wrapper method for logging debug messages. """
- logger = logging.getLogger('MARKDOWN')
- if logger.handlers:
- # The logger is configured
- logger.log(level, text)
- if level > WARN:
- sys.exit(0)
- elif level > WARN:
- raise MarkdownException, text
- else:
- warnings.warn(text, MarkdownWarning) \ No newline at end of file
diff --git a/tests/test_apis.py b/tests/test_apis.py
index ebbc24f..eecfbf6 100644
--- a/tests/test_apis.py
+++ b/tests/test_apis.py
@@ -13,8 +13,6 @@ import os
import sys
import types
import markdown
-from markdown.md_logging import MarkdownException, MarkdownWarning
-from logging import DEBUG, INFO, WARN, ERROR, CRITICAL
import warnings
class TestMarkdownBasics(unittest.TestCase):
@@ -226,47 +224,34 @@ class TestErrors(unittest.TestCase):
# Reset warning behavior back to default
warnings.simplefilter('default')
- def testMessageWarn(self):
- """ Test message WARN. """
- self.assertRaises(MarkdownWarning, markdown.md_logging.message,
- WARN, 'This should raise a MardownWarning')
-
- def testMessageError(self):
- """ Test message ERROR. """
- self.assertRaises(MarkdownException, markdown.md_logging.message,
- ERROR, 'This should raise a MarkdownException')
-
def testNonUnicodeSource(self):
""" Test falure on non-unicode source text. """
source = "foo".encode('utf-16')
- self.assertRaises(MarkdownException, markdown.markdown, source)
+ self.assertRaises(UnicodeDecodeError, markdown.markdown, source)
def testBadOutputFormat(self):
""" Test failure on bad output_format. """
- self.assertRaises(MarkdownException,
- markdown.Markdown, output_format='invalid')
+ self.assertRaises(KeyError, markdown.Markdown, output_format='invalid')
def testLoadExtensionFailure(self):
""" Test failure of an extension to load. """
- self.assertRaises(MarkdownWarning,
+ self.assertRaises(ValueError,
markdown.Markdown, extensions=['non_existant_ext'])
def testLoadBadExtension(self):
""" Test loading of an Extension with no makeExtension function. """
_create_fake_extension(name='fake', has_factory_func=False)
- self.assertRaises(MarkdownException,
- markdown.Markdown, extensions=['fake'])
+ self.assertRaises(ValueError, markdown.Markdown, extensions=['fake'])
def testNonExtension(self):
""" Test loading a non Extension object as an extension. """
_create_fake_extension(name='fake', is_wrong_type=True)
- self.assertRaises(MarkdownException,
- markdown.Markdown, extensions=['fake'])
+ self.assertRaises(ValueError, markdown.Markdown, extensions=['fake'])
def testBaseExtention(self):
""" Test that the base Extension class will raise NotImplemented. """
_create_fake_extension(name='fake')
- self.assertRaises(MarkdownException,
+ self.assertRaises(NotImplementedError,
markdown.Markdown, extensions=['fake'])