Skip to content

Instantly share code, notes, and snippets.

@danielmacuare
Last active March 7, 2020 18:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielmacuare/72aa980034a2f954f42a1c0737277110 to your computer and use it in GitHub Desktop.
Save danielmacuare/72aa980034a2f954f42a1c0737277110 to your computer and use it in GitHub Desktop.
Python Logging Boilerplate

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment