Method 1 - With basicCofig() (Logging to a file)
#!/usr/bin/env python3
import logging
def conf_logging(log_sev='WARNING'):
log_format = "[%(name)s]-[%(levelname)s]-%(asctime)s-[%(funcName)s]-%(message)s"
datefmt='[%d/%m/%y]-[%H:%M:%S]'
file='dotfiles.log'
# Define a your logger
logging.basicConfig(format=log_format, datefmt=datefmt, level=log_sev, filename=file)
logger = logging.getLogger(__name__)
logger.warning(f'Test')
conf_logging()
Example output
[__main__]-[INFO]-[07/03/20]-[15:48:59]-[main]-Test
[__main__]-[INFO]-[07/03/20]-[15:49:01]-[test_function]-Test inside the function
Method 2 - More granular (Logging to a file)
#!/usr/bin/env python3
import logging
def conf_logging(log_sev='WARNING'):
log_format = "[%(name)s]-[%(levelname)s]-%(asctime)s-[%(funcName)s]-%(message)s"
datefmt='[%d/%m/%y]-[%H:%M:%S]'
# Define a custom logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
# Create a file handler
file_hand = logging.FileHandler('dotfiles.log')
file_hand.setLevel(logging.INFO)
# Create a loging format
formatter = logging.Formatter(fmt=log_format, datefmt=datefmt)
file_hand.setFormatter(formatter)
# Add the File handler to the logger
logger.addHandler(file_hand)
logger.info(f'Test')
conf_logging()
Example output
[__main__]-[INFO]-[07/03/20]-[15:48:59]-[main]-Test
[__main__]-[INFO]-[07/03/20]-[15:49:01]-[test_function]-Test inside the function