question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Logging to an output widget (as opposed to print with context manager)

See original GitHub issue

Following discussion with @jasongrout, a rough version of how I accomplished logging to an Output widget.

Benefits of this method are:

  • Avoid repeated calls to with output: and print throughout code
  • Can configure several logging with different handlers; route your logging messages to different Output widgets.

The particular configuration I used here means that logging messages always appear on top of the Output widget, and force newer messages to the bottom.

Credit: https://stackoverflow.com/questions/3290292/read-from-a-log-file-as-its-being-written-using-python for the code to subclass the handler and extend the emit() method.

import logging
from colorama import Fore
import ipywidgets as ipyw

out = ipyw.Output(layout=ipyw.Layout(width='600px', height='160px', border='solid'))

class log_viewer(logging.Handler):
    """ Class to redistribute python logging data """

    # have a class member to store the existing logger
    logger_instance = logging.getLogger("__name__")

    def __init__(self, *args, **kwargs):
         # Initialize the Handler
         logging.Handler.__init__(self, *args)

         # optional take format
         # setFormatter function is derived from logging.Handler
         for key, value in kwargs.items():
             if "{}".format(key) == "format":
                 self.setFormatter(value)

         # make the logger send data to this class
         self.logger_instance.addHandler(self)

    def emit(self, record):
        """ Overload of logging.Handler method """

        record = self.format(record)
        out.outputs = ({'name': 'stdout', 'output_type': 'stream', 'text': (Fore.BLACK + (record + '\n'))},) + out.outputs

main_logger = logging.getLogger(__name__)
main_logger.addHandler(log_viewer())
main_logger.setLevel(20)   # log at info level.

You can log to the widget from anywhere (provided you have imported main_logger) by calling `main_logger.info(‘msg text’), and possibly alter the color (hence colorama).

Issue Analytics

  • State:open
  • Created 6 years ago
  • Reactions:1
  • Comments:6 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
sthapacommented, Nov 18, 2018

I’ve created a pull request https://github.com/jupyter-widgets/ipywidgets/pull/2268 to implement the convenience function, if it looks good, I’ll update the docs based on the function.

1reaction
jasongroutcommented, Jun 16, 2018
Read more comments on GitHub >

github_iconTop Results From Across the Web

Output widgets: leveraging Jupyter's display system - ipywidgets
After the widget is created, direct output to it using a context manager. You can print text to the output area:
Read more >
why cannot I print in jupyter lab using ipywidgets class?
Ipywidget documentation: the output from _on_click is directed to output by using either a context manager with self.output: over print() ...
Read more >
contextlib — Utilities for with-statement contexts ... - Python Docs
This module provides utilities for common tasks involving the with statement. For more information see also Context Manager Types and With Statement Context ......
Read more >
Jupyterlab output in log rather than cell
You need to add in the context manager to your run_service function. To do it like that, you need to have assigned your...
Read more >
Debugging Widgets | ServiceNow Developer
data or Log to console: $scope Widget Context menu items to write object properties and values to the console. To access the ˆ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found