Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
logging in simple program
#1
Hello everyone. Below I am sharing the code of a simple working calculator. Program works well but i need to obtain this:
Enter action, select number 1 Addition, 2 Substraction , 3 Multiplication, 4 Division: 1
Enter number 1. 2.3
Enter number 2. 5.4
I add 2.30 and 5.40
Result is 7.70
This is my code:
import operator
from functools import reduce
import logging
logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('Time')
print()
print()

# Add
def add(numbers):
    return reduce(operator.add, numbers)


# Sub


def subtract(numbers):
    return reduce(operator.sub, numbers)


# Multiply


def multiply(numbers):
    return reduce(operator.mul, numbers)


# Divide


def divide(numbers):
    return reduce(operator.truediv, numbers)


def get_data():
    choice = input("Choose operation(1/2/3/4): ")
    args = []
    if choice in "1234":
        while True:
            num = input("Choose another number or click q to quit: ")
            if num == 'q':
                break
            args.append(float(num))
    return args, choice


print("Enter operation, select number:")
print("1.Add")
print("2.Sub")
print("3.Multiply")
print("4.Divide")

operations = {
    '1': add,
    '2': subtract,
    '3': multiply,
    '4': divide,
}

numbers, choice = get_data()
result = operations[choice](numbers)
print(result)
Can someone help me and tell me where and how to put logging in so that it displays what I wrote at the beginning?
Reply
#2
As a advice should use Loguru for easier logging in Python.

You put in logger.info and logger.debug on what you want to logg.
As you just print a lot to screen,could redirect sys.stdout but not showing that now.
Also added logger.exception as your code break if eg put in character instead of and integer.
import operator
from functools import reduce
import my_log

def add(numbers):
    return reduce(operator.add, numbers)

def subtract(numbers):
    return reduce(operator.sub, numbers)

def multiply(numbers):
    return reduce(operator.mul, numbers)

def divide(numbers):
    return reduce(operator.truediv, numbers)

def get_data():
    try:

        choice = input("Choose operation(1/2/3/4): ")
        args = []
        if choice in "1234":
            while True:
                num = input("Choose another number or click q to quit: ")
                if num == 'q':
                    break
                args.append(float(num))
        return args, choice
    except Exception as error:
        my_log.logger.exception(error)

print("Enter operation, select number:")
my_log.logger.info('Enter operation, select number:')
print("1.Add")
my_log.logger.info('1.Add')
print("2.Sub")
print("3.Multiply")
print("4.Divide")

operations = {
    '1': add,
    '2': subtract,
    '3': multiply,
    '4': divide,
}

numbers, choice = get_data()
result = operations[choice](numbers)
my_log.logger.debug(numbers)
my_log.logger.debug(choice)
my_log.logger.debug(result)
print(result)
In logg.log
Output:
2020-12-18 15:29:26,813 - my_log - INFO - Enter operation, select number: 2020-12-18 15:29:26,813 - my_log - INFO - 1.Add 2020-12-18 15:29:41,103 - my_log - DEBUG - [4.0, 9.0] 2020-12-18 15:29:41,103 - my_log - DEBUG - 1 2020-12-18 15:29:41,103 - my_log - DEBUG - 13.0
The boilerplate code i import in my_log
If use Loguru this is not needed.
# my_log.py
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# create a file handler
handler = logging.FileHandler('logg.log')
handler.setLevel(logging.DEBUG)

# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)

# add the handlers to the logger
logger.addHandler(handler)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Suggestions for a simple data analysis program t4keheart 0 1,761 Mar-08-2021, 03:45 PM
Last Post: t4keheart
  Newbie needs help with a simple program feynarun 3 2,215 Jan-15-2020, 01:17 PM
Last Post: DeaD_EyE
  Python Program to Make a Simple Calculator jack_sparrow007 2 10,102 Oct-19-2018, 08:32 AM
Last Post: volcano63
  help with simple program juanb007 2 2,705 Dec-07-2017, 02:15 PM
Last Post: j.crater
  a 'simple' program, hard as .... to understand meems 3 5,098 Dec-04-2016, 10:59 PM
Last Post: meems

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020