- Don't use Python 2. Unless you're in legacy software hell, such as Jython, just don't do it.
C:\tool_temp is not a good location for log files. Depending on intent, this might be better as C:\ProgramData\my_app\logs for instance.
- Instead of initializing the logger in the global namespace and configuring it after the fact, consider instantiating the logger locally, configuring and then returning it to be set on the global namespace afterwards.
- Your configuration dict mechanism is unnecessary. Read about https://docs.python.org/3.8/library/argparse.html#fromfile-prefix-chars which supports what - in another universe - is called a response file; basically a file with the exact same information that a list of command-line arguments would have.
- You call
basicConfig, but only in the case where you don't want to rotate logs. This means that in the case where you do want to rotate logs, you're failing to set up a StreamHandler. That's probably an error.
%d %b %d is probably an error.
- You're using a non-sortable datetime format, which has grave consequences for some log file handling software. Just use a machine-readable ISO8601-style timestamp instead.
- Consider adding PEP484 type hints.
- Your arguments should follow the Unix convention of having a
--double-dashed long form and a -s single-dashed short form.
import logging
from argparse import ArgumentParser, Namespace
from logging import Formatter, Logger, getLogger, FileHandler, StreamHandler
from logging.handlers import RotatingFileHandler
from pathlib import Path
from pprint import pformat
LOG_FILENAME = 'debug.log'
# Consider /var/log/my_app if in Unix, or something under C:\ProgramData if in Windows
LOG_PATH = Path('.')
def log_setup(dir_name: Path, filename: str, rotation_enabled: bool) -> Logger:
# Avoid printing 628 after 2021-05-25 16:30:30,628
formatter = Formatter(
fmt='%(asctime)s : %(levelname)s: %(filename)s::%(funcName)s:%(lineno)d %(message)s',
datefmt="%Y-%m-%d %H:%M:%S",
)
stream_handler = StreamHandler()
stream_handler.setFormatter(formatter)
if rotation_enabled:
# Add the log message rotate_handler to the logger
file_handler = RotatingFileHandler(dir_name / filename, maxBytes=512, backupCount=5)
else:
file_handler = FileHandler(dir_name / filename)
file_handler.setFormatter(formatter)
logger = getLogger('MYAPP')
logger.addHandler(stream_handler)
logger.addHandler(file_handler)
# by default, the logging module logs the messages with a severity level of WARNING or above.
# so used level=logging.DEBUG to log everything from debug to critical
logger.setLevel(logging.DEBUG)
return logger
def parse_command_line_args() -> Namespace:
parser = ArgumentParser(
description='My Application',
fromfile_prefix_chars='@',
)
parser.add_argument(
'-r', '--log-rotate', type=boolaction='store_true',
default=False, help='logrotation enabled or not' help='enable log rotation',
)
return parser.parse_args()
def test_levels() -> None:
logger.debug('this debug is from our test')
logger.info('this info is from our test')
logger.error('this error is from our test')
if __name__ == "__main__":
config = parse_command_line_args()
logger = log_setup(Path(LOG_PATH), LOG_FILENAME, config.log_rotate)
logger.debug(f'Configuration: {pformat(config.__dict__)}')
test_levels()