Skip to content

Commit f53e0ee

Browse files
authored
Merge pull request #340 from candleindark/local-logger
Replace use of the root logger with use of module-level loggers
2 parents 6ba1b0b + b183708 commit f53e0ee

File tree

16 files changed

+134
-97
lines changed

16 files changed

+134
-97
lines changed

linkml_runtime/dumpers/rdflib_dumper.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
from linkml_runtime.utils.schemaview import SchemaView, ElementName, PermissibleValue, PermissibleValueText
1616
from linkml_runtime.utils.yamlutils import YAMLRoot
1717

18+
logger = logging.getLogger(__name__)
19+
1820

1921
class RDFLibDumper(Dumper):
2022
"""
@@ -44,7 +46,7 @@ def as_rdf_graph(
4446
if isinstance(prefix_map, Converter):
4547
# TODO replace with `prefix_map = prefix_map.bimap` after making minimum requirement on python 3.8
4648
prefix_map = {record.prefix: record.uri_prefix for record in prefix_map.records}
47-
logging.debug(f'PREFIXMAP={prefix_map}')
49+
logger.debug(f'PREFIXMAP={prefix_map}')
4850
if prefix_map:
4951
for k, v in prefix_map.items():
5052
if k == "@base":
@@ -80,7 +82,7 @@ def inject_triples(self, element: Any, schemaview: SchemaView, graph: Graph, tar
8082
"""
8183
namespaces = schemaview.namespaces()
8284
slot_name_map = schemaview.slot_name_mappings()
83-
logging.debug(f'CONVERT: {element} // {type(element)} // {target_type}')
85+
logger.debug(f'CONVERT: {element} // {type(element)} // {target_type}')
8486
if target_type in schemaview.all_enums():
8587
if isinstance(element, PermissibleValueText):
8688
e = schemaview.get_enum(target_type)
@@ -105,7 +107,7 @@ def inject_triples(self, element: Any, schemaview: SchemaView, graph: Graph, tar
105107
namespaces["xsd"] = XSD
106108
return Literal(element, datatype=namespaces.uri_for(dt_uri))
107109
else:
108-
logging.warning(f'No datatype specified for : {t.name}, using plain Literal')
110+
logger.warning(f'No datatype specified for : {t.name}, using plain Literal')
109111
return Literal(element)
110112
element_vars = {k: v for k, v in vars(element).items() if not k.startswith('_')}
111113
if len(element_vars) == 0:
@@ -134,7 +136,7 @@ def inject_triples(self, element: Any, schemaview: SchemaView, graph: Graph, tar
134136
if k in slot_name_map:
135137
k = slot_name_map[k].name
136138
else:
137-
logging.error(f'Slot {k} not in name map')
139+
logger.error(f'Slot {k} not in name map')
138140
slot = schemaview.induced_slot(k, cn)
139141
if not slot.identifier:
140142
slot_uri = URIRef(schemaview.get_uri(slot, expand=True))

linkml_runtime/index/object_index.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
from linkml_runtime.utils import eval_utils
1717
from linkml_runtime.utils.yamlutils import YAMLRoot
1818

19+
logger = logging.getLogger(__name__)
20+
1921

2022
class ObjectIndex:
2123
"""
@@ -257,7 +259,7 @@ def _map(self, obj: Any, in_range: str) -> Any:
257259
module = inspect.getmodule(self._shadowed)
258260
cls_dict = dict(inspect.getmembers(module, inspect.isclass))
259261
if in_range not in cls_dict:
260-
logging.warning(f"Class {in_range} not found in {module}, classes: {cls_dict}")
262+
logger.warning(f"Class {in_range} not found in {module}, classes: {cls_dict}")
261263
return obj
262264
cls = cls_dict[in_range]
263265
return cls(obj)

linkml_runtime/loaders/json_loader.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
from linkml_runtime.utils.yamlutils import YAMLRoot
99
from pydantic import BaseModel
1010

11+
logger = logging.getLogger(__name__)
12+
13+
1114
class JSONLoader(Loader):
1215

1316
def load_as_dict(self,
@@ -31,6 +34,6 @@ def load_any(self,
3134
if isinstance(data_as_dict, dict):
3235
typ = data_as_dict.pop('@type', None)
3336
if typ and typ != target_class.__name__:
34-
logging.warning(f"Warning: input type mismatch. Expected: {target_class.__name__}, Actual: {typ}")
37+
logger.warning(f"Warning: input type mismatch. Expected: {target_class.__name__}, Actual: {typ}")
3538

3639
return self._construct_target_class(data_as_dict, target_class)

linkml_runtime/loaders/rdflib_loader.py

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,9 @@
1818
from linkml_runtime.utils.yamlutils import YAMLRoot
1919
from pydantic import BaseModel
2020

21+
logger = logging.getLogger(__name__)
22+
23+
2124
VALID_SUBJECT = Union[URIRef, BNode]
2225
ANYDICT = Dict[str, Any]
2326

@@ -60,7 +63,7 @@ def from_rdf_graph(
6063
if c2.name in schemaview.class_ancestors(cn):
6164
continue
6265
else:
63-
logging.error(f'Inconsistent URI to class map: {uri} -> {c2.name}, {c.name}')
66+
logger.error(f'Inconsistent URI to class map: {uri} -> {c2.name}, {c.name}')
6467
uri_to_class_map[uri] = c
6568
# data prefix map: supplements or overrides existing schema prefix map
6669
if isinstance(prefix_map, Converter):
@@ -74,7 +77,7 @@ def from_rdf_graph(
7477
target_class_uriref: URIRef = target_class.class_class_uri
7578
root_dicts: List[ANYDICT] = []
7679
root_subjects: List[VALID_SUBJECT] = list(graph.subjects(RDF.type, target_class_uriref))
77-
logging.debug(f'ROOTS = {root_subjects}')
80+
logger.debug(f'ROOTS = {root_subjects}')
7881
# Step 2: walk RDF graph starting from root subjects, constructing dict tree
7982
node_tuples_to_visit: List[Tuple[VALID_SUBJECT, ClassDefinitionName]] ## nodes and their type still to visit
8083
node_tuples_to_visit = [(subject, target_class.class_name) for subject in root_subjects]
@@ -101,14 +104,14 @@ def from_rdf_graph(
101104
type_classes = [uri_to_class_map[str(x)] for x in type_vals]
102105
if len(type_classes) > 1:
103106
raise ValueError(f'Ambiguous types for {subject} == {type_classes}')
104-
logging.info(f'Replacing {subject_class} with {type_classes}')
107+
logger.info(f'Replacing {subject_class} with {type_classes}')
105108
subject_class = type_classes[0].name
106109
# process all triples for this node
107110
for (_, p, o) in graph.triples((subject, None, None)):
108111
processed_triples.add((subject,p,o))
109-
logging.debug(f' Processing triple {subject} {p} {o}, subject type = {subject_class}')
112+
logger.debug(f' Processing triple {subject} {p} {o}, subject type = {subject_class}')
110113
if p == RDF.type:
111-
logging.debug(f'Ignoring RDF.type for {subject} {o}, we automatically infer this from {subject_class}')
114+
logger.debug(f'Ignoring RDF.type for {subject} {o}, we automatically infer this from {subject_class}')
112115
elif p not in uri_to_slot:
113116
if ignore_unmapped_predicates:
114117
unmapped_predicates.add(p)
@@ -121,13 +124,13 @@ def from_rdf_graph(
121124
slot_name = underscore(slot.name)
122125
if isinstance(o, Literal):
123126
if EnumDefinition.class_name in range_applicable_elements:
124-
logging.debug(f'Assuming no meaning assigned for value {o} for Enum {slot.range}')
127+
logger.debug(f'Assuming no meaning assigned for value {o} for Enum {slot.range}')
125128
elif TypeDefinition.class_name not in range_applicable_elements:
126129
raise ValueError(f'Cannot map Literal {o} to a slot {slot.name} whose range {slot.range} is not a type;')
127130
v = o.value
128131
elif isinstance(o, BNode):
129132
if not is_inlined:
130-
logging.error(f'blank nodes should be inlined; {slot_name}={o} in {subject}')
133+
logger.error(f'blank nodes should be inlined; {slot_name}={o} in {subject}')
131134
v = Pointer(o)
132135
else:
133136
if ClassDefinition.class_name in range_applicable_elements:
@@ -137,7 +140,7 @@ def from_rdf_graph(
137140
else:
138141
v = namespaces.curie_for(o)
139142
if v is None:
140-
logging.debug(f'No CURIE for {p}={o} in {subject} [{subject_class}]')
143+
logger.debug(f'No CURIE for {p}={o} in {subject} [{subject_class}]')
141144
v = str(o)
142145
elif EnumDefinition.class_name in range_applicable_elements:
143146
range_union_elements = schemaview.slot_range_as_union(slot)
@@ -156,7 +159,7 @@ def from_rdf_graph(
156159
v = namespaces.curie_for(o)
157160
if v is None:
158161
v = str(o)
159-
logging.debug(f'Casting {o} to string')
162+
logger.debug(f'Casting {o} to string')
160163
else:
161164
raise ValueError(f'Expected literal value ({range_applicable_elements}) for {slot_name}={o}')
162165
if is_inlined:
@@ -175,13 +178,13 @@ def from_rdf_graph(
175178
if slot.range in schemaview.all_classes():
176179
node_tuples_to_visit.append((o, ClassDefinitionName(slot.range)))
177180
if unmapped_predicates:
178-
logging.info(f'Unmapped predicated: {unmapped_predicates}')
181+
logger.info(f'Unmapped predicated: {unmapped_predicates}')
179182
unprocessed_triples = set(graph.triples((None, None, None))) - processed_triples
180-
logging.info(f'Triple processed = {len(processed_triples)}, unprocessed = {len(unprocessed_triples)}')
183+
logger.info(f'Triple processed = {len(processed_triples)}, unprocessed = {len(unprocessed_triples)}')
181184
if len(unprocessed_triples) > 0:
182185
if not allow_unprocessed_triples:
183186
for t in unprocessed_triples:
184-
logging.warning(f' Unprocessed: {t}')
187+
logger.warning(f' Unprocessed: {t}')
185188
raise ValueError(f'Unprocessed triples: {len(unprocessed_triples)}')
186189
# Step 2: replace inline pointers with object dicts
187190
def repl(v):
@@ -195,7 +198,7 @@ def repl(v):
195198
objs_to_visit: List[ANYDICT] = copy(root_dicts)
196199
while len(objs_to_visit) > 0:
197200
obj = objs_to_visit.pop()
198-
logging.debug(f'Replacing pointers for {obj}')
201+
logger.debug(f'Replacing pointers for {obj}')
199202
for k, v in obj.items():
200203
if v is None:
201204
continue

linkml_runtime/utils/csvutils.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
SlotDefinition, ClassDefinition, ClassDefinitionName
66
from linkml_runtime.utils.schemaview import SchemaView
77

8+
logger = logging.getLogger(__name__)
9+
10+
811
def get_configmap(schemaview: SchemaView, index_slot: SlotDefinitionName) -> CONFIGMAP:
912
"""
1013
Generates a configuration that specifies mapping between a CSV and a JSON structure
@@ -28,9 +31,9 @@ def get_configmap(schemaview: SchemaView, index_slot: SlotDefinitionName) -> CON
2831
cm[sn] = config
2932
return cm
3033
else:
31-
logging.warning(f'Index slot range not to class: {slot.range}')
34+
logger.warning(f'Index slot range not to class: {slot.range}')
3235
else:
33-
logging.warning(f'Index slot or schema not specified')
36+
logger.warning(f'Index slot or schema not specified')
3437
return {}
3538

3639
def _get_key_config(schemaview: SchemaView, tgt_cls: ClassDefinitionName, sn: SlotDefinitionName, sep='_'):

linkml_runtime/utils/distroutils.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from pathlib import PurePath
77
from typing import List, Type
88

9+
logger = logging.getLogger(__name__)
910

1011

1112
def get_default_paths(file_type: str) -> List[PurePath]:
@@ -41,7 +42,7 @@ def get_default_paths(file_type: str) -> List[PurePath]:
4142
paths.append(rel_dir)
4243
# YAML files may be in the same directory as the python
4344
paths.append(PurePath('.'))
44-
logging.debug(f"Paths to search: {paths}")
45+
logger.debug(f"Paths to search: {paths}")
4546
return paths
4647

4748
def get_packaged_file_as_str(package: str, file_type: str, rel_paths: List[PurePath]=[], encoding="utf-8") -> str:
@@ -65,7 +66,7 @@ def get_packaged_file_as_str(package: str, file_type: str, rel_paths: List[PureP
6566
if data:
6667
break
6768
except FileNotFoundError:
68-
logging.debug(f'candidate {path} not found')
69+
logger.debug(f'candidate {path} not found')
6970
if not data:
7071
raise FileNotFoundError(f'package: {package} file: {file_type}')
7172
return data.decode(encoding)

linkml_runtime/utils/inference_utils.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111
from linkml_runtime.utils.walker_utils import traverse_object_tree
1212
from linkml_runtime.utils.yamlutils import YAMLRoot
1313

14+
logger = logging.getLogger(__name__)
15+
16+
1417
RESOLVE_FUNC = Callable[[str, Any], Any]
1518

1619
def obj_as_dict_nonrecursive(obj: YAMLRoot, resolve_function: RESOLVE_FUNC = None) -> Dict[str, Any]:
@@ -73,7 +76,7 @@ def generate_slot_value(obj: YAMLRoot, slot_name: Union[str, SlotDefinitionName]
7376
mapped_slot = schemaview.slot_name_mappings()[slot_name]
7477
slot_name = mapped_slot.name
7578
slot = schemaview.induced_slot(slot_name, class_name)
76-
logging.debug(f' CONF={config}')
79+
logger.debug(f' CONF={config}')
7780
if config.use_string_serialization:
7881
if slot.string_serialization:
7982
if isinstance(obj, JsonObj):
@@ -106,7 +109,7 @@ def infer_slot_value(obj: YAMLRoot, slot_name: Union[str, SlotDefinitionName], s
106109
if v is not None and policy == Policy.KEEP:
107110
return v
108111
new_v = generate_slot_value(obj, slot_name, schemaview, class_name=class_name, config=config)
109-
logging.debug(f'SETTING {slot_name} = {new_v} // current={v}, {policy}')
112+
logger.debug(f'SETTING {slot_name} = {new_v} // current={v}, {policy}')
110113
if new_v:
111114
# check if new value is different; not str check is necessary as enums may not be converted
112115
if v is not None and new_v != v and str(new_v) != str(v):
@@ -138,7 +141,7 @@ def infer_all_slot_values(obj: YAMLRoot, schemaview: SchemaView,
138141
:return:
139142
"""
140143
def infer(in_obj: YAMLRoot):
141-
logging.debug(f'INFER={in_obj}')
144+
logger.debug(f'INFER={in_obj}')
142145
if isinstance(in_obj, YAMLRoot) and not isinstance(in_obj, EnumDefinitionImpl) and not isinstance(in_obj, PermissibleValue):
143146
for k, v in vars(in_obj).items():
144147
#print(f' ISV={k} curr={v} policy={policy} in_obj={type(in_obj)}')

linkml_runtime/utils/ruleutils.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
from linkml_runtime.linkml_model.meta import SchemaDefinition, ClassDefinition, SlotDefinition, Expression, \
77
ClassExpression, ClassDefinitionName, ClassRule, AnonymousClassExpression, SlotExpression, SlotDefinitionName
88

9+
logger = logging.getLogger(__name__)
10+
911

1012
class AtomicClassExpression:
1113
"""
@@ -58,12 +60,12 @@ def get_range_as_disjunction(slot: SlotExpression) -> Set[ClassDefinitionName]:
5860
if isinstance(slot.range_expression, ClassExpression):
5961
conjs.append(get_disjunction(slot.range_expression))
6062
else:
61-
logging.warning(f'Expected range_expression for {slot.name} to be a class expression, not {type(slot.range_expression)}')
63+
logger.warning(f'Expected range_expression for {slot.name} to be a class expression, not {type(slot.range_expression)}')
6264
if len(conjs) == 0:
6365
if slot.range:
6466
conjs.append({slot.range})
6567
else:
66-
logging.warning(f'No range for {slot.name}')
68+
logger.warning(f'No range for {slot.name}')
6769
if len(conjs) > 1:
6870
raise Exception(f'Cannot determine range disjunction for {slot}, got conjunctions: {conjs}')
6971
if len(conjs) == 0:

linkml_runtime/utils/schemaview.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ def load_import(self, imp: str, from_schema: SchemaDefinition = None):
224224
base_dir = os.path.dirname(from_schema.source_file)
225225
else:
226226
base_dir = None
227-
logging.info(f'Importing {imp} as {sname} from source {from_schema.source_file}; base_dir={base_dir}')
227+
logger.info(f'Importing {imp} as {sname} from source {from_schema.source_file}; base_dir={base_dir}')
228228
schema = load_schema_wrap(sname + '.yaml', base_dir=base_dir)
229229
return schema
230230

@@ -1403,7 +1403,7 @@ def induced_slot(self, slot_name: SLOT_NAME, class_name: CLASS_NAME = None, impo
14031403
# )
14041404
if not is_empty(v2):
14051405
v = v2
1406-
logging.debug(f'{v} takes precedence over {v2} for {induced_slot.name}.{metaslot_name}')
1406+
logger.debug(f'{v} takes precedence over {v2} for {induced_slot.name}.{metaslot_name}')
14071407
if v is None:
14081408
if metaslot_name == 'range':
14091409
v = self.schema.default_range

linkml_runtime/utils/schemaview_cli.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313
import click
1414
import yaml
1515

16+
logger = logging.getLogger(__name__)
17+
18+
1619
DEFAULT_DISPLAY_COLS = [
1720
'name',
1821
'is_a',
@@ -58,8 +61,8 @@ def list(schema, columns, element_type):
5861
5962
"""
6063
schema_view = SchemaView(schema)
61-
logging.info(f'id={schema_view.schema.id}')
62-
logging.info(f'name={schema_view.schema.name}')
64+
logger.info(f'id={schema_view.schema.id}')
65+
logger.info(f'name={schema_view.schema.name}')
6366
enames = schema_view.all_element()
6467
elements = [schema_view.get_element(ename) for ename in enames]
6568
if element_type is not None:
@@ -79,7 +82,7 @@ def islot(schema, columns, class_names):
7982
"""
8083
schema_view = SchemaView(schema)
8184
for cn in class_names:
82-
logging.info(f'Class: {cn}')
85+
logger.info(f'Class: {cn}')
8386
islots = schema_view.class_induced_slots(cn)
8487
_show_elements(islots, columns=columns)
8588

@@ -97,7 +100,7 @@ def ancs(schema, class_names, is_a, mixins):
97100
"""
98101
schema_view = SchemaView(schema)
99102
for cn in class_names:
100-
logging.info(f'Class: {cn}')
103+
logger.info(f'Class: {cn}')
101104
ancs = schema_view.class_ancestors(cn, is_a=is_a, mixins=mixins)
102105
for a in ancs:
103106
print(f'{cn}\t{a}')
@@ -116,7 +119,7 @@ def descs(schema, class_names, is_a, mixins):
116119
"""
117120
schema_view = SchemaView(schema)
118121
for cn in class_names:
119-
logging.info(f'Class: {cn}')
122+
logger.info(f'Class: {cn}')
120123
ds = schema_view.class_descendants(cn, is_a=is_a, mixins=mixins)
121124
for d in ds:
122125
print(f'{cn}\t{d}')
@@ -130,7 +133,7 @@ def delete(schema, class_names):
130133
"""
131134
schema_view = SchemaView(schema)
132135
for cn in class_names:
133-
logging.info(f'Class: {cn}')
136+
logger.info(f'Class: {cn}')
134137
schema_view.delete_class(cn)
135138
print(yaml_dumper.dumps(schema_view.schema))
136139

0 commit comments

Comments
 (0)