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

adding logging to io.genomio.fasta.process #206

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/python/ensembl/io/genomio/fasta/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,13 @@
from Bio import SeqIO

from ensembl.io.genomio.utils.archive_utils import open_gz_file
from ensembl.io.genomio.utils.logging import setup_logging
from ensembl.utils.argparse import ArgumentParser

# logging references module, but can be overridden by a specific logger
import logging
logger = logging # by default
Copy link
Contributor Author

@vsitnik vsitnik Nov 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or we can just replace logger with logging and do something like

logging = None
import logging
def ...
    logging.info(...)

def main:
    ...
    logging = setup_logging(...)
    ...    

Or make a more cruel thing.
Just treat import logging as definition of a global var. So just

#  logging = None
import logging

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was not happy with the logger approach either, so that is why I have opted for accessing the logging.root instead in my PR.

Copy link
Contributor Author

@vsitnik vsitnik Nov 13, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the reassigning of logging way,
because in this case you're allowing the module to be used/imported from the outside without calling main function and setup we have in it.
So if you use main -- you define your own logger (however prettified) and assign it to global logging (replacing it, basically).
But if you import this module from outside, you preserve logging default settings (perhaps, already modified by the calling/upstream code).

In this case this module itself doesn't import other models with logging.
I think, it's worth to update the root logger to propagate changes downstream, instead as in your PR !207.



exclude_seq_regions: List[str] = []

Expand All @@ -41,13 +46,14 @@ def get_peptides_to_exclude(genbank_path: PathLike, seqr_to_exclude: Set[str]) -
with open_gz_file(genbank_path) as in_genbank:
for record in SeqIO.parse(in_genbank, "genbank"):
if record.id in seqr_to_exclude:
print(f"Skip sequence {record.id}")
logger.info(f"Skip sequence {record.id}")
for feat in record.features:
if feat.type == "CDS":
if "protein_id" in feat.qualifiers:
feat_id = feat.qualifiers["protein_id"]
peptides_to_exclude.add(feat_id[0])
else:
logger.critical(f"Peptide without peptide ID ${feat}")
raise GFFParserError(f"Peptide without peptide ID ${feat}")
return peptides_to_exclude

Expand Down Expand Up @@ -82,7 +88,7 @@ def prep_fasta_data(
with open_gz_file(file_path) as in_fasta:
for record in SeqIO.parse(in_fasta, "fasta"):
if record.id in to_exclude:
print(f"Skip record ${record.id}")
logger.info(f"Skip record ${record.id}")
else:
records.append(record)
with Path(fasta_outfile).open("w") as out_fasta:
Expand All @@ -96,6 +102,11 @@ def main() -> None:
parser.add_argument_src_path("--genbank_infile", help="Input GenBank GBFF file")
parser.add_argument_dst_path("--fasta_outfile", required=True, help="Output FASTA file")
parser.add_argument("--peptide_mode", action="store_true", help="Process proteins instead of DNA")
parser.add_argument("-v", "--verbose", action="store_true", help="Verbose level logging")
parser.add_argument("-d", "--debug", action="store_true", help="Debug level logging")
parser.add_argument("-l", "--logfile", required=False, type=str, help="file to log to")
args = parser.parse_args()

logger = setup_logging(args, name = __name__)

prep_fasta_data(**vars(args))
1 change: 1 addition & 0 deletions src/python/ensembl/io/genomio/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@

from .archive_utils import *
from .json_utils import *
from .logging import *
79 changes: 79 additions & 0 deletions src/python/ensembl/io/genomio/utils/logging.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utils to deal with logging."""

__all__ = ["setup_logging"]

import argparse
import logging
from typing import Optional


# default logging formats
LOGGING_FORMAT = "%(asctime)s\t%(levelname)s\t%(message)s"
DATE_FORMAT = r"%Y-%m-%d_%H:%M:%S"

# helper functions
def _prepare_console_handler(*, debug: bool = False, verbose: bool = False) -> logging.StreamHandler:
"""setup console handler with different logging levels"""
console_h = logging.StreamHandler()
# set default logging level
if debug:
console_h.setLevel(logging.DEBUG)
elif verbose:
console_h.setLevel(logging.INFO)
return console_h


def _prepare_file_handler(filename: Optional[str] = None, *, debug: bool = False) -> Optional[logging.FileHandler]:
"""setup file handler with default loggin.INFO level"""
"""retuns None if no file name defined"""
if filename is None:
return None

file_h = logging.FileHandler(filename)

file_h.setLevel(logging.INFO)
if debug:
file_h.setLevel(logging.DEBUG)

return file_h


def setup_logging(
args: argparse.Namespace,
*, # no positional arguments allowed after this
name: Optional[str] = None,
) -> logging.Logger:
"""Setup logging infrustucture."""
"""args: argparse.Namespace -- args with "debug", "verbose" and "logfile" options."""
# get logger with a specified name (or the default one)
logger = logging.getLogger(name)

# set up shared formatter
formatter = logging.Formatter(fmt = LOGGING_FORMAT, datefmt = DATE_FORMAT)

# adding console handler
console_h = _prepare_console_handler(debug = args.debug, verbose = args.verbose)
console_h.setFormatter(formatter)
logger.addHandler(console_h)

# adding logging to file
file_h = _prepare_file_handler(args.logfile)
if file_h:
file_h.setFormatter(formatter)
logger.addHandler(file_h)

return logger