Skip to content

Commit 4969b2f

Browse files
authored
Merge pull request #169 from hanjinliu/logger
Improve logger
2 parents b0ffdac + c8f32f6 commit 4969b2f

File tree

4 files changed

+35
-36
lines changed

4 files changed

+35
-36
lines changed

magicclass/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
__version__ = "0.7.20"
1+
__version__ = "0.7.21"
22

33
from magicclass.core import (
44
magicclass,

magicclass/logging/core.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,7 @@ def print_table(
4343
width: int | None = None,
4444
header_style: str | None = None,
4545
):
46-
"""
47-
Print object as a table in the logger widget.
46+
"""Print object as a table in the logger widget.
4847
4948
Parameters
5049
----------
@@ -113,8 +112,7 @@ def setLevel(self, level) -> None:
113112

114113

115114
def getLogger(name: str | None = None, show: bool = False) -> MagicClassLogger:
116-
"""
117-
Get a magicclass logger.
115+
"""Get a magicclass logger.
118116
119117
The returned logger has a name specific logger widget. Many method of
120118
`magicclass.widgets.Logger` are also available.

magicclass/widgets/logger.py

Lines changed: 27 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -169,12 +169,15 @@ def update(self, output: tuple[int, Printable]):
169169
linkFormat.setAnchor(True)
170170
linkFormat.setAnchorHref(linkedstr.link)
171171
linkFormat.setFontUnderline(True)
172-
linkFormat.setForeground(QtGui.QBrush(QtGui.QColor("blue")))
172+
bgcolor = self._get_background_color()[:3]
173+
if sum(bgcolor) < 382.5: # 255*3/2, dark background
174+
linkFormat.setForeground(QtGui.QBrush(QtGui.QColor("cyan")))
175+
else:
176+
linkFormat.setForeground(QtGui.QBrush(QtGui.QColor("blue")))
173177
cursor.insertText(linkedstr.text, linkFormat)
174178
else:
175179
raise TypeError("Wrong type.")
176180
self._post_append()
177-
return None
178181

179182
def appendText(self, text: str):
180183
"""Append text in the main thread."""
@@ -300,6 +303,10 @@ def mouseMoveEvent(self, e: QtGui.QMouseEvent) -> None:
300303
self.viewport().setCursor(
301304
Qt.CursorShape.PointingHandCursor if _anchor else Qt.CursorShape.IBeamCursor
302305
)
306+
if _anchor:
307+
self.setToolTip(f"Open in browser: {_anchor}")
308+
else:
309+
self.setToolTip("")
303310
return super().mouseMoveEvent(e)
304311

305312
def mouseReleaseEvent(self, e: QtGui.QMouseEvent):
@@ -320,8 +327,7 @@ def keyPressEvent(self, e: QtGui.QKeyEvent):
320327

321328

322329
class Logger(Widget, logging.Handler):
323-
"""
324-
A widget for logging.
330+
"""A widget for logging.
325331
326332
Examples
327333
--------
@@ -389,30 +395,25 @@ def emit(self, record):
389395
"""Handle the logging event."""
390396
msg = self.format(record)
391397
self.print(msg)
392-
return None
393398

394399
def clear(self):
395400
"""Clear all the histories."""
396401
self.native.clear()
397-
return None
398402

399403
def print(self, *msg, sep=" ", end="\n"):
400404
"""Print things in the end of the logger widget."""
401405
self.native.appendText(sep.join(map(str, msg)) + end)
402-
return None
403406

404407
def print_html(self, html: str, end="<br></br>"):
405408
"""Print things in the end of the logger widget using HTML string."""
406409
self.native.appendHtml(html + end)
407-
return None
408410

409411
def print_rst(self, rst: str, end="\n"):
410412
"""Print things in the end of the logger widget using rST string."""
411413
html = rst_to_html(rst, unescape=False)
412414
if end == "\n":
413415
end = "<br></br>"
414416
self.native.appendHtml(html + end)
415-
return None
416417

417418
def print_table(
418419
self,
@@ -424,8 +425,7 @@ def print_table(
424425
width: int | None = None,
425426
header_style: str | None = None,
426427
):
427-
"""
428-
Print object as a table in the logger widget.
428+
"""Print object as a table in the logger widget.
429429
430430
Parameters
431431
----------
@@ -469,7 +469,7 @@ def _str(val: Any):
469469
return str(val)
470470

471471
if isinstance(table, Mapping):
472-
header = list(table.keys())
472+
_header = list(table.keys())
473473
columns = list(table.values())
474474
rows: list[list[str]] = []
475475
nrows = max(len(col) for col in columns)
@@ -491,23 +491,26 @@ def _str(val: Any):
491491
rows.append(row)
492492
ncols = max(len(row), ncols)
493493

494-
header = list(range(ncols))
495494
# fill empty cells
496495
for row in rows:
497496
if len(row) < ncols:
498497
row.extend([""] * (ncols - len(row)))
498+
_header = list(range(ncols))
499499
# make HTML table
500-
_head_html = (
501-
'<tr style="text-align: right;">'
502-
+ "".join(f"<th>{h}</th>" for h in header)
503-
+ "</tr>"
504-
)
500+
if header:
501+
_head_html = (
502+
'<tr style="text-align: right;">'
503+
+ "".join(f"<th>{h}</th>" for h in _header)
504+
+ "</tr>"
505+
)
506+
_head_html = f"<thead>{_head_html}</thead>"
507+
else:
508+
_head_html = ""
505509
_body_html = "".join(
506510
f"<tr>{''.join(f'<td>{c}</td>' for c in row)}</tr>" for row in rows
507511
)
508512
html = (
509-
f'<table width="{width}" border="1" class="dataframe">'
510-
f'<thead>{_head_html}</thead>'
513+
f'<table width="{width}" border="1" class="dataframe">{_head_html}'
511514
f'<tbody>{_body_html}</tbody>'
512515
f'</table>'
513516
) # fmt: skip
@@ -558,26 +561,22 @@ def print_image(
558561
)
559562

560563
self.native.appendImage(image)
561-
return None
562564

563-
def print_link(self, text: str, href: str):
565+
def print_link(self, text: str, href: str, end: str = "\n"):
564566
"""Print a link in the logger widget."""
565-
self.native.appendHref(text, href)
566-
return None
567+
self.native.appendHref(text + end, href)
567568

568569
def print_figure(self, fig: mpl_Figure | FigureManagerBase) -> None:
569570
"""Print matplotlib Figure object like inline plot."""
570571
import numpy as np
571572

572573
fig.canvas.draw()
573574
data = np.asarray(fig.canvas.renderer.buffer_rgba(), dtype=np.uint8)
574-
self.print_image(data)
575-
return None
575+
self.print_image(data, width=data.shape[1] // 3)
576576

577577
def write(self, msg) -> None:
578578
"""Handle the print event."""
579579
self.print(msg, end="")
580-
return None
581580

582581
def flush(self):
583582
"""Do nothing."""
@@ -643,7 +642,7 @@ def set_plt(self, style: str | None = None, rc_context: dict[str, Any] = {}):
643642
style = "default"
644643

645644
if "figure.dpi" not in rc_context:
646-
rc_context["figure.dpi"] = 800
645+
rc_context["figure.dpi"] = 300
647646
if "figure.figsize" not in rc_context:
648647
rc_context["figure.figsize"] = (4, 3)
649648
backend = mpl.get_backend()
Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
11
from magicclass.widgets import Logger
2+
import matplotlib.pyplot as plt
23

34
def test_logger():
45
log = Logger()
56
log.print("Hello")
6-
log.print_table({"a": [1, 2], "b": [3, 4]})
7-
log.print_table([["a", "b"], [4, -1], [4.3, None]])
7+
log.print_table({"a": [1, 2], "b": [3, 4]}, header=True)
8+
log.print_table({"a": [1, 2], "b": [3, 4]}, header=False)
9+
log.print_table([["a", "b"], [4, -1], [4.3, None]], header=True)
10+
log.print_table([["a", "b"], [4, -1], [4.3, None]], header=False)
811
log.print_html("<b>bold</b>")
912
with log.set_stdout():
1013
print("Hello")
1114
with log.set_plt():
12-
import matplotlib.pyplot as plt
1315
plt.plot([1, 2, 3])
1416
log.clear()

0 commit comments

Comments
 (0)