-
Notifications
You must be signed in to change notification settings - Fork 7
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
Redesign the logger module to unify structure and remove repeated messages #281
Open
TonyB9000
wants to merge
3
commits into
master
Choose a base branch
from
redesign_logger_274
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+344
−285
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,68 +1,70 @@ | ||
from __future__ import annotations | ||
|
||
import logging | ||
import os | ||
import time | ||
from datetime import datetime | ||
|
||
from pytz import UTC | ||
from datetime import datetime, timezone | ||
|
||
DEFAULT_LOG_LEVEL = logging.INFO | ||
DEFAULT_LOG_DIR = "e2c_logs" | ||
DEFAULT_LOGPATH = f"{DEFAULT_LOG_DIR}/e2c_root_log-{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S_%f')}.log" | ||
|
||
def _setup_root_logger() -> str: # pragma: no cover | ||
"""Sets up the root logger. | ||
# Logger message and date formats. | ||
MSGFMT = "%(asctime)s_%(msecs)03d:%(levelname)s:%(name)s:%(funcName)s:%(message)s" | ||
DATEFMT = "%Y%m%d_%H%M%S" | ||
|
||
The logger module will write to a log file and stream the console | ||
simultaneously. | ||
|
||
The log files are saved in a `/logs` directory relative to where | ||
`e3sm_to_cmip` is executed. | ||
def _logger( | ||
name: str | None = None, | ||
log_filename: str = DEFAULT_LOGPATH, | ||
log_level: int = DEFAULT_LOG_LEVEL, | ||
to_console: bool = False, | ||
to_logfile: bool = False, | ||
propagate: bool = False, | ||
): | ||
"""Return a root or named logger with variable configuration. | ||
|
||
Returns | ||
------- | ||
str | ||
The name of the logfile. | ||
Parameters | ||
---------- | ||
name : str | None | ||
The name displayed for the logger in messages. | ||
If name == None or name == "__main__", the root logger is returned | ||
log_filename : str | ||
If logfile handling is requested, any logfile may be specified. | ||
log_level : LogLevel | ||
Either logging.DEBUG (10), logging.INFO (20), logging.WARNING (30), | ||
logging.ERROR (40), logging.CRITICAL (50), by default logging.INFO. | ||
to_console : boolean | ||
If True, a logging.StreamHandler is supplied, by default False. | ||
to_logfile : boolean | ||
If True, a logging.FileHandler is supplied, by default False. | ||
propagate : boolean | ||
If True, messages logged are propagated to the root logger, by default | ||
False. | ||
""" | ||
os.makedirs("logs", exist_ok=True) | ||
filename = f'logs/{UTC.localize(datetime.utcnow()).strftime("%Y%m%d_%H%M%S_%f")}' | ||
log_format = "%(asctime)s_%(msecs)03d:%(levelname)s:%(funcName)s:%(message)s" | ||
|
||
# Setup the logging module. | ||
logging.basicConfig( | ||
filename=filename, | ||
format=log_format, | ||
datefmt="%Y%m%d_%H%M%S", | ||
level=logging.DEBUG, | ||
) | ||
logging.captureWarnings(True) | ||
logging.Formatter.converter = time.gmtime | ||
|
||
# Configure and add a console stream handler. | ||
console_handler = logging.StreamHandler() | ||
console_handler.setLevel(logging.INFO) | ||
log_formatter = logging.Formatter(log_format) | ||
console_handler.setFormatter(log_formatter) | ||
logging.getLogger().addHandler(console_handler) | ||
if to_logfile: | ||
dn = os.path.dirname(log_filename) | ||
if len(dn) and not os.path.exists(dn): | ||
os.makedirs(dn) | ||
|
||
return filename | ||
if name is None or name == "__main__": | ||
# FIXME: F821 Undefined name `logger` | ||
logger = logger.root # noqa: F821 | ||
else: | ||
logger = logging.getLogger(name) | ||
|
||
logger.propagate = propagate | ||
logger.setLevel(log_level) | ||
|
||
def _setup_logger(name, propagate=True) -> logging.Logger: | ||
"""Sets up a logger object. | ||
|
||
This function is intended to be used at the top-level of a module. | ||
logger.handlers = [] | ||
|
||
Parameters | ||
---------- | ||
name : str | ||
Name of the file where this function is called. | ||
propagate : bool, optional | ||
Propogate this logger module's messages to the root logger or not, by | ||
default True. | ||
if to_console: | ||
logStreamHandler = logging.StreamHandler() | ||
logStreamHandler.setFormatter(logging.Formatter(MSGFMT, datefmt=DATEFMT)) | ||
logger.addHandler(logStreamHandler) | ||
|
||
Returns | ||
------- | ||
logging.Logger | ||
The logger. | ||
""" | ||
logger = logging.getLogger(name) | ||
logger.propagate = propagate | ||
if to_logfile: | ||
logFileHandler = logging.FileHandler(log_filename) | ||
logFileHandler.setFormatter(logging.Formatter(MSGFMT, datefmt=DATEFMT)) | ||
logger.addHandler(logFileHandler) | ||
|
||
return logger |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of instantiating
global logger
, we should have a conditional that checks if--help
/--version
is called and not create the default logfile directory.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@tomvothecoder Right. Originally, the "setup_logger" functions were global to modules like mpas.py, and would get executed by main: import mpas.py, LONG before arg-parsing happens. So, the log-directory gets created before arg-parsing occurs.