我正在从https://www.youtube.com/watch?v=jxmzY9soFXg运行日志记录教程。我已经复制并粘贴了代码,但我不了解日志记录。据我了解,我为每个模块本身创建了两个日志文件,但是当我运行任何模块时,我都会在一个日志文件上获得两个文件的输出。我不明白,也将不胜感激。是否不可能为每个创建一个,而不是一前一后地运行。我看到的唯一变化是哪个模块运行了代码,例如main与模块名称。
在本教程的重点是创建单独的日志文件以便于调试时,为什么以某种方式连接日志文件?
员工类的代码为
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(levelname)s:%(name)s:%(message)s')
file_handler = logging.FileHandler('employee.log')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
class Employee:
"""A sample Employee class"""
def __init__(self, first, last):
self.first = first
self.last = last
logger.info('Created Employee: {} - {}'.format(self.fullname, self.email))
@property
def email(self):
return '{}.{}@email.com'.format(self.first, self.last)
@property
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('John', 'Smith')
emp_2 = Employee('Corey', 'Schafer')
emp_3 = Employee('Jane', 'Doe')
and the code for the main program is:
import logging
import employee
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s:%(name)s:%(message)s')
file_handler = logging.FileHandler('sample.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
def add(x, y):
"""Add Function"""
return x + y
def subtract(x, y):
"""Subtract Function"""
return x - y
def multiply(x, y):
"""Multiply Function"""
return x * y
#def divide(x, y):
# """Divide Function"""
# try:
# result = x / y
# except ZeroDivisionError:
# logger.exception('Tried to divide by zero')
# else:
# return result
num_1 = 10
num_2 = 0
add_result = add(num_1, num_2)
logger.info('Add: {} + {} = {}'.format(num_1, num_2, add_result))
sub_result = subtract(num_1, num_2)
logger.info('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))
mul_result = multiply(num_1, num_2)
logger.info('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))
#div_result = divide(num_1, num_2)
#logger.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))