Logging#

Scipp is generally quiet because it mostly provides low level components. It can however produce warnings and some functions (e.g. scipp.transform_coords) log at the info level. For this purpose, scipp defines a logger which allows customizing how those warnings and errors are reported.

The logger is an instance of logging.Logger with name ‘scipp’. It has no handlers by default and needs to be configured using the logging module of the standard library.

[1]:
import scipp as sc
logger = sc.get_logger()

You can silence Scipp’s info messages if they get in your way using

[2]:
logger.setLevel('WARNING')

For illustration purposes, install a basic logging.StreamHandler and enable logging of info messages:

[3]:
import logging
stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
logger.addHandler(stream_handler)
logger.setLevel(logging.INFO)
[4]:
logger.info('The stream handler simply prints messages')
The stream handler simply prints messages

Jupyter Log Widget#

When running in Jupyter notebooks, scipp.logging provides a special handler which sends messages to a widget. It can be added like any other handler. Once Scipp’s logger has a WidgetHandler, scipp.display_logs can be used to render its widget in a notebook.

[5]:
# This only works in a Jupyter notebook.
logger.addHandler(sc.logging.make_widget_handler())
[6]:
sc.display_logs()

(Click and drag the bottom right corner to increase the size of the widget if it is too small.)

[7]:
logger.info('This shows up in the widget and error stream.')
This shows up in the widget and error stream.

scipp.logging provides a number of high level convenience functions for managing log widgets and handlers. See the module documentation for more details.

TIP

In Jupyter lab, you can show the widget in a separate tab and keep it visible. To do so, right-click the widget and select ‘Create New View for Output’.

Formatting Scipp Objects#

The widget can display the HTML representation of Scipp containers (Variable, DataArray, Dataset):

[8]:
logger.info(sc.arange('x', 0, 5))
<scipp.Variable> (x: 5)      int64  [dimensionless]  [0, 1, ..., 3, 4]

It is also possible to embed Scipp containers in strings using %-formatting:

[9]:
logger.info('The HTML representation of a Variable: %s',
            sc.arange('h', 10, 15))
The HTML representation of a Variable: <scipp.Variable> (h: 5)      int64  [dimensionless]  [10, 11, ..., 13, 14]

Or use %r to display a plain string representation:

[10]:
logger.info('A Variable converted to string: %r',
            sc.arange('r', 100, 105))
A Variable converted to string: <scipp.Variable> (r: 5)      int64  [dimensionless]  [100, 101, ..., 103, 104]

Our stream_handler and other handlers behave as normal and produce the string representation of Scipp objects unless endowed with a custom formatter.