Source code for pysolver_view.reporting.logging

import os
import logging
from datetime import datetime


[docs] def create_logger(name, path=None, use_datetime=True, to_console=False): """ Creates and configures a logging object for recording logs during program execution. Parameters ---------- name : str Name of the log file. Allows for differentiation when analyzing logs from different components or runs of a program. path : str, optional Specifies the directory where the log files will be saved. By default, a directory named "logs" will be created in the current working directory (cwd). use_datetime : bool, optional Determines whether the log filename should have a unique datetime identifier appended. Default is True. to_console : bool, optional Whether to print log messages to the console. Default is True. Returns ------- logger : object Configured logger object. Notes ----- - By default, the function sets the log level to `INFO`, which means the logger will handle messages of level `INFO` and above (like `ERROR`, `WARNING`, etc.). The log entries will contain the timestamp, log level, and the actual log message. - When `use_datetime=True`, each log file will have a unique datetime identifier. This ensures traceability, avoids overwriting previous logs, allows chronological ordering of log files, and handles concurrency in multi-instance environments. """ # Define logs directory if it is not provided if path is None: path = os.path.join(os.getcwd(), "logs") # Create logs directory if it does not exist if not os.path.exists(path): os.makedirs(path) # Define file name and path if use_datetime: current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") log_filename = os.path.join(path, f"{name}_{current_time}.log") else: log_filename = os.path.join(path, f"{name}.log") # Set logger configuration logging.basicConfig( filename=log_filename, level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", ) # Create logger object logger = logging.getLogger() # Console handler (optional) if to_console: console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter("%(message)s")) logger.addHandler(console_handler) return logger