Skip to content

Commit 812eb0c

Browse files
committed
refactor: Unify and moernize agent logging system
Signed-off-by: Cesar Berrospi Ramis <ceb@zurich.ibm.com>
1 parent cb2ad4c commit 812eb0c

12 files changed

Lines changed: 594 additions & 211 deletions

File tree

docling_agent/agent/base_functions.py

Lines changed: 39 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -32,14 +32,14 @@
3232
)
3333
from docling_core.types.io import DocumentStream
3434

35-
from docling_agent.logging import logger
35+
from docling_agent.logging import log_debug, log_error, log_info, log_warning
3636

3737

3838
def find_crefs(text: str) -> list[RefItem]:
3939
"""
4040
Check if a string matches the pattern ```markdown(.*)?```
4141
"""
42-
logger.info("find_crefs")
42+
log_info("find_crefs")
4343
labels: str = "|".join(e.value for e in DocItemLabel)
4444
pattern = rf"#/({labels})/\d+"
4545

@@ -51,15 +51,15 @@ def find_crefs(text: str) -> list[RefItem]:
5151

5252

5353
def has_crefs(text: str) -> bool:
54-
logger.info("has_crefs")
54+
log_info("has_crefs")
5555
return len(find_crefs(text)) > 0
5656

5757

5858
def has_json_dicts(text: str) -> bool:
5959
"""
6060
Extract JSON dictionaries from ```json code blocks
6161
"""
62-
logger.info("has_json_dicts")
62+
log_info("has_json_dicts")
6363
pattern = r"```json\s*(.*?)\s*```"
6464
matches = re.findall(pattern, text, re.DOTALL)
6565

@@ -68,7 +68,7 @@ def has_json_dicts(text: str) -> bool:
6868
try:
6969
calls.append(json.loads(json_content))
7070
except Exception as e:
71-
logger.error("Failed to parse JSON call block: %s", e)
71+
log_error("Failed to parse JSON call block: %s", e)
7272
return False
7373

7474
return len(calls) > 0
@@ -78,7 +78,7 @@ def find_json_dicts(text: str) -> list[dict]:
7878
"""
7979
Extract JSON dictionaries from ```json code blocks
8080
"""
81-
logger.info("find_json_dicts")
81+
log_info("find_json_dicts")
8282
pattern = r"```json\s*(.*?)\s*```"
8383
matches = re.findall(pattern, text, re.DOTALL)
8484

@@ -92,7 +92,7 @@ def find_json_dicts(text: str) -> list[dict]:
9292
else:
9393
calls.append(parsed)
9494
except json.JSONDecodeError as e:
95-
logger.warning(f"Failed to parse JSON in match {i}: {e}")
95+
log_warning(f"Failed to parse JSON in match {i}: {e}")
9696

9797
return calls
9898

@@ -111,7 +111,7 @@ def create_document_outline(
111111
Returns:
112112
A text representation of a document outline.
113113
"""
114-
logger.debug("create_document_outline")
114+
log_debug("create_document_outline")
115115

116116
# Use OutlineDocSerializer with JSON format to get structured data
117117
params = OutlineParams(
@@ -127,7 +127,7 @@ def create_document_outline(
127127

128128
def serialize_item_to_markdown(item: TextItem, doc: DoclingDocument) -> str:
129129
"""Serialize a text item to markdown format using existing serializer."""
130-
logger.info("serialize_item_to_markdown")
130+
log_info("serialize_item_to_markdown")
131131

132132
serializer = MarkdownDocSerializer(doc=doc, params=MarkdownParams())
133133

@@ -136,7 +136,7 @@ def serialize_item_to_markdown(item: TextItem, doc: DoclingDocument) -> str:
136136

137137

138138
def serialize_table_to_html(table: TableItem, doc: DoclingDocument) -> str:
139-
logger.info("serialize_table_to_html")
139+
log_info("serialize_table_to_html")
140140
from docling_core.transforms.serializer.html import (
141141
HTMLDocSerializer,
142142
HTMLTableSerializer,
@@ -158,7 +158,7 @@ def find_html_code_block(text: str) -> str | None:
158158
"""
159159
Check if a string matches the pattern ```html(.*)?```
160160
"""
161-
logger.info("find_html_code_block")
161+
log_info("find_html_code_block")
162162
pattern = r"```html(.*?)```"
163163
match = re.search(pattern, text, re.DOTALL)
164164
return match.group(1) if match else None
@@ -168,15 +168,15 @@ def has_html_code_block(text: str) -> bool:
168168
"""
169169
Check if a string contains a html code block pattern anywhere in the text
170170
"""
171-
logger.info("has_html_code_block")
171+
log_info("has_html_code_block")
172172
return find_html_code_block(text) is not None
173173

174174

175175
def find_markdown_code_block(text: str) -> str | None:
176176
"""
177177
Check if a string matches the pattern ```(md|markdown)(.*)?```
178178
"""
179-
logger.info("find_markdown_code_block")
179+
log_info("find_markdown_code_block")
180180
pattern = r"```(md|markdown)(.*?)```"
181181
match = re.search(pattern, text, re.DOTALL)
182182
return match.group(2) if match else None
@@ -186,12 +186,12 @@ def has_markdown_code_block(text: str) -> bool:
186186
"""
187187
Check if a string contains a markdown code block pattern anywhere in the text
188188
"""
189-
logger.info("has_markdown_code_block")
189+
log_info("has_markdown_code_block")
190190
return find_markdown_code_block(text) is not None
191191

192192

193193
def convert_html_to_docling_table(text: str) -> list[TableItem] | None:
194-
logger.info("convert_html_to_docling_table")
194+
log_info("convert_html_to_docling_table")
195195
text_ = find_html_code_block(text)
196196
if text_ is None:
197197
text_ = text # assume the entire text is html
@@ -208,19 +208,19 @@ def convert_html_to_docling_table(text: str) -> list[TableItem] | None:
208208
return conv.document.tables
209209

210210
except Exception as exc:
211-
logger.error(exc)
211+
log_error("Failed to convert HTML to docling table", exception=exc)
212212
return None
213213

214214
return None
215215

216216

217217
def validate_html_to_docling_table(text: str) -> bool:
218-
logger.info("validate_html_to_docling_table")
218+
log_info("validate_html_to_docling_table")
219219
return convert_html_to_docling_table(text) is not None
220220

221221

222222
def convert_markdown_to_docling_document(text: str) -> DoclingDocument | None:
223-
logger.info("convert_markdown_to_docling_document")
223+
log_info("convert_markdown_to_docling_document")
224224
text_ = find_markdown_code_block(text)
225225
if text_ is None:
226226
text_ = text # assume the entire text is html
@@ -242,12 +242,12 @@ def convert_markdown_to_docling_document(text: str) -> DoclingDocument | None:
242242

243243

244244
def validate_markdown_to_docling_document(text: str) -> bool:
245-
logger.info("validate_markdown_to_docling_document")
245+
log_info("validate_markdown_to_docling_document")
246246
return convert_markdown_to_docling_document(text) is not None
247247

248248

249249
def convert_html_to_docling_document(text: str) -> DoclingDocument | None:
250-
logger.info("convert_html_to_docling_document")
250+
log_info("convert_html_to_docling_document")
251251
text_ = find_html_code_block(text)
252252
if text_ is None:
253253
text_ = text # assume the entire text is html
@@ -263,19 +263,19 @@ def convert_html_to_docling_document(text: str) -> DoclingDocument | None:
263263
if conv.status == ConversionStatus.SUCCESS:
264264
return conv.document
265265
except Exception as exc:
266-
logger.error(f"error: {exc}")
266+
log_error(f"error: {exc}")
267267
return None
268268

269269
return None
270270

271271

272272
def validate_html_to_docling_document(text: str) -> bool:
273-
logger.info("validate_html_to_docling_document")
273+
log_info("validate_html_to_docling_document")
274274
return convert_html_to_docling_document(text) is not None
275275

276276

277277
def insert_document(*, item: NodeItem, doc: DoclingDocument, updated_doc: DoclingDocument) -> DoclingDocument:
278-
logger.info(f"insert_document: item={item.self_ref}")
278+
log_info(f"insert_document: item={item.self_ref}")
279279

280280
group_item = GroupItem(
281281
label=GroupLabel.UNSPECIFIED,
@@ -295,10 +295,10 @@ def insert_document(*, item: NodeItem, doc: DoclingDocument, updated_doc: Doclin
295295
to_item[_item.self_ref] = group_item
296296

297297
elif _item.parent is None:
298-
logger.error(f"Item with null parent: {_item}")
298+
log_error(f"Item with null parent: {_item}")
299299

300300
elif _item.parent.cref not in to_item:
301-
logger.error(f"Item with unknown parent: {_item}")
301+
log_error(f"Item with unknown parent: {_item}")
302302

303303
elif isinstance(_item, GroupItem):
304304
gr = doc.add_group(
@@ -341,7 +341,7 @@ def insert_document(*, item: NodeItem, doc: DoclingDocument, updated_doc: Doclin
341341
to_item[_item.self_ref] = te
342342

343343
else:
344-
logger.warning(f"No support to insert items of type: {type(item).__name__}")
344+
log_warning(f"No support to insert items of type: {type(item).__name__}")
345345

346346
return doc
347347

@@ -353,7 +353,7 @@ def insert_document(*, item: NodeItem, doc: DoclingDocument, updated_doc: Doclin
353353

354354
def get_item_by_ref(doc: DoclingDocument, ref: str) -> NodeItem | None:
355355
"""Resolve a self_ref string to a NodeItem. Returns None on failure."""
356-
logger.info(f"get_item_by_ref: ref={ref!r}")
356+
log_info(f"get_item_by_ref: ref={ref!r}")
357357
try:
358358
return RefItem(cref=ref).resolve(doc)
359359
except Exception:
@@ -368,7 +368,7 @@ def collect_subtree_text(node: NodeItem, doc: DoclingDocument) -> str:
368368
Non-text nodes (TableItem, PictureItem, GroupItem) are traversed for their
369369
children but do not contribute text directly.
370370
"""
371-
logger.info(f"collect_subtree_text: node={node.self_ref!r}")
371+
log_info(f"collect_subtree_text: node={node.self_ref!r}")
372372
parts: list[str] = []
373373
if hasattr(node, "text") and node.text:
374374
parts.append(node.text)
@@ -389,7 +389,7 @@ def _copy_list_group(
389389
target_doc: DoclingDocument,
390390
parent: NodeItem,
391391
) -> ListGroup:
392-
logger.info(f"_copy_list_group: source={source.self_ref!r}")
392+
log_info(f"_copy_list_group: source={source.self_ref!r}")
393393
new_group = target_doc.add_list_group(parent=parent)
394394
new_group.meta = source.meta
395395
for child_ref in source.children or []:
@@ -411,7 +411,7 @@ def _copy_list_group(
411411
except Exception:
412412
pass
413413
except Exception as exc:
414-
logger.warning(f"Could not copy list child: {exc}")
414+
log_warning(f"Could not copy list child: {exc}")
415415
return new_group
416416

417417

@@ -421,7 +421,7 @@ def _copy_table(
421421
target_doc: DoclingDocument,
422422
parent: NodeItem,
423423
) -> TableItem:
424-
logger.info(f"_copy_table: source={source.self_ref!r}")
424+
log_info(f"_copy_table: source={source.self_ref!r}")
425425
new_table = target_doc.add_table(data=source.data, parent=parent)
426426
new_table.meta = source.meta
427427
for cap_ref in source.captions:
@@ -432,7 +432,7 @@ def _copy_table(
432432
new_cap.meta = cap.meta
433433
new_table.captions.append(new_cap.get_ref())
434434
except Exception as exc:
435-
logger.warning(f"Could not copy table caption: {exc}")
435+
log_warning(f"Could not copy table caption: {exc}")
436436
return new_table
437437

438438

@@ -442,7 +442,7 @@ def _copy_picture(
442442
target_doc: DoclingDocument,
443443
parent: NodeItem,
444444
) -> PictureItem:
445-
logger.info(f"_copy_picture: source={source.self_ref!r}")
445+
log_info(f"_copy_picture: source={source.self_ref!r}")
446446
new_pic = target_doc.add_picture(image=source.image, parent=parent)
447447
new_pic.meta = source.meta
448448
for cap_ref in source.captions:
@@ -453,7 +453,7 @@ def _copy_picture(
453453
new_cap.meta = cap.meta
454454
new_pic.captions.append(new_cap.get_ref())
455455
except Exception as exc:
456-
logger.warning(f"Could not copy picture caption: {exc}")
456+
log_warning(f"Could not copy picture caption: {exc}")
457457
return new_pic
458458

459459

@@ -464,12 +464,12 @@ def _flatten_into(
464464
target_parent: NodeItem,
465465
) -> None:
466466
"""Recursively add node's children to target_parent, preserving atomic units."""
467-
logger.info(f"_flatten_into: node={node.self_ref!r}")
467+
log_info(f"_flatten_into: node={node.self_ref!r}")
468468
for child_ref in node.children or []:
469469
try:
470470
child = child_ref.resolve(source_doc)
471471
except Exception as exc:
472-
logger.warning(f"Could not resolve child {child_ref}: {exc}")
472+
log_warning(f"Could not resolve child {child_ref}: {exc}")
473473
continue
474474

475475
if isinstance(child, ListGroup):
@@ -487,7 +487,7 @@ def _flatten_into(
487487
new_item.meta = child.meta
488488
_flatten_into(child, source_doc, target_doc, target_parent)
489489
elif isinstance(child, ListItem):
490-
logger.warning(f"ListItem {child.self_ref} found outside a ListGroup; skipping")
490+
log_warning(f"ListItem {child.self_ref} found outside a ListGroup; skipping")
491491
elif isinstance(child, GroupItem):
492492
# Dissolve other groups (recurse into children without adding the group)
493493
_flatten_into(child, source_doc, target_doc, target_parent)
@@ -498,13 +498,13 @@ def _flatten_into(
498498

499499
def make_flat_document(doc: DoclingDocument) -> DoclingDocument:
500500
"""Normalize the document in place with Docling's native heading flattening."""
501-
logger.info(f"make_flat_document: doc={doc.name!r}")
501+
log_info(f"make_flat_document: doc={doc.name!r}")
502502
doc._flatten()
503503
return doc
504504

505505

506506
def make_hierarchical_document(doc: DoclingDocument) -> DoclingDocument:
507507
"""Normalize the document in place with Docling's native hierarchy normalization applied."""
508-
logger.info(f"make_hierarchical_document: doc={doc.name!r}")
508+
log_info(f"make_hierarchical_document: doc={doc.name!r}")
509509
doc._hierarchize()
510510
return doc

0 commit comments

Comments
 (0)