Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev logging #304

Merged
merged 48 commits into from
Apr 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
2aa4f62
bump version
jacob-rosenthal Feb 7, 2022
c0a30d6
Merge pull request #290 from Dana-Farber-AIOS/release-2.0.4
jacob-rosenthal Feb 7, 2022
20c84df
pin working pip version in Dockerfile
jacob-rosenthal Feb 7, 2022
1ad212c
Add option to manually trigger docker Action
jacob-rosenthal Feb 7, 2022
acaef6c
pin spams version in dockerfile
jacob-rosenthal Feb 7, 2022
b73a516
Update README.md
surya-narayanan Feb 9, 2022
d046c12
clean up installation instructions; add troubleshooting section
jacob-rosenthal Feb 9, 2022
2352127
remove old sentences
jacob-rosenthal Feb 9, 2022
8d96849
set up a logger with varying levels to track the four main files of t…
BeeGass Feb 21, 2022
bf9f49e
added the imports for loguru
BeeGass Feb 21, 2022
7e64b94
Merge pull request #298 from Dana-Farber-AIOS/surya-narayanan-safe-wo…
jacob-rosenthal Feb 22, 2022
390a59a
Got all the base logging stuff figured out. There was a misunderstand…
BeeGass Feb 28, 2022
f1ae9e7
all errors that got raised with some message to the user is now logged
BeeGass Feb 28, 2022
be3f79a
somewhat brute forcing the fixes on logging at the moment. Log files …
BeeGass Mar 2, 2022
d05a741
changed the bash script to recognize if the directory exists before c…
BeeGass Mar 2, 2022
c772da2
need to still remove wrappers, add dependecies, save logs to consiste…
BeeGass Mar 9, 2022
d8936e9
need to still remove wrappers, save logs to consistent file path and …
BeeGass Mar 9, 2022
fa974be
add logging function to docs
jacob-rosenthal Mar 9, 2022
f1261f4
added global variable call in enable_logging(), also making sure lint…
BeeGass Mar 9, 2022
d2bb067
logging is now functional, tests have been built to (naively) test fo…
BeeGass Mar 14, 2022
bdb62f2
changed enable_logging() to configure the logger.
BeeGass Mar 14, 2022
9c2d6f1
updates to logs and log tests
jacob-rosenthal Mar 16, 2022
2ce8611
trying to get logger.configure to work within a function
BeeGass Mar 17, 2022
56007cf
currently not working but think I might have found a way to get a one…
BeeGass Mar 21, 2022
2f6c343
Logging is now functional through the use of a single function call w…
BeeGass Mar 22, 2022
1842a81
updates to logging implementation
jacob-rosenthal Mar 23, 2022
514b363
fixed logger warnings that were making tests fail
BeeGass Mar 23, 2022
60d051c
format for log handler in tests
jacob-rosenthal Mar 23, 2022
9681e53
got rid of test that used logging_example() and tests are running again
BeeGass Mar 23, 2022
9961f1f
removed bindings to logger in h5manager
BeeGass Mar 23, 2022
a8fb928
squash this commit, removed import * from all pathml modules
BeeGass Mar 28, 2022
498344b
Implemented logging and associated tests.
BeeGass Mar 28, 2022
50d143c
Merge branch 'dev-logging' of github.com:Dana-Farber-AIOS/pathml into…
BeeGass Mar 28, 2022
6707252
update docs and clean up logging
jacob-rosenthal Mar 28, 2022
9d76f9f
Merge branch 'dev-logging' of github.com:Dana-Farber-AIOS/pathml into…
jacob-rosenthal Mar 28, 2022
d7032ba
fix logging tests
jacob-rosenthal Mar 28, 2022
3dde444
remove extra files and dirs
jacob-rosenthal Mar 28, 2022
aec565f
clean up logging tests
jacob-rosenthal Mar 28, 2022
3fdc786
separate enable and disable methods for logging. Fix tests
jacob-rosenthal Mar 28, 2022
941f9a0
add logging for backends
jacob-rosenthal Apr 4, 2022
264c85b
add logging for dask clients
jacob-rosenthal Apr 5, 2022
6209d71
minor updates to logger
jacob-rosenthal Apr 5, 2022
fb23232
Merge branch 'dev' into dev-logging
jacob-rosenthal Apr 5, 2022
0fb0871
add loguru to env file
jacob-rosenthal Apr 5, 2022
b4b666a
Merge branch 'dev-logging' of github.com:Dana-Farber-AIOS/pathml into…
jacob-rosenthal Apr 5, 2022
527ed03
revert changes to codex example
jacob-rosenthal Apr 5, 2022
d2892f4
remove logs inside exceptions
jacob-rosenthal Apr 5, 2022
bf9fbb0
remove unused reshape method
jacob-rosenthal Apr 5, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion .github/workflows/publish-to-docker-hub.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
name: Publish PathML Docker image on Docker Hub

on:
workflow_dispatch:
release:
types: [published]
types:
- published

jobs:
docker:
Expand Down
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@ COPY pathml/ /opt/pathml/pathml
COPY tests/ /opt/pathml/tests

# install pathml and deepcell
RUN pip3 install --upgrade pip \
&& pip3 install numpy==1.19.5 spams \
RUN pip3 install pip==21.3.1 \
&& pip3 install numpy==1.19.5 spams==2.6.2.5 \
&& pip3 install python-bioformats==4.0.0 deepcell /opt/pathml/ pytest

# run tests to verify container
Expand Down
5 changes: 5 additions & 0 deletions docs/source/api_utils_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ Utilities API

Documentation for various utilities from all modules.

Logging Utils
-------------

.. autoapiclass:: pathml.PathMLLogger

Core Utils
----------

Expand Down
1 change: 1 addition & 0 deletions environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,4 @@ dependencies:
- scanpy==1.8.2
- anndata==0.7.8
- tqdm==4.62.3
- loguru==0.5.3
1 change: 1 addition & 0 deletions pathml/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@
from . import datasets as ds
from . import ml
from . import preprocessing as pp
from ._logging import PathMLLogger
from ._version import __version__
96 changes: 96 additions & 0 deletions pathml/_logging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"""
Copyright 2021, Dana-Farber Cancer Institute and Weill Cornell Medicine
License: GNU GPL 2.0
"""

from loguru import logger
import functools
import sys


class PathMLLogger:
"""
Convenience methods for turning on or off and configuring logging for PathML.
Note that this can also be achieved by interfacing with loguru directly

Example::

from pathml import PathMLLogger as pml

# turn on logging for PathML
pml.enable()

# turn off logging for PathML
pml.disable()

# turn on logging and output logs to a file named 'logs.txt', with colorization enabled
pml.enable(sink="logs.txt", colorize=True)
"""

logger.disable("pathml")
logger.disable(__name__)

@staticmethod
def disable():
"""
Turn off logging for PathML
"""
logger.disable("pathml")
logger.disable(__name__)
logger.info(
"Disabled Logging For PathML! If you are seeing this, there is a problem"
)

@staticmethod
def enable(
sink=sys.stderr,
level="DEBUG",
fmt="PathML:{level}:{time:HH:mm:ss} | {module}:{function}:{line} | {message}",
**kwargs
):
"""
Turn on and configure logging for PathML

Args:
sink (str or io._io.TextIOWrapper, optional):
Destination sink for log messages. Defaults to ``sys.stderr``.
level (str):
level of logs to capture. Defaults to 'DEBUG'.
fmt (str):
Formatting for the log message. Defaults to: 'PathML:{level}:{time:HH:mm:ss} | {module}:{function}:{line} | {message}'
**kwargs (dict, optional):
additional options passed to configure logger. See:
`loguru documentation <https://loguru.readthedocs.io/en/stable/api/logger.html#loguru._logger.Logger.add>`_
"""
logger.enable("pathml")
logger.enable(__name__)
# remove pre-configured logger (https://github.com/Delgan/loguru/issues/208#issuecomment-581002215)
logger.remove(0)
handler_id = logger.add(sink=sink, level=level, format=fmt, **kwargs)
logger.info("Enabled Logging For PathML!")
return handler_id


# courtesy of the people at loguru
# https://loguru.readthedocs.io/en/stable/resources/recipes.html#:~:text=or%20fallback%20policy.-,Logging%20entry%20and%20exit%20of%20functions%20with%20a%20decorator,-%EF%83%81
def logger_wraps(*, entry=True, exit=True, level="DEBUG"):
def wrapper(func):
name = func.__name__

@functools.wraps(func)
def wrapped(*args, **kwargs):
logger_ = logger.opt(depth=1)
if entry:
logger_.bind(enter_exit=True).log(
level, "Entering '{}' (args={}, kwargs={})", name, args, kwargs
)
result = func(*args, **kwargs)
if exit:
logger_.bind(enter_exit=True).log(
level, "Exiting '{}' (result={})", name, result
)
return result

return wrapped

return wrapper
2 changes: 1 addition & 1 deletion pathml/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
License: GNU GPL 2.0
"""

__version__ = "2.0.3"
__version__ = "2.0.4"
15 changes: 8 additions & 7 deletions pathml/core/h5managers.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from collections import OrderedDict

import anndata
from loguru import logger
import h5py
import numpy as np
import pathml.core
Expand Down Expand Up @@ -95,7 +96,7 @@ def add_tile(self, tile):
tile(pathml.core.tile.Tile): Tile object
"""
if str(tile.coords) in self.h5["tiles"].keys():
print(f"Tile is already in tiles. Overwriting {tile.coords} inplace.")
logger.info(f"Tile is already in tiles. Overwriting {tile.coords} inplace.")
# remove old cells from self.counts so they do not duplicate
if tile.counts:
if "tile" in self.counts.obs.keys():
Expand All @@ -114,7 +115,6 @@ def add_tile(self, tile):
raise ValueError(
f"cannot add tile of shape {tile.image.shape}. Must match shape of existing tiles: {existing_shape}"
)

if self.slide_type and tile.slide_type:
# check that slide types match
if tile.slide_type != self.slide_type:
Expand All @@ -127,7 +127,7 @@ def add_tile(self, tile):

# create a group for tile and write tile
if str(tile.coords) in self.h5["tiles"]:
print(f"overwriting tile at {str(tile.coords)}")
logger.info(f"overwriting tile at {str(tile.coords)}")
del self.h5["tiles"][str(tile.coords)]
self.h5["tiles"].create_group(str(tile.coords))
self.h5["tiles"][str(tile.coords)].create_dataset(
Expand Down Expand Up @@ -155,7 +155,9 @@ def add_tile(self, tile):
# add tile-level masks
for key, mask in tile.masks.items():
self.h5["tiles"][str(tile.coords)]["masks"].create_dataset(
str(key), data=mask, dtype="float16",
str(key),
data=mask,
dtype="float16",
)

# add coords
Expand Down Expand Up @@ -209,8 +211,7 @@ def get_tile(self, item):
item = list(self.h5["tiles"].keys())[item]
else:
raise KeyError(
f"invalid item type: {type(item)}. must getitem by coord (type tuple[int]),"
f"index (type int), or name (type str)"
f"invalid item type: {type(item)}. must getitem by coord (type tuple[int]), index (type int), or name (type str)"
)
tile = self.h5["tiles"][item]["array"][:]

Expand Down Expand Up @@ -339,7 +340,7 @@ def remove_mask(self, key):
f"masks keys must be of type(str) but key was passed of type {type(key)}"
)
if key not in self.h5["masks"].keys():
raise KeyError("key is not in Masks")
raise KeyError(f"key is not in Masks")
del self.h5["masks"][key]

def get_slidetype(self):
Expand Down
3 changes: 2 additions & 1 deletion pathml/core/masks.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from collections import OrderedDict
import h5py
import reprlib
from loguru import logger

import pathml.core.h5managers

Expand All @@ -31,7 +32,7 @@ def __init__(self, h5manager, masks=None):
if masks:
if not isinstance(masks, dict):
raise ValueError(
f"masks must be passed as dicts of the form key1:mask1,key2:mask2,..."
"masks must be passed as dicts of the form {key1:mask1, key2:mask2, ...}"
)
for val in masks.values():
if not isinstance(val, np.ndarray):
Expand Down