A Simple Log Helper for Python

Just wanted to share this simple log helper method I came up with after some research, which can help you quickly setup Python logging and focus on your main app logic instead of dangling around in logging documentation.

The method is very simple, takes a filename and two other optional arguments, and returns ‘logging’ object, and you can start logging in your Python projects in no time!

Here’s the code:

#file log_helper.py
import os, sys
import logging

def logHelper(fileName, logLevel=logging.INFO, useConsole=True):
    """
    Simple Logging Helper. Retuens logger reference.

    Paramsmeters:
    fileName: Filename, may include full path, or will open a file in default folder
    logLevel: Pass logging.INFO, logging.DEBUG or other enums for logging level
    useConsole: If Ture, will also dump log to console
    """

    ##### init logging
    log = logging.getLogger()
    log.setLevel(logLevel)
    logFormatter = logging.Formatter("%(asctime)s | %(threadName)-12.12s | %(levelname)-5.5s | %(message)s")

    ##### file handler
    fileOut = logging.FileHandler(fileName)
    fileOut.setFormatter(logFormatter)
    log.addHandler(fileOut)

    ##### console handler
    if useConsole:
        consoleOut = logging.StreamHandler(sys.stdout)
        consoleOut.setFormatter(logFormatter)
        log.addHandler(consoleOut)

    ##### return reference
    return log

And usage is simple. Passing just filename defaults to ‘logging.INFO’ log level, and console output turned on:

#import module
import log_helper as log

# get logger
log = log.logHelper('logfile.log')
log.info("Got logger")

Or use optional arguments to set up logging level and console output:

#import module
import log_helper as log

# get logger
log = log.logHelper('logfile.log', logging.WARN, False)
log.warn("this is a warning message")

Additionally, you can always tweak the method as per your needs, for rotating file handler, additional output handlers and log output format.

Check out Python’s documentation for ‘logging’ module here for more info.

Bugs reports? Suggestions? Let me know if you found this useful. Leave a comment 🙂

Cheers,

// Sohail