diff --git a/README.md b/README.md index 0a42a45c..1b513c2a 100644 --- a/README.md +++ b/README.md @@ -127,19 +127,19 @@ Map Tile Service (WMTS). Some of those are beta quality. Logging ------- -OWSLib logs messages to the 'owslib' named Python logger. You may +OWSLib logs messages to module-based named Python loggers. You may configure your application to use the log messages like so: ```python >>> import logging - >>> owslib_log = logging.getLogger('owslib') + >>> LOGGER = logging.getLogger(__name__) >>> # Add formatting and handlers as needed, for example to log to the console >>> ch = logging.StreamHandler() >>> ch.setLevel(logging.DEBUG) >>> ch.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) >>> # add the handler to the logger - >>> owslib_log.addHandler(ch) - >>> owslib_log.setLevel(logging.DEBUG) + >>> LOGGER.addHandler(ch) + >>> LOGGER.setLevel(logging.DEBUG) ``` Releasing diff --git a/owslib/coverage/wcs100.py b/owslib/coverage/wcs100.py index cfdc6627..f826d696 100644 --- a/owslib/coverage/wcs100.py +++ b/owslib/coverage/wcs100.py @@ -3,21 +3,23 @@ # Copyright (c) 2004, 2006 Sean C. Gillies # Copyright (c) 2007 STFC # -# Authors : +# Authors: # Dominic Lowe # # Contact email: d.lowe@rl.ac.uk # ============================================================================= -from owslib.coverage.wcsBase import WCSBase, WCSCapabilitiesReader, ServiceException -from urllib.parse import urlencode -from owslib.util import openURL, testXMLValue -from owslib.etree import etree -from owslib.crs import Crs import os import errno +import logging +from urllib.parse import urlencode + +from owslib.coverage.wcsBase import WCSBase, WCSCapabilitiesReader, ServiceException +from owslib.crs import Crs +from owslib.etree import etree +from owslib.util import makeString, openURL, testXMLValue -from owslib.util import log, makeString +LOGGER = logging.getLogger(__name__) # function to save writing out WCS namespace in full each time @@ -108,7 +110,7 @@ def getCoverage(self, identifier=None, bbox=None, time=None, format=None, crs=No """ msg = 'WCS 1.0.0 DEBUG: Parameters passed to GetCoverage: identifier={}, bbox={}, time={}, format={}, crs={}, width={}, height={}, resx={}, resy={}, resz={}, parameter={}, method={}, other_arguments={}' # noqa - log.debug(msg.format( + LOGGER.debug(msg.format( identifier, bbox, time, format, crs, width, height, resx, resy, resz, parameter, method, str(kwargs))) try: @@ -117,7 +119,7 @@ def getCoverage(self, identifier=None, bbox=None, time=None, format=None, crs=No except StopIteration: base_url = self.url - log.debug('WCS 1.0.0 DEBUG: base url of server: %s' % base_url) + LOGGER.debug('WCS 1.0.0 DEBUG: base url of server: %s' % base_url) # process kwargs request = {'version': self.version, 'request': 'GetCoverage', 'service': 'WCS'} @@ -151,7 +153,7 @@ def getCoverage(self, identifier=None, bbox=None, time=None, format=None, crs=No # encode and request data = urlencode(request) - log.debug('WCS 1.0.0 DEBUG: Second part of URL: %s' % data) + LOGGER.debug('WCS 1.0.0 DEBUG: Second part of URL: %s' % data) u = openURL(base_url, data, method, self.cookies, auth=self.auth, timeout=timeout, headers=self.headers) return u diff --git a/owslib/coverage/wcs110.py b/owslib/coverage/wcs110.py index 451a1505..d9e5ffd0 100644 --- a/owslib/coverage/wcs110.py +++ b/owslib/coverage/wcs110.py @@ -3,7 +3,7 @@ # Copyright (c) 2004, 2006 Sean C. Gillies # Copyright (c) 2007 STFC # -# Authors : +# Authors: # Dominic Lowe # # Contact email: d.lowe@rl.ac.uk @@ -11,18 +11,18 @@ # NOTE: Does not conform to new interfaces yet ################# -from .wcsBase import WCSBase, WCSCapabilitiesReader, ServiceException -from owslib.util import openURL, testXMLValue +import errno +import logging +import os from urllib.parse import urlencode + +from .wcsBase import WCSBase, WCSCapabilitiesReader, ServiceException from owslib.etree import etree -import os -import errno from owslib.coverage import wcsdecoder from owslib.crs import Crs +from owslib.util import openURL, testXMLValue -import logging -from owslib.util import log - +LOGGER = logging.getLogger(__name__) class Namespaces_1_1_0(): @@ -157,7 +157,7 @@ def getCoverage(self, identifier=None, bbox=None, time=None, format=None, store= if store = false, returns a multipart mime """ msg = 'WCS 1.1.0 DEBUG: Parameters passed to GetCoverage: identifier={}, bbox={}, time={}, format={}, rangesubset={}, gridbaseCRS={}, gridtype={}, gridCS={}, gridorigin={}, gridoffsets={}, method={}, other_arguments={}' # noqa - log.debug(msg.format( + LOGGER.debug(msg.format( identifier, bbox, time, format, rangesubset, gridbaseCRS, gridtype, gridCS, gridorigin, gridoffsets, method, str(kwargs))) diff --git a/owslib/coverage/wcs200.py b/owslib/coverage/wcs200.py index b48d7f9a..b04bbcd5 100644 --- a/owslib/coverage/wcs200.py +++ b/owslib/coverage/wcs200.py @@ -3,7 +3,7 @@ # Copyright (c) 2004, 2006 Sean C. Gillies # Copyright (c) 2007 STFC # -# Authors : +# Authors: # Oliver Clements # # Contact email: olcl@pml.ac.uk @@ -11,25 +11,26 @@ # !!! NOTE: Does not conform to new interfaces yet ################# +from datetime import timedelta +import errno +import logging +import os +from urllib.parse import urlencode + +import dateutil.parser as parser from owslib.coverage.wcsBase import WCSBase, WCSCapabilitiesReader, ServiceException +from owslib.crs import Crs +from owslib.etree import etree from owslib.ows import ( OwsCommon, ServiceIdentification, ServiceProvider, - OperationsMetadata, + OperationsMetadata ) +from owslib.util import datetime_from_ansi, datetime_from_iso, openURL, param_list_to_url_string, testXMLValue -from urllib.parse import urlencode -from owslib.util import openURL, testXMLValue -from owslib.etree import etree -from owslib.crs import Crs -import os -import errno -import dateutil.parser as parser -from datetime import timedelta -import logging -from owslib.util import log, datetime_from_ansi, datetime_from_iso, param_list_to_url_string +LOGGER = logging.getLogger(__name__) # function to save writing out WCS namespace in full each time @@ -153,7 +154,7 @@ def getCoverage( """ - log.debug( + LOGGER.debug( "WCS 2.0.0 DEBUG: Parameters passed to GetCoverage: identifier=%s, bbox=%s, time=%s, format=%s, crs=%s, width=%s, height=%s, resx=%s, resy=%s, resz=%s, parameter=%s, method=%s, other_arguments=%s" # noqa % ( identifier, @@ -183,7 +184,7 @@ def getCoverage( except StopIteration: base_url = self.url - log.debug("WCS 2.0.0 DEBUG: base url of server: %s" % base_url) + LOGGER.debug("WCS 2.0.0 DEBUG: base url of server: %s" % base_url) request = {"version": self.version, "request": "GetCoverage", "service": "WCS"} assert len(identifier) > 0 @@ -207,12 +208,12 @@ def getCoverage( if subsets: data += param_list_to_url_string(subsets, 'subset') if resolutions: - log.debug('Adding vendor-specific RESOLUTION parameter.') + LOGGER.debug('Adding vendor-specific RESOLUTION parameter.') data += param_list_to_url_string(resolutions, 'resolution') if sizes: - log.debug('Adding vendor-specific SIZE parameter.') + LOGGER.debug('Adding vendor-specific SIZE parameter.') data += param_list_to_url_string(sizes, 'size') - log.debug("WCS 2.0.0 DEBUG: Second part of URL: %s" % data) + LOGGER.debug("WCS 2.0.0 DEBUG: Second part of URL: %s" % data) u = openURL(base_url, data, method, self.cookies, auth=self.auth, timeout=timeout, headers=self.headers) return u diff --git a/owslib/coverage/wcs201.py b/owslib/coverage/wcs201.py index d26155ed..d720ec5d 100644 --- a/owslib/coverage/wcs201.py +++ b/owslib/coverage/wcs201.py @@ -3,7 +3,7 @@ # Copyright (c) 2004, 2006 Sean C. Gillies # Copyright (c) 2007 STFC # -# Authors : +# Authors: # Oliver Clements # # Contact email: olcl@pml.ac.uk @@ -11,25 +11,24 @@ # !!! NOTE: Does not conform to new interfaces yet ################# +import os +from datetime import timedelta +import errno +import logging +from urllib.parse import urlencode + +import dateutil.parser as parser from owslib.coverage.wcsBase import WCSBase, WCSCapabilitiesReader, ServiceException +from owslib.etree import etree +from owslib.crs import Crs from owslib.ows import ( OwsCommon, ServiceIdentification, ServiceProvider, - OperationsMetadata, + OperationsMetadata ) - -from urllib.parse import urlencode -from owslib.util import openURL, testXMLValue -from owslib.etree import etree -from owslib.crs import Crs -import os -import errno -import dateutil.parser as parser -from datetime import timedelta -import logging -from owslib.util import log, datetime_from_ansi, datetime_from_iso, param_list_to_url_string +from owslib.util import datetime_from_ansi, datetime_from_iso, openURL, param_list_to_url_string, testXMLValue # function to save writing out WCS namespace in full each time @@ -153,7 +152,7 @@ def getCoverage( """ - log.debug( + LOGGER.debug( "WCS 2.0.1 DEBUG: Parameters passed to GetCoverage: identifier=%s, bbox=%s, time=%s, format=%s, crs=%s, width=%s, height=%s, resx=%s, resy=%s, resz=%s, parameter=%s, method=%s, other_arguments=%s" # noqa % ( identifier, @@ -183,7 +182,7 @@ def getCoverage( except StopIteration: base_url = self.url - log.debug("WCS 2.0.1 DEBUG: base url of server: %s" % base_url) + LOGGER.debug("WCS 2.0.1 DEBUG: base url of server: %s" % base_url) request = {"version": self.version, "request": "GetCoverage", "service": "WCS"} assert len(identifier) > 0 @@ -207,13 +206,13 @@ def getCoverage( if subsets: data += param_list_to_url_string(subsets, 'subset') if resolutions: - log.debug('Adding vendor-specific RESOLUTION parameter.') + LOGGER.debug('Adding vendor-specific RESOLUTION parameter.') data += param_list_to_url_string(resolutions, 'resolution') if sizes: - log.debug('Adding vendor-specific SIZE parameter.') + LOGGER.debug('Adding vendor-specific SIZE parameter.') data += param_list_to_url_string(sizes, 'size') - log.debug("WCS 2.0.1 DEBUG: Second part of URL: %s" % data) + LOGGER.debug("WCS 2.0.1 DEBUG: Second part of URL: %s" % data) u = openURL(base_url, data, method, self.cookies, auth=self.auth, timeout=timeout, headers=self.headers) return u diff --git a/owslib/feature/__init__.py b/owslib/feature/__init__.py index d6e7866d..9f3de0f1 100644 --- a/owslib/feature/__init__.py +++ b/owslib/feature/__init__.py @@ -5,12 +5,16 @@ # # ============================================================================= +import logging + from urllib.parse import urlencode from owslib.crs import Crs -from owslib.util import log, Authentication +from owslib.util import Authentication from owslib.feature.schema import get_schema from owslib.feature.postrequest import PostRequest_1_1_0, PostRequest_2_0_0 +LOGGER = logging.getLogger(__name__) + class WebFeatureService_(object): """Base class for WebFeatureService implementations""" @@ -137,7 +141,7 @@ def getSRS(self, srsname, typename): return self.contents[typename].crsOptions[index] except ValueError: options = ", ".join([crs.id for crs in self.contents[typename].crsOptions]) - log.warning( + LOGGER.warning( "Requested srsName %r is not declared as being " "allowed for requested typename %r. " "Options are: %r.", @@ -326,7 +330,7 @@ def getPOSTGetFeatureRequest( if storedQueryID: if self.version in ["1.0.0", "1.1.0"]: - log.warning("Stored queries are only supported in version 2.0.0 and above.") + LOGGER.warning("Stored queries are only supported in version 2.0.0 and above.") return None storedQueryParams = storedQueryParams or {} diff --git a/owslib/feature/wfs100.py b/owslib/feature/wfs100.py index 0484affd..f3c8ca04 100644 --- a/owslib/feature/wfs100.py +++ b/owslib/feature/wfs100.py @@ -6,21 +6,19 @@ # $Id: wfs.py 503 2006-02-01 17:09:12Z dokai $ # ============================================================================= +from io import BytesIO import itertools import logging - -from owslib import util - -from io import BytesIO from urllib.parse import urlencode + from owslib.util import ( + nspath_eval, testXMLValue, extract_xml_list, ServiceException, xmltag_split, Authentication, - openURL, - log, + openURL ) from owslib.etree import etree from owslib.fgdc import Metadata @@ -296,7 +294,7 @@ def getfeature( request["outputFormat"] = outputFormat data = urlencode(request) - log.debug("Making request: %s?%s" % (base_url, data)) + LOGGER.debug("Making request: %s?%s" % (base_url, data)) u = openURL(base_url, data, method, timeout=self.timeout, headers=self.headers, auth=self.auth) @@ -464,9 +462,9 @@ def parse_remote_metadata(self, timeout=30): metadataUrl["metadata"] = None elif metadataUrl["type"] == "TC211": mdelem = doc.find( - ".//" + util.nspath_eval("gmd:MD_Metadata", n.get_namespaces(["gmd"])) + ".//" + nspath_eval("gmd:MD_Metadata", n.get_namespaces(["gmd"])) ) or doc.find( - ".//" + util.nspath_eval("gmi:MI_Metadata", n.get_namespaces(["gmi"])) + ".//" + nspath_eval("gmi:MI_Metadata", n.get_namespaces(["gmi"])) ) if mdelem is not None: metadataUrl["metadata"] = MD_Metadata(mdelem) diff --git a/owslib/feature/wfs110.py b/owslib/feature/wfs110.py index ab28e922..92066e20 100644 --- a/owslib/feature/wfs110.py +++ b/owslib/feature/wfs110.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # ============================================================================= -# Copyright (c) 2011 Tom Kralidis +# Copyright (c) 2024 Tom Kralidis # # Authors : Tom Kralidis # @@ -8,7 +8,9 @@ # ============================================================================= from io import BytesIO +import logging from urllib.parse import urlencode + from owslib.util import ( testXMLValue, nspath_eval, @@ -36,7 +38,7 @@ AbstractContentMetadata, ) from owslib.namespaces import Namespaces -from owslib.util import log, openURL +from owslib.util import openURL def get_namespaces(): @@ -328,7 +330,7 @@ def getfeature( request["outputFormat"] = outputFormat data = urlencode(request) - log.debug("Making request: %s?%s" % (base_url, data)) + LOGGER.debug("Making request: %s?%s" % (base_url, data)) elif method.lower() == "post": base_url, data = self.getPOSTGetFeatureRequest( diff --git a/owslib/feature/wfs200.py b/owslib/feature/wfs200.py index 296548b0..651eaaaf 100644 --- a/owslib/feature/wfs200.py +++ b/owslib/feature/wfs200.py @@ -6,6 +6,10 @@ # $Id: wfs.py 503 2006-02-01 17:09:12Z dokai $ # ============================================================================= +from io import BytesIO +import logging +from urllib.parse import urlencode + # owslib imports: from owslib import util from owslib.fgdc import Metadata @@ -18,16 +22,11 @@ from owslib.feature import WebFeatureService_ from owslib.feature.common import ( WFSCapabilitiesReader, - AbstractContentMetadata, + AbstractContentMetadata ) from owslib.namespaces import Namespaces -# other imports -from io import BytesIO -from urllib.parse import urlencode - -import logging -from owslib.util import log +LOGGER = logging.getLogger(__name__) n = Namespaces() WFS_NAMESPACE = n.get_namespace("wfs20") @@ -116,7 +115,7 @@ def __init__( else: auth = Authentication() super(WebFeatureService_2_0_0, self).__init__(auth) - log.debug("building WFS %s" % url) + LOGGER.debug("building WFS %s" % url) self.url = url self.version = version self.timeout = timeout @@ -306,7 +305,7 @@ def getfeature( startindex, sortby, ) - log.debug("GetFeature WFS GET url %s" % url) + LOGGER.debug("GetFeature WFS GET url %s" % url) else: url, data = self.getPOSTGetFeatureRequest( typename, diff --git a/owslib/map/wms130.py b/owslib/map/wms130.py index 130ecd7a..07efe910 100644 --- a/owslib/map/wms130.py +++ b/owslib/map/wms130.py @@ -28,8 +28,6 @@ from owslib.namespaces import Namespaces from owslib.map.common import WMSCapabilitiesReader, AbstractContentMetadata -from owslib.util import log - n = Namespaces() WMS_NAMESPACE = n.get_namespace("wms") OGC_NAMESPACE = n.get_namespace('ogc') diff --git a/owslib/owscontext/__init__.py b/owslib/owscontext/__init__.py index 72e38590..2383f68f 100644 --- a/owslib/owscontext/__init__.py +++ b/owslib/owscontext/__init__.py @@ -3,9 +3,3 @@ # Authors : Alexander Kmoch # # ============================================================================= - -""" -place for some constants to avoid circular imports -""" - -from owslib.util import log diff --git a/owslib/owscontext/atom.py b/owslib/owscontext/atom.py index ee16aadf..03c7b59f 100644 --- a/owslib/owscontext/atom.py +++ b/owslib/owscontext/atom.py @@ -12,15 +12,17 @@ OGC OWS Context Atom Encoding Standard 1.0 (12-084r2) """ +import logging + from owslib.etree import etree, ParseError from owslib import util from owslib.namespaces import Namespaces +from owslib.owscontext.common import is_empty, extract_p, \ + try_int, try_float from owslib.util import nspath_eval, element_to_string -from owslib.util import log -from owslib.owscontext.common import is_empty, extract_p, \ - try_int, try_float +LOGGER = logging.getLogger(__name__) # default variables add_namespaces = {"georss": "http://www.georss.org/georss", @@ -111,31 +113,31 @@ def parse_entry(entry_node): # ftp://ftp.remotesensing.org/pub/geotiff/samples/gdal_eg/cea.txt val = entry_node.find(util.nspath_eval('atom:id', ns)) id = util.testXMLValue(val) - # log.debug("entry :id %s :: %s", id, val) + # LOGGER.debug("entry :id %s :: %s", id, val) resource_base_dict.update({"id": id}) # GeoTIFF Example val = entry_node.find(util.nspath_eval('atom:title', ns)) title = util.testXMLValue(val) - # log.debug("entry: title %s :: %s", id, val) + # LOGGER.debug("entry: title %s :: %s", id, val) resource_base_dict['properties'].update({"title": title}) # 2011-11-01T00:00:00Z val = entry_node.find(util.nspath_eval('atom:updated', ns)) update_date = util.testXMLValue(val) - # log.debug("entry: updated %s :: %s", update_date, val) + # LOGGER.debug("entry: updated %s :: %s", update_date, val) resource_base_dict['properties'].update({"updated": update_date}) # val = entry_node.find(util.nspath_eval('dc:publisher', ns)) publisher = util.testXMLValue(val) - # log.debug("entry: dc:publisher %s :: %s", publisher, val) + # LOGGER.debug("entry: dc:publisher %s :: %s", publisher, val) resource_base_dict['properties'].update({"publisher": publisher}) # val = entry_node.find(util.nspath_eval('dc:rights', ns)) rights = util.testXMLValue(val) - # log.debug("entry: rights %s :: %s", rights, val) + # LOGGER.debug("entry: rights %s :: %s", rights, val) resource_base_dict['properties'].update({"rights": rights}) # @@ -147,13 +149,13 @@ def parse_entry(entry_node): xmltxt = element_to_string( list(val)[0], False) # TODO here parse geometry?? - # log.debug("entry: geometry %s :: %s", xmltxt, val) + # LOGGER.debug("entry: geometry %s :: %s", xmltxt, val) resource_base_dict.update({"geometry": xmltxt.decode('utf-8')}) # aka subtitle, aka abstract val = entry_node.find(util.nspath_eval('atom:content', ns)) subtitle = util.testXMLValue(val) - # log.debug("entry: subtitle %s :: %s", subtitle, val) + # LOGGER.debug("entry: subtitle %s :: %s", subtitle, val) resource_base_dict['properties'].update({"abstract": subtitle}) # .. @@ -173,7 +175,7 @@ def parse_entry(entry_node): "email": email, "uri": uri } - # log.debug("entry: author %s :: %s", author, vals) + # LOGGER.debug("entry: author %s :: %s", author, vals) if not is_empty(author): authors.append(author) @@ -205,7 +207,7 @@ def parse_entry(entry_node): "title": title, "rel": rel } - # log.debug("entry: link %s :: %s", link, vals) + # LOGGER.debug("entry: link %s :: %s", link, vals) if link.get("rel") == "alternate" and not is_empty(link): links_alternates.append(link) elif link.get("rel") == "icon" and not is_empty(link): @@ -215,7 +217,7 @@ def parse_entry(entry_node): elif link.get("rel") == "via" and not is_empty(link): links_via.append(link) else: - log.warning( + LOGGER.warning( "unknown link type in Ows Resource entry section: %r", link) resource_base_dict['properties']['links'].update( @@ -266,7 +268,7 @@ def parse_entry(entry_node): "request": None if is_empty(req_content) else req_content, "result": None } - # log.debug("entry: operation %s :: %s", op_dict, vals) + # LOGGER.debug("entry: operation %s :: %s", op_dict, vals) if not is_empty(op_dict): operations.append(op_dict) @@ -274,7 +276,7 @@ def parse_entry(entry_node): util.nspath_eval('owc:content', ns)) for cont_val in content_nodes: content_dict = parse_owc_content(cont_val) - # log.debug("entry: content_dict %s :: %s", content_dict, vals) + # LOGGER.debug("entry: content_dict %s :: %s", content_dict, vals) if not is_empty(content_dict): contents.append(content_dict) @@ -297,7 +299,7 @@ def parse_entry(entry_node): "legendURL": legend_url, "content": None } - # log.debug("entry: style_set %s :: %s", style_set, vals) + # LOGGER.debug("entry: style_set %s :: %s", style_set, vals) if not is_empty(style_set): styles.append(style_set) @@ -317,14 +319,14 @@ def parse_entry(entry_node): # 2500 val = entry_node.find(util.nspath_eval('owc:minScaleDenominator', ns)) min_scale_denominator = util.testXMLValue(val) - # log.debug("entry: min-scale-... %s :: %s", min_scale_denominator, val) + # LOGGER.debug("entry: min-scale-... %s :: %s", min_scale_denominator, val) resource_base_dict['properties'].update( {"minscaledenominator": min_scale_denominator}) # 25000 val = entry_node.find(util.nspath_eval('owc:maxScaleDenominator', ns)) max_scale_denominator = util.testXMLValue(val) - # log.debug("entry: max_scale_... %s :: %s", max_scale_denominator, val) + # LOGGER.debug("entry: max_scale_... %s :: %s", max_scale_denominator, val) resource_base_dict['properties'].update( {"maxscaledenominator": max_scale_denominator}) # TODO no examples for folder attribute @@ -364,18 +366,18 @@ def decode_atomxml(xml_string): feed_root = etree.fromstring(xml_string) # feed_root = etree.parse(xml_bytes) # feed_root xml lang use? - # # log.debug(feed_root) + # # LOGGER.debug(feed_root) # feed xml:lang=en # lang = feed_root.get('{http://www.w3.org/XML/1998/namespace}lang') lang = util.testXMLAttribute( feed_root, '{http://www.w3.org/XML/1998/namespace}lang') - # log.debug("lang %s ", lang) + # LOGGER.debug("lang %s ", lang) context_base_dict['properties'].update({"lang": lang}) # val = feed_root.find(util.nspath_eval('atom:id', ns)) id = util.testXMLValue(val) - # log.debug("id %s :: %s", id, val) + # LOGGER.debug("id %s :: %s", id, val) context_base_dict.update({"id": id}) # val = feed_root.find(util.nspath_eval('atom:title', ns)) title = util.testXMLValue(val) - # log.debug("title %s :: %s", title, val) + # LOGGER.debug("title %s :: %s", title, val) context_base_dict['properties'].update({"title": title}) # .. @@ -441,7 +443,7 @@ def decode_atomxml(xml_string): "email": email, "uri": uri } - # log.debug("author %s :: %s", author, vals) + # LOGGER.debug("author %s :: %s", author, vals) if not is_empty(author): authors.append(author) @@ -453,32 +455,32 @@ def decode_atomxml(xml_string): if len(list(val)) > 0: xmltxt = element_to_string( list(val)[0], False) - # log.debug("geometry %s :: %s", xmltxt, val) + # LOGGER.debug("geometry %s :: %s", xmltxt, val) context_base_dict['properties'].update({"bbox": xmltxt.decode('utf-8')}) # 2012-11-04T17:26:23Z val = feed_root.find(util.nspath_eval('atom:updated', ns)) update_date = util.testXMLValue(val) - # log.debug("updated %s :: %s", update_date, val) + # LOGGER.debug("updated %s :: %s", update_date, val) context_base_dict['properties'].update({"updated": update_date}) # 2009-01-23T09:08:56.000Z/2009-01-23T09:14:08.000Z val = feed_root.find(util.nspath_eval('dc:date', ns)) time_interval_of_interest = util.testXMLValue(val) - # log.debug("dc:date %s :: %s", time_interval_of_interest, val) + # LOGGER.debug("dc:date %s :: %s", time_interval_of_interest, val) context_base_dict['properties'].update( {"date": time_interval_of_interest}) # val = feed_root.find(util.nspath_eval('atom:rights', ns)) rights = util.testXMLValue(val) - # log.debug("rights %s :: %s", rights, val) + # LOGGER.debug("rights %s :: %s", rights, val) context_base_dict['properties'].update({"rights": rights}) # val = feed_root.find(util.nspath_eval('dc:publisher', ns)) publisher = util.testXMLValue(val) - # log.debug("dc:publisher %s :: %s", publisher, val) + # LOGGER.debug("dc:publisher %s :: %s", publisher, val) context_base_dict['properties'].update({"publisher": publisher}) # @@ -498,7 +500,7 @@ def decode_atomxml(xml_string): "pixelHeight": pixel_height, "mmPerPixel": mm_per_pixel } - # log.debug("display %s :: %s", owc_display, val_display) + # LOGGER.debug("display %s :: %s", owc_display, val_display) if not is_empty(owc_display): context_base_dict['properties'].update({"display": owc_display}) @@ -512,7 +514,7 @@ def decode_atomxml(xml_string): "version": version, "uri": uri } - # log.debug("generator %s :: %s", owc_generator, val) + # LOGGER.debug("generator %s :: %s", owc_generator, val) if not is_empty(owc_generator): context_base_dict['properties'].update({"generator": owc_generator}) @@ -528,7 +530,7 @@ def decode_atomxml(xml_string): "scheme": scheme, "label": label } - # log.debug("category %s :: %s", category, vals) + # LOGGER.debug("category %s :: %s", category, vals) if not is_empty(category): categories.append(category) @@ -543,7 +545,7 @@ def decode_atomxml(xml_string): if entry_dict.get("id") is not None: resources.append(entry_dict) else: - log.warning("feature entry has no id, not allowed: skipping!") + LOGGER.warning("feature entry has no id, not allowed: skipping!") context_base_dict.update({"features": resources}) return context_base_dict @@ -562,16 +564,16 @@ def encode_atomxml(obj_d): # tree = etree.ElementTree(xml_tree) # return tree # except TypeError as te: - # log.warning('problem encoding context to xml', te) + # LOGGER.warning('problem encoding context to xml', te) # raise te # except AttributeError as ae: - # log.warning('problem encoding context to xml', ae) + # LOGGER.warning('problem encoding context to xml', ae) # raise ae # except ValueError as ve: - # log.warning('problem encoding context to xml', ve) + # LOGGER.warning('problem encoding context to xml', ve) # raise ve # except ParseError as pe: - # log.warning('problem encoding context to xml', pe) + # LOGGER.warning('problem encoding context to xml', pe) # raise pe xml_tree = axml_context(obj_d) tree = etree.ElementTree(xml_tree) @@ -598,7 +600,7 @@ def axml_context(d): georss = etree.SubElement(xml, ns_elem("georss", "where")) georss.append(gml) except Exception as ex: - log.warning('could encode bbox into georss:where', ex) + LOGGER.warning('could encode bbox into georss:where', ex) pass context_metadata = [axml_link(do) for do in @@ -674,7 +676,7 @@ def axml_resource(d): georss = etree.SubElement(entry, ns_elem("georss", "where")) georss.append(gml) except Exception as ex: - log.warning('could encode geometry into georss:where', ex) + LOGGER.warning('could encode geometry into georss:where', ex) pass title = d['properties']['title'] @@ -776,7 +778,7 @@ def axml_creator_app(d): creator_app.set("version", version) return creator_app except Exception as ex: - log.warning('could encode creator_app', ex) + LOGGER.warning('could encode creator_app', ex) return None @@ -802,7 +804,7 @@ def axml_display(d): "owc", "mmPerPixel")).text = str(mm_per_pixel) return creator_display except Exception as ex: - log.warning('could encode creator_display', ex) + LOGGER.warning('could encode creator_display', ex) return None @@ -833,7 +835,7 @@ def axml_link(d): link.set("length", str(length)) return link except Exception as ex: - log.warning('could not encode link', ex) + LOGGER.warning('could not encode link', ex) return None @@ -855,7 +857,7 @@ def axml_category(d): category.set("label", label) return category except Exception as ex: - log.warning('could encode category', ex) + LOGGER.warning('could encode category', ex) return None @@ -879,7 +881,7 @@ def axml_author(d): etree.SubElement(author, "uri").text = uri return author except Exception as ex: - log.warning('could encode author', ex) + LOGGER.warning('could encode author', ex) return None @@ -908,7 +910,7 @@ def axml_offering(d): [offering.append(el) for el in styles if el is not None] return offering except Exception as ex: - log.warning('could encode offering', ex) + LOGGER.warning('could encode offering', ex) return None @@ -948,7 +950,7 @@ def axml_operation(d): operation.append(result_enc) return operation except Exception as ex: - log.warning('could encode operation', ex) + LOGGER.warning('could encode operation', ex) return None @@ -988,7 +990,7 @@ def axml_styleset(d): styleset.append(content_enc) return styleset except Exception as ex: - log.warning('could encode styleset', ex) + LOGGER.warning('could encode styleset', ex) return None @@ -1020,5 +1022,5 @@ def axml_content(d): content_elem.text = content return content_elem except Exception as ex: - log.warning('could encode content', ex) + LOGGER.warning('could encode content', ex) return None diff --git a/owslib/owscontext/core.py b/owslib/owscontext/core.py index 8d8778a1..ec525fbd 100644 --- a/owslib/owscontext/core.py +++ b/owslib/owscontext/core.py @@ -14,7 +14,6 @@ from owslib.owscontext.atom import decode_atomxml, encode_atomxml from owslib.owscontext.common import GENERIC_OWCSPEC_URL -# from owslib.util import log # TODO make dates from (currently) string to datetime instances from owslib.owscontext.common import TimeIntervalFormat from owslib.owscontext.common import try_float, try_int, \ diff --git a/owslib/owscontext/geojson.py b/owslib/owscontext/geojson.py index c567ff29..ea371c9f 100644 --- a/owslib/owscontext/geojson.py +++ b/owslib/owscontext/geojson.py @@ -17,8 +17,6 @@ from owslib.owscontext.common import skip_nulls, skip_nulls_rec -# from owslib.util import log - class DateTimeEncoder(json.JSONEncoder): """ https://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable/36142844#36142844 diff --git a/owslib/util.py b/owslib/util.py index 78ba85b9..5e1e560e 100644 --- a/owslib/util.py +++ b/owslib/util.py @@ -1,13 +1,12 @@ # -*- coding: ISO-8859-15 -*- # ============================================================================= -# Copyright (c) 2022 Tom Kralidis +# Copyright (c) 2024 Tom Kralidis # # Authors : Tom Kralidis # # Contact email: tomkralidis@gmail.com # ============================================================================= -import logging as log import os import sys from collections import OrderedDict diff --git a/owslib/wps.py b/owslib/wps.py index f4a63fce..6f567d9e 100644 --- a/owslib/wps.py +++ b/owslib/wps.py @@ -113,7 +113,7 @@ from owslib.ows import ServiceIdentification, ServiceProvider, OperationsMetadata, BoundingBox from time import sleep from owslib.util import (testXMLValue, testXMLAttribute, build_get_url, clean_ows_url, dump, getTypedValue, - getNamespace, element_to_string, nspath, openURL, nspath_eval, log, Authentication) + getNamespace, element_to_string, nspath, openURL, nspath_eval, Authentication) from xml.dom.minidom import parseString from owslib.namespaces import Namespaces from urllib.parse import urlparse @@ -277,7 +277,7 @@ def getcapabilities(self, xml=None): self._capabilities = reader.readFromUrl( self.url, headers=self.headers) - log.debug(element_to_string(self._capabilities)) + LOGGER.debug(element_to_string(self._capabilities)) # populate the capabilities metadata obects from the XML tree self._parseCapabilitiesMetadata(self._capabilities) @@ -305,7 +305,7 @@ def describeprocess(self, identifier, xml=None): rootElement = reader.readFromUrl( self.url, identifier, headers=self.headers) - log.info(element_to_string(rootElement)) + LOGGER.info(element_to_string(rootElement)) # build metadata objects processes = self._parseProcessMetadata(rootElement) @@ -339,7 +339,7 @@ def execute(self, identifier, inputs, output=None, mode=ASYNC, lineage=False, re """ # instantiate a WPSExecution object - log.info('Executing WPS request...') + LOGGER.info('Executing WPS request...') execution = WPSExecution( version=self.version, url=self.url, @@ -354,7 +354,7 @@ def execute(self, identifier, inputs, output=None, mode=ASYNC, lineage=False, re requestElement = execution.buildRequest(identifier, inputs, output, mode=mode, lineage=lineage) request = etree.tostring(requestElement) execution.request = request - log.debug(request) + LOGGER.debug(request) # submit the request to the live server if response is None: @@ -362,7 +362,7 @@ def execute(self, identifier, inputs, output=None, mode=ASYNC, lineage=False, re else: response = etree.fromstring(response) - log.debug(etree.tostring(response)) + LOGGER.debug(etree.tostring(response)) # parse response execution.parseResponse(response) @@ -496,7 +496,7 @@ def _readFromUrl(self, url, data, timeout, method='Get', username=None, password if self.language: data["language"] = self.language request_url = build_get_url(url, data, overwrite=True) - log.debug(request_url) + LOGGER.debug(request_url) # split URL into base url and query string to use utility function spliturl = request_url.split('?') @@ -657,7 +657,7 @@ def buildRequest(self, identifier, inputs=[], output=None, mode=ASYNC, lineage=F if mode is SYNC: _async = False elif mode is AUTO: - log.warn("Auto mode not available in WPS 1.0.0. Using async mode.") + LOGGER.warn("Auto mode not available in WPS 1.0.0. Using async mode.") _async = True else: _async = True @@ -703,7 +703,7 @@ def buildRequest(self, identifier, inputs=[], output=None, mode=ASYNC, lineage=F # # if is_literaldata(val): - log.debug("literaldata %s", key) + LOGGER.debug("literaldata %s", key) dataElement = etree.SubElement( inputElement, nspath_eval('wps:Data', namespaces)) literalDataElement = etree.SubElement( @@ -728,7 +728,7 @@ def buildRequest(self, identifier, inputs=[], output=None, mode=ASYNC, lineage=F # # elif is_complexdata(val): - log.debug("complexdata %s", key) + LOGGER.debug("complexdata %s", key) inputElement.append(val.getXml()) elif is_boundingboxdata(val): inputElement.append(val.get_xml()) @@ -801,13 +801,13 @@ def checkStatus(self, url=None, response=None, sleepSecs=60): # override status location if url is not None: self.statusLocation = url - log.info('\nChecking execution status... (location=%s)' % + LOGGER.info('\nChecking execution status... (location=%s)' % self.statusLocation) try: response = reader.readFromUrl( self.statusLocation, headers=self.headers) except Exception: - log.error("Could not read status document.") + LOGGER.error("Could not read status document.") else: response = reader.readFromString(response) @@ -815,16 +815,16 @@ def checkStatus(self, url=None, response=None, sleepSecs=60): try: xml = etree.tostring(response) except Exception: - log.error("Could not parse XML response.") + LOGGER.error("Could not parse XML response.") else: self.response = xml - log.debug(self.response) + LOGGER.debug(self.response) self.parseResponse(response) # sleep given number of seconds if self.isComplete() is False: - log.info('Sleeping %d seconds...' % sleepSecs) + LOGGER.info('Sleeping %d seconds...' % sleepSecs) sleep(sleepSecs) def getStatus(self): @@ -902,7 +902,7 @@ def getOutput(self, filepath=None, identifier=None): out = open(filepath, 'wb') out.write(content) out.close() - log.info(f'Output written to file: {filepath}') + LOGGER.info(f'Output written to file: {filepath}') else: raise Exception( f"Execution not successfully completed: status={self.status}") @@ -953,12 +953,12 @@ def parseResponse(self, response): self._parseExceptionReport(response) else: - log.debug('Unknown Response') + LOGGER.debug('Unknown Response') # log status, errors - log.info('Execution status=%s' % self.status) - log.info('Percent completed=%s' % self.percentCompleted) - log.info('Status message=%s' % self.statusMessage) + LOGGER.info('Execution status=%s' % self.status) + LOGGER.info('Percent completed=%s' % self.percentCompleted) + LOGGER.info('Status message=%s' % self.statusMessage) for error in self.errors: dump(error) @@ -1025,7 +1025,7 @@ def _parseExecuteResponse(self, root): # xmlns:ows="http://www.opengis.net/ows/1.1" # xmlns:xlink="http://www.w3.org/1999/xlink"> if len(self.dataInputs) > 0: - log.debug('clean data inputs') + LOGGER.debug('clean data inputs') self.dataInputs[:] = [] for inputElement in root.findall(nspath('DataInputs/Input', ns=wpsns)): self.dataInputs.append(Output(inputElement)) @@ -1034,7 +1034,7 @@ def _parseExecuteResponse(self, root): # # xmlns:ns="http://www.opengis.net/wps/1.0.0" if len(self.processOutputs) > 0: - log.debug('clean process outputs') + LOGGER.debug('clean process outputs') self.processOutputs[:] = [] for outputElement in root.findall(nspath('ProcessOutputs/Output', ns=wpsns)): self.processOutputs.append(Output(outputElement)) @@ -1438,7 +1438,7 @@ def retrieveData(self, username=None, password=None, headers=None, verify=True, # a) 'http://cida.usgs.gov/climate/gdp/process/RetrieveResultServlet?id=1318528582026OUTPUT.601bb3d0-547f-4eab-8642-7c7d2834459e' # noqa # b) 'http://rsg.pml.ac.uk/wps/wpsoutputs/outputImage-11294Bd6l2a.tif' - log.info('Output URL=%s' % url) + LOGGER.info('Output URL=%s' % url) # Extract output filepath from base URL self.fileName = url.split('/')[-1] @@ -1492,7 +1492,7 @@ def writeToDisk(self, path=None, username=None, password=None, out = open(self.filePath, 'wb') out.write(content) out.close() - log.info('Output written to file: %s' % self.filePath) + LOGGER.info('Output written to file: %s' % self.filePath) class WPSException: @@ -1922,7 +1922,7 @@ def monitorExecution(execution, sleepSecs=3, download=False, filepath=None): ''' while execution.isComplete() is False: execution.checkStatus(sleepSecs=sleepSecs) - log.info('Execution status: %s' % execution.status) + LOGGER.info('Execution status: %s' % execution.status) if execution.isSucceeded(): if download: @@ -1930,10 +1930,10 @@ def monitorExecution(execution, sleepSecs=3, download=False, filepath=None): else: for output in execution.processOutputs: if output.reference is not None: - log.info('Output URL=%s' % output.reference) + LOGGER.info('Output URL=%s' % output.reference) else: for ex in execution.errors: - log.error('Error: code=%s, locator=%s, text=%s' % + LOGGER.error('Error: code=%s, locator=%s, text=%s' % (ex.code, ex.locator, ex.text)) diff --git a/tests/test_owscontext_atomxml.py b/tests/test_owscontext_atomxml.py index 77febe98..f7f4b1d8 100644 --- a/tests/test_owscontext_atomxml.py +++ b/tests/test_owscontext_atomxml.py @@ -19,8 +19,6 @@ from owslib.namespaces import Namespaces from owslib.util import nspath_eval -from owslib.util import log - from owslib.owscontext.common import is_empty # default variables @@ -82,17 +80,12 @@ def test_load_feeds_bulk(): atom11, atom12, atom13, atom14, atom15, atom16, atom17] for f in feeds: - # logger.debug(f) dict_obj = decode_atomxml(f) assert dict_obj is not None - # logger.debug("dict title: " + dict_obj.get('properties').get('title')) owc = OwcContext.from_dict(dict_obj) assert owc is not None - # logger.debug("owc title: " + owc.title) for res in owc.resources: - # logger.debug(res.id) assert res.title is not None - # logger.debug(OwcContext.from_dict(dict_obj).to_json()) jsdata = owc.to_json() assert jsdata is not None @@ -131,17 +124,12 @@ def test_single_atomxml_coding(): atom1 = open(resource_file(os.path.join('owc_atom_examples', 'wms_meris.xml')), 'rb').read() owc = OwcContext.from_atomxml(atom1) assert owc is not None - # logger.debug("s owc title: " + owc.title) for res in owc.resources: - # logger.debug("s res id: " + res.id) assert res.title is not None assert len(res.offerings) > 0 for off in res.offerings: - # logger.debug("s off code: " + off.offering_code) assert off.operations is not None assert len(off.operations) > 0 - # for lnk in res.preview: - # logger.debug(lnk.to_dict()) jsdata = owc.to_json() assert jsdata is not None @@ -149,14 +137,9 @@ def test_single_atomxml_coding(): re_owc = OwcContext.from_json(jsdata) assert re_owc is not None for res in re_owc.resources: - # logger.debug("s res id: " + res.id) assert res.title is not None assert len(res.offerings) > 0 for off in res.offerings: - # logger.debug("s off code: " + off.offering_code) assert off.operations is not None assert len(off.operations) > 0 - # for lnk in res.preview: - # logger.debug(lnk.to_dict()) assert owc.to_dict() == re_owc.to_dict() - # logger.debug(owc.to_json()) diff --git a/tests/test_wps_execute_language.py b/tests/test_wps_execute_language.py index 092401f8..439502ac 100644 --- a/tests/test_wps_execute_language.py +++ b/tests/test_wps_execute_language.py @@ -1,5 +1,5 @@ +import logging import owslib.wps -from owslib.util import log def test_wps_execute_language(monkeypatch): @@ -8,7 +8,7 @@ def raise_on_log_error(*a): """Make sure the errors are raised, not only caught and logged""" raise AssertionError - monkeypatch.setattr(log, "error", raise_on_log_error) + monkeypatch.setattr(logging, "error", raise_on_log_error) monkeypatch.setattr(owslib.wps.WPSExecution, "parseResponse", lambda *a: None) wps = owslib.wps.WebProcessingService('http://www.example.com', language='fr-CA', skip_caps=True) diff --git a/tests/utils.py b/tests/utils.py index 0334b31d..580cf1d3 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -8,7 +8,7 @@ def setup_logging(loglevel='INFO'): """Helper function to setup logging for tests""" - logger = logging.getLogger('owslib') + logger = logging.getLogger(__name__) logger.setLevel(getattr(logging, loglevel)) sh = logging.StreamHandler(sys.stdout) formatter = logging.Formatter('%(message)s')