Calmcode - logging: format

A Python Example on how to set up the format for logging.

1 2 3 4 5 6 7

In this video we've explained how python can customise the logging format.

We've introduced a new file.

Important: do not name this file

import logging

logger = logging.getLogger(__name__)

# the handler determines where the logs go: stdout/file
handler = logging.StreamHandler()

# the formatter determines what our logs will look like
fmt = '%(levelname)s %(asctime)s %(filename)s %(funcName)s %(lineno)d %(message)s'
formatter = logging.Formatter(fmt)


This file contains a logger that we can re-use. We're using it in all of our other files.

import sys

from logger import logger
from summarise import summary

if __name__ == "__main__":
    ticker = sys.argv[1]
    logger.warning(f"Will find summary for {ticker}")
    print(f"The average stock price is {summary(ticker)}")

from fetch import download_data
from logger import logger

def summary(ticker):
    logger.warning("About to download data.")
    dataf = download_data()
    logger.warning("Dataset downloaded.")
    return dataf[ticker].mean()

import pandas as pd
from logger import logger

def download_data():
    url = ''
    logger.warning(f"Fetching from {url}")
    return pd.read_csv(url)