logging打印日志,文件名为log_config.py
import logging
import sys
def setup_logger(log_file, error_log_file):
# 创建一个日志记录器
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG) # 设置全局日志级别为 DEBUG
# 创建一个文件处理器,将日志写入文件
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logging.DEBUG) # 设置文件日志级别为 DEBUG
# 创建一个错误文件处理器,将错误日志单独写入文件
error_file_handler = logging.FileHandler(error_log_file)
error_file_handler.setLevel(logging.ERROR) # 设置错误文件日志级别为 ERROR
# 创建一个控制台处理器,将日志输出到控制台
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setLevel(logging.DEBUG) # 设置控制台日志级别为 DEBUG
# 创建一个日志格式化对象
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
# 将格式化应用到处理器
file_handler.setFormatter(formatter)
error_file_handler.setFormatter(formatter)
console_handler.setFormatter(formatter)
# 将处理器添加到日志记录器
logger.addHandler(file_handler)
logger.addHandler(error_file_handler) # 将错误文件处理器添加到日志记录器
logger.addHandler(console_handler)
return logger
if __name__ == '__main__':
logger = setup_logger('mail.log', 'error_mail.log')
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.DEBUGing('This is a DEBUGing message')
logger.error('This is an error message')
logger.critical('This is a critical message')
邮件发送,导入log_config.py配置
import smtplib
import socket
import log_config #导入log_config.py
import logging
from email.mime.text import MIMEText
from email.header import Header
#logger = log_config.setup_logger('mail.log','error_mail.log')
def send_mail():
from_address = '18847097110@163.com'
to_address = '963268595@qq.com'
subject = 'test email'
body = 'hahahhahaha'
smtp_server = 'smtp.163.com'
smtp_port = 25
username = '18847097110@163.com'
password = 'your password'
msg = MIMEText(body, 'plain', 'utf-8')
msg['From'] = from_address
msg['To'] = to_address
msg['Subject'] = Header(subject, 'utf-8')
logger = log_config.setup_logger('mail.log','error_mail.log') #引用log_confog.py里的setup_logger
server = None
try:
sock = socket.create_connection((smtp_server, smtp_port), timeout=5)
sock.close()
server = smtplib.SMTP(smtp_server, smtp_port)
server.login(username, password)
server.sendmail(from_address, to_address, msg.as_string())
logger.info('Email sent successfully!')
except socket.error as e:
logger.error(f'Socket error occurred: {e}',exc_info=True)
except smtplib.SMTPException as e:
logger.error(f'SMTP error occurred: {e}')
except Exception as e:
logger.error(f'An error occurred: {e}')
finally:
if server is not None:
server.quit()
if __name__ == '__main__':
send_mail()
生成了一个mail.log和error_mai.log