Skip to content

Use Python's logging instead of print function? #15

@astropenguin

Description

@astropenguin

I would like to propose to use the Python's logging feature instead of the print function for logging. This would be nice for users to control levels and destination of the PRIISM log messages. The following changes are what we need to implement the feature.

  1. Add a module logger to each PRIISM submodule:
     import logging
    
     logger = logging.getLogger(__name__)
  2. Replace each print function with a logger method of an appropriate level:
    + logger.info("information")
    - print("information")
    
    + logger.debug("for debug")
    - print("for debug")

Then users can customize logging by adding basicConfig at the top of a Python file. For example:

import logging

logging.basicConfig(
    filename="priism.log",
    format="%(asctime)s %(message)s",
    level="INFO",
)

It would also be nice to use the CASA logger. For example, the following code can create a custom log handler that posts a log message to the CASA logger:

Click to show the code
import logging
from casatasks import casalog


CASALOG_LEVELS = {
    logging.DEBUG: "DEBUGGING",
    logging.INFO: "INFO",
    logging.WARNING: "WARN",
    logging.ERROR: "SEVERE",
    logging.CRITICAL: "SEVERE",
}


class CasalogHandler(logging.Handler):
    def __init__(self, level: int = logging.DEBUG) -> None:
        super().__init__(level)

    def emit(self, record: logging.LogRecord) -> None:
        casalog.post(
            message=self.format(record),
            priority=CASALOG_LEVELS[record.levelno],
        )

Then users can alter the destination of log messages. For example:

logging.basicConfig(
    handlers=(CasalogHandler()),
    format="%(asctime)s %(message)s",
    level="INFO",
)

Because the updates change many lines of the codes, I'm not going to argue that it should be implemented right away... it is just a personal proposal.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions