Python logging Two Different Files with logging














































Python logging Two Different Files with logging



Python logging 
Two Different Files with logging

Description: In this small project we are going to use logging in two different python file to log admission of student and teacher. We are using console or terminal for input and output. For executing this project just give command "python main.py" on console.

Code:(main.py)
import logging
from student import Student
from teacher import Teacher

def create(choice):

    def create_student():
        print("-----------------------------------------------")
        f_name = input("Enter First Name: ")
        l_name = input("Enter Last Name: ")
        roll_no = int(input("Enter Roll No: "))
        st1 = Student(f_name, l_name, roll_no)
        return None

    def create_teacher():
        print("-----------------------------------------------")
        f_name = input("Enter First Name: ")
        l_name = input("Enter Last Name: ")
        pay = int(input("Enter Pay Amount: "))
        st1 = Teacher(f_name, l_name, pay)
        return None

    choice_dict = {
        1: create_student,
        2: create_teacher
    }

    if choice not in choice_dict:
        raise RuntimeError("{} choice does not exist".format(choice))
    else:
        choice_dict[choice]()

    return None


while True:
    print("-----------------------------------------------")
    print("1. Press 1 for Create Student")
    print("2. Press 2 for Create Teacher")
    print("3. Press . for Exit")
    print("-----------------------------------------------")
    print()

    choice = input("Enter Your Choice: ")
    if choice == ".":
        print("Thank You")
        break
    else:
        try:
            choice = int(choice)
            create(choice)
        except Exception as msg:
            print(msg)
Code:(student.py)
import logging

logger = logging.getLogger(__name__)

formatter = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
                              datefmt="%a, %d %b %Y %H:%M:%S")

file_handler = logging.FileHandler("student.log")
file_handler.setFormatter(formatter)

logger.setLevel(logging.INFO)
logger.addHandler(file_handler)

class Student:

    def __init__(self, firstName, lastName, roll_no):
        self.firstName = firstName
        self.lastName = lastName
        self.roll_no = roll_no

        logger.info(f"Created Student: {self.firstName} {self.lastName} - {self.email}")

    @property
    def email(self):
        return "{}.{}@Company.com".format(self.firstName, self.lastName)

    def __str__(self):
        return "{} {}".format(self.firstName, self.lastName)

Code:(teacher.py)
import logging

logger = logging.getLogger(__name__)

formatter = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
                              datefmt="%a, %d %b %Y %H:%M:%S")

file_handler = logging.FileHandler("teacher.log")
file_handler.setFormatter(formatter)

logger.setLevel(logging.INFO)
logger.addHandler(file_handler)

class Teacher:

    def __init__(self, firstName, lastName, pay):
        self.firstName = firstName
        self.lastName = lastName
        self.pay = pay

        logger.info(f"Created Teacher: {self.firstName} {self.lastName} - {self.email}")

    @property
    def email(self):
        return "{}.{}@Company.com".format(self.firstName, self.lastName)

    def __str__(self):
        return "{} {}".format(self.firstName, self.lastName)

Output:(Console)

Output:(Log File)
Sun, 11 Oct 2020 20:18:26 - student - INFO - Created Student: Robert Edison - Robert.Edison@Company.com


Explanation: When user press option 1 for create student, after entering student's first name, last name and roll number it will be logged in student.log file.


Output:(Console)

Output:(Log File)
Sun, 11 Oct 2020 20:20:27 - teacher - INFO - Created Teacher: Client Holland - Client.Holland@Company.com


Explanation:When user press option 2 for create teacher, after entering teacher's first name, last name and payable amount it will be logged in teacher.log file. 


If user wants to close the program then just press "." and program will terminate.


This is a very basic and simple project of logging new admission of teacher and student. It will help to understand how logging should be used in day to day life or simple short software application.



Comments