Configuring Logger
Any logger from the logging module can be used. A utility function setup_logger is provided for convenience.
- nbiatoolkit.logger.setup_logger(name: str, log_level: str = 'INFO', console_logging: bool = False, log_file: str | None = None, log_dir: str | None = None, log_format: str = '%(asctime)s | %(name)s | %(levelname)s | %(message)s', datefmt: str = '%y-%m-%d %H:%M') Logger [source]
Set up a logger object that can be used to log messages to a file and/or console with daily log file rotation. If passing a log_file, the log file will be created in the current working directory unless a log_dir is provided. The log_file is created with a TimedRotatingFileHandler to rotate the log file daily.
- Parameters:
name (str) – The name of the logger.
log_level (str, optional) – The log level. Defaults to ‘INFO’.
console_logging (bool, optional) – Whether to log to console. Defaults to False.
log_file (str, optional) – The log file name. Defaults to None.
log_dir (str, optional) – The log directory. Defaults to None.
log_format (str, optional) – The log format. Defaults to ‘%(asctime)s | %(name)s | %(levelname)s | %(message)s’.
datefmt (str, optional) – The date format. Defaults to ‘%y-%m-%d %H:%M’.
- Returns:
The logger object.
- Return type:
logger (logging.Logger)
from nbiatoolkit import NBIAClient
from nbiatoolkit import setup_logger
my_logger = setup_logger(
name="my_logger",
log_level="DEBUG",
console_logging=False,
log_file="logfile.log",
log_dir="logs",
log_format="%(asctime)s | %(name)s | %(levelname)s | %(message)s",
datefmt="%y-%m-%d %H:%M",
)
# log some messages
my_logger.info("This is an info message")
# read in the log file
print("Contents of logfile.log:")
with open("logs/logfile.log", "r") as f:
print(f.read())
client_logger = setup_logger(
name="NBIAClient",
log_level="DEBUG",
console_logging=False,
log_file="logfile.log",
log_dir="logs",
log_format="%(asctime)s | %(name)s | %(levelname)s | %(message)s",
datefmt="%y-%m-%d %H:%M",
)
client = NBIAClient(logger=client_logger)
print("Contents of logfile.log after creating NBIAClient:")
with open("logs/logfile.log", "r") as f:
print(f.read())
Contents of logfile.log:
24-04-01 20:06 | my_logger | INFO | This is an info message
Contents of logfile.log after creating NBIAClient:
24-04-01 20:06 | my_logger | INFO | This is an info message
24-04-01 20:06 | NBIAClient | DEBUG | Setting up OAuth2 client... with username nbia_guest