Skip to content

Instantly share code, notes, and snippets.

@damontallen
Created February 3, 2023 19:48
Show Gist options
  • Save damontallen/6997a715371287be73a4011c5dd87c35 to your computer and use it in GitHub Desktop.
Save damontallen/6997a715371287be73a4011c5dd87c35 to your computer and use it in GitHub Desktop.
Logging example for Jupyter Lab Notebook
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "849875e9-aae4-47fe-8136-5a1a68a8c62e",
"metadata": {},
"source": [
"Based on the information found in the video \"[Python Decorators: The Complete Guide](https://www.youtube.com/watch?v=QH5fw9kxDQA)\" and a post on [stackoverflow](https://stackoverflow.com/questions/18786912/get-output-from-the-logging-module-in-ipython-notebook)."
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "be14af80-28c6-4bbb-ab8a-dd887bde65b2",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"DEBUG:root:test\n",
"INFO:root:Calling add\n",
"INFO:root:Finished calling add\n"
]
},
{
"data": {
"text/plain": [
"4"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"import functools\n",
"# functools is use to maintain the __name__ consistancy of what is being logged\n",
"import logging\n",
"# To allow logging messages to be displayed in jupyterlab\n",
"# a logger must be gotten and the level of logging must be set.\n",
"logger = logging.getLogger()\n",
"logger.setLevel(logging.DEBUG)\n",
"logging.debug(\"test\")\n",
"\n",
"\n",
"def with_logging(func):\n",
" @functools.wraps(func) # allows func to maintain its original name\n",
" def wrapper(*args, **kwargs):\n",
" logging.info(f\"Calling {func.__name__}\")\n",
" value = func(*args, **kwargs)\n",
" logging.info(f\"Finished calling {func.__name__}\")\n",
" return value\n",
" return wrapper\n",
"\n",
"\n",
"@with_logging # now adds logging messages to this function\n",
"def add(a=0, b=0):\n",
" return a+b\n",
"\n",
"\n",
"add(2, 2)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.1"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment