Logging - python

Prebuilt module

from logger_slg import init_logger

logger = init_logger(
    name=__name__,
    log_path=f'/var/log/slg/{__file__.split("/")[-1]}.log'
)
        

Standard Format

formatter = logging.Formatter('%(asctime)s | %(levelname)-8s |  %(pathname)s:%(lineno)d  | %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
        

Basic logging template

import time
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s | %(levelname)-8s |  %(pathname)s:%(lineno)d  | %(message)s', datefmt='%Y-%m-%d %H:%M:%S')

# add for UTC/GMT time
formatter.converter = time.gmtime

# Remember to always use absolute path when using cron. I think the relative path is relative to where the script is called from.
file_handler = RotatingFileHandler('logs/example.log', maxBytes=10000000, backupCount=10)
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)

stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)

logger.addHandler(file_handler)
logger.addHandler(stream_handler)
        

Add exception to logger output

try:
    print(undefined_var)
except:
    logger.exception('Your exception here')
        

Meaning of logging "levels"

# Example
logger.setLevel(logging.DEBUG)

The "level" simply determines what level message will be actually logged.
Anything equally or more serious than the level will be logged.

So if you wanted to log only ERROR and CRITICAL messages then you would set the
log level to logging.ERROR
        

Use traceback to print the traceback

import traceback

try:
    do_stuff()
except:
    print(traceback.format_exc())
    # You can now do other stuff down here like send text message etc.

    print('Example stuffs')