Updated wk.log.update_log_path()

* The log file is now moved instead of copied
* The new path can now be based on a new dir, name, or both
This commit is contained in:
2Shirt 2019-09-18 20:58:06 -07:00
parent 318f59c473
commit f1775766e7
Signed by: 2Shirt
GPG key ID: 152FAC923B0E132C
2 changed files with 30 additions and 22 deletions

View file

@ -59,39 +59,47 @@ def start(config=None):
atexit.register(logging.shutdown) atexit.register(logging.shutdown)
def update_log_path(dest_dir, dest_name=''): def update_log_path(dest_dir=None, dest_name=None):
"""Copies current log file to new dir and updates the root logger. """Moves current log file to new path and updates the root logger.
NOTE: A timestamp and extension will be added to dest_name if provided. NOTE: A timestamp and extension will be added to dest_name if provided.
""" """
root_logger = logging.getLogger() root_logger = logging.getLogger()
cur_handler = root_logger.handlers[0] cur_handler = root_logger.handlers[0]
dest = pathlib.Path(dest_dir) cur_path = pathlib.Path(cur_handler.baseFilename).resolve()
dest = dest.expanduser()
if dest_name:
dest_name = f'{dest_name}_{time.strftime("%Y-%m-%d_%H%M%S%z")}.log'
# Safety checks # Safety checks
if not (dest_dir or dest_name):
raise RuntimeError('Neither a directory nor name specified')
if len(root_logger.handlers) > 1: if len(root_logger.handlers) > 1:
raise RuntimeError('Multiple handlers not supported') raise RuntimeError('Multiple handlers not supported')
if not isinstance(cur_handler, logging.FileHandler): if not isinstance(cur_handler, logging.FileHandler):
raise RuntimeError('Only FileHandlers are supported') raise RuntimeError('Only FileHandlers are supported')
# Copy original log to new location # Update dir if specified or use current path
source = pathlib.Path(cur_handler.baseFilename) if dest_dir:
source = source.resolve() new_path = pathlib.Path(dest_dir).resolve()
if dest_name:
dest = dest.joinpath(dest_name)
else: else:
dest = dest.joinpath(source.name) new_path = cur_path
dest = dest.resolve()
if dest.exists(): # Update name if specified
raise FileExistsError(f'Refusing to clobber: {dest}') if dest_name:
os.makedirs(dest.parent, exist_ok=True) new_path = new_path.with_name(
shutil.copy(source, dest) f'{dest_name}'
f'_{time.strftime("%Y-%m-%d_%H%M%S%z")}'
f'{"".join(cur_path.suffixes)}'
)
else:
new_path = new_path.with_name(cur_path.name)
# Copy original log to new location
if new_path.exists():
raise FileExistsError(f'Refusing to clobber: {new_path}')
os.makedirs(new_path.parent, exist_ok=True)
shutil.move(cur_path, new_path)
# Create new cur_handler (preserving formatter settings) # Create new cur_handler (preserving formatter settings)
new_handler = logging.FileHandler(dest, mode='a') new_handler = logging.FileHandler(new_path, mode='a')
new_handler.setFormatter(cur_handler.formatter) new_handler.setFormatter(cur_handler.formatter)
# Replace current handler # Replace current handler

View file

@ -839,21 +839,21 @@ def print_info(msg, log=True, **kwargs):
"""Prints message in BLUE and log as INFO.""" """Prints message in BLUE and log as INFO."""
print_colored([msg], ['BLUE'], **kwargs) print_colored([msg], ['BLUE'], **kwargs)
if log: if log:
LOG.info(msg, log=True) LOG.info(msg)
def print_standard(msg, log=True, **kwargs): def print_standard(msg, log=True, **kwargs):
"""Prints message and log as INFO.""" """Prints message and log as INFO."""
print(msg, log=True, **kwargs) print(msg, **kwargs)
if log: if log:
LOG.info(msg, log=True) LOG.info(msg)
def print_success(msg, log=True, **kwargs): def print_success(msg, log=True, **kwargs):
"""Prints message in GREEN and log as INFO.""" """Prints message in GREEN and log as INFO."""
print_colored([msg], ['GREEN'], **kwargs) print_colored([msg], ['GREEN'], **kwargs)
if log: if log:
LOG.info(msg, log=True) LOG.info(msg)
def print_warning(msg, log=True, **kwargs): def print_warning(msg, log=True, **kwargs):