Calmcode - logging: files

Logging to a file in Python.

1 2 3 4 5 6 7

This time we've made a big change to our file. We're not just streaming the output to stdout, we're also applying a filehandler.

import logging

logger = logging.getLogger(__name__)

# the handler determines where the logs go: stdout/file
shell_handler = logging.StreamHandler()
file_handler = logging.FileHandler("debug.log")


# the formatter determines what our logs will look like
fmt_shell = '%(levelname)s %(asctime)s %(message)s'
fmt_file = '%(levelname)s %(asctime)s [%(filename)s:%(funcName)s:%(lineno)d] %(message)s'

shell_formatter = logging.Formatter(fmt_shell)
file_formatter = logging.Formatter(fmt_file)

# here we hook everything together


We've also added more logging statements to the other files.

import sys

from logger import logger
from summarise import summary

if __name__ == "__main__":
    logger.debug("Program started.")
        ticker = sys.argv[1]"Will find summary for {ticker}.")
        print(f"The average stock price is {summary(ticker)}")
        logger.debug("Program ended with success.")
    except BaseException:
        logger.error("Error happened!", exc_info=True)

from fetch import download_data
from logger import logger

def summary(ticker):"About to download data.")
    dataf = download_data()
    logger.debug(f"Dataset downloaded. shape={dataf.shape}")
    logger.debug(f"Dataset downloaded. columns={dataf.columns}")
    return dataf[ticker].mean()

import pandas as pd

from logger import logger

def download_data():
    url = ''
    logger.debug(f"Fetching from {url}.")
    df = pd.read_csv(url)"File downloaded from {url}.")
    return df