欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

前面程序整合加自定义日志,日志会记录重目前还在找问题

程序员文章站 2022-04-10 20:37:40
前面程序整合加自定义日志 1.文件摆放 2.运行文件 1.run 3.自定义辅助模块 1.用于文件的读取和写入 2.用于子程序返回主界面来个延迟动画效果 3.用于记录时间 用于记录时间 4.记录日志(这部分有点问题) logger.py ......

前面程序整合加自定义日志

1.文件摆放

├── xxxx
│   ├── src.py
│   └── fil_mode.py
│   └── data_time.py
│   └── loading.py
│   └── data_time.py
│   └── logger.py

2.运行文件

1.run

src.py

# 导入需要用到的所有内置模块
import logging
import time
import json
import os
from fil_mode import *
from loading import *
from data_time import *
from logger import *

#全局所需要用到的变量
login_name = [none] #用全局可变的受局部影响
goods_dict = {
    '0':['*',100],
    '1':['《nick写真集》',1],
    '2':['奥特曼玩偶',50],
    '3':['钢铁侠真人套装',10000],
    '4':['《产品经理强哥自传》',188],
    '5':['《马叉虫是如何炼成的》',888],
    '6':['《ywy自传》',8888888888888]
}
user_car = dict()


#功能模块
#注册
def register():
    print('\033[1;34;46m\t\t欢迎使用注册功能\t\t\033[0m')
    register_name_ture = 0
    name_list = fil_info_name_list()
    while register_name_ture==0:
        print('\033[1;34;43m\t\t请您输入注册账号\t\t\033[0m')
        print('\033[1;34;43m\t\t账号由全英文组成\t\t\033[0m')
        print('\033[1;31;m输入q退出程序\t\033[0m')
        register_name = input('请输入:').strip()
        if register_name == 'q':
            loading()
            return false
        elif len(register_name.replace(' ','')) != len(register_name):
            print('\033[1;31;m输入账号中有宫格请重新输入\t\033[0m')
            continue
        elif not register_name.isalpha():
            print('\033[1;31;m输入账号不是由全英文组成请重新输入\t\t\033[0m')
            continue
        elif register_name in fil_info_name_list():
            print('\033[1;31;m输入账号以存在请重新输入\t\t\033[0m')
        else:
            register_name_ture =1
            print('\033[1;34;43m\t\t账号名已注册成功\t\t\033[0m')
            while true:
                print('\033[1;34;43m\t\t请您输入注册密码\t\t\033[0m')
                print('\033[1;34;43m\t\t账号由全数字组成\t\t\033[0m')
                register_pwd = input('请输入:').strip()
                if len(register_pwd.replace(' ', '')) != len(register_pwd):
                    print('\033[1;31;m输入密码中有宫格请重新输入\t\033[0m')
                    continue
                elif not register_pwd.isdigit():
                    print('\033[1;31;m输入密码不是由全数字组成请重新输入\t\t\033[0m')
                    continue
                else:
                    print('\033[1;32;m\t\t注册成功\t\t\033[0m')
                    register_info_dict = {'name':none,'pwd':none,'balance':0,'integral':0,'freeze':0}
                    register_info_dict['name'] = register_name
                    register_info_dict['pwd'] = register_pwd
                    fil_add_info_dict(register_info_dict)
                    print('注册成功')
                    loading()
                    break
    return true

#登入
def login():
    print('\033[1;34;46m\t\t欢迎使用登入功能\t\033[0m')
    name_list = fil_info_name_list()
    login_name_ture = 0
    login_count =0
    if not name_list:
        print('\033[1;31;m没有用户注册请先注册\033[0m')
        loading()

        return false
    global login_name
    if not login_name[0]:
        while login_name_ture == 0:
            print('\033[1;34;43m\t\t请您输入账号\t\t\033[0m')
            print('\033[1;31;m输入q退出程序\t\033[0m')
            login_username = input('请输入:').strip()
            if login_username == 'q':
                loading()
                return false
            elif len(login_username.replace(' ', '')) != len(login_username):
                print('\033[1;31;m输入账号中有宫格请重新输入\t\033[0m')
                continue
            elif not login_username.isalpha():
                print('\033[1;31;m输入账号不为全英文\t\t\033[0m')
                continue
            elif not login_username in fil_info_name_list():
                print('\033[1;31;m输入账号不存在\t\t\033[0m')
                continue
            else:
                login_name_ture = 1
                print('\033[1;34;43m\t\t账号输入正确\t\t\033[0m')
                while login_count < 5:
                    print(f'\033[1;34;43m\t你有{5-login_count}次机会输入密码\t\t\033[0m')
                    print('\033[1;34;43m\t\t请您输入密码\t\t\033[0m')
                    login_pwd = input('请输入:').strip()
                    if len(login_pwd.replace(' ', '')) != len(login_pwd):
                        print('\033[1;31;m输入密码中有宫格请重新输入\t\033[0m')
                        login_count += 1
                        continue
                    elif not login_pwd.isdigit():
                        print('\033[1;31;m输入密码不为全数字\t\t\033[0m')
                        login_count += 1
                        continue
                    else:
                        user_dict = fil_userinfo(login_username)
                        if user_dict['pwd'] != login_pwd:
                            print('\033[1;31;m输入密码错误请重新输入\t\t\033[0m')
                            login_count += 1
                            continue
                        else:
                            if user_dict["freeze"] == 0:
                                print('\033[1;32;m\t\t登入成功\t\t\033[0m')
                                login_name[0] = login_username
                                loading()
                                logger_login(login_username)
                                return true
                            else:
                                print('\033[1;31;m登入失败\t\t\033[0m')
                                print(f'\033[1;31;m账户{login_username}以被冻结\t\t\033[0m')
                                loading()

                                return false
                fil_info_frzzez_amend(login_username,1)
                print('\033[1;31;m\t\t登入失败\t\t\033[0m')
                print(f'\033[1;31;m{login_username}账号密码登入失败太多已被冻结\033[0m')
                loading()

                return false
    while true:
        print(38 * '-')
        print("\033[0;40;46m\t\t欢迎使用登入功能\t\t\t\033[0m")
        print(f'账号{login_name[0]}已经登入')
        chiose = input('输入1当前账号退出并退出登入程序\n'
                       '输入2当前账号退出并重新登入程序\n'
                       '输入q退出当前程序')
        print(38 * '-')
        if chiose == '1':
            logger_exit(login_name[0])
            login_name[0] = none

            return false
        elif chiose == '2':
            logger_exit(login_name[0])
            login_name[0] = none
            login()
            return
        elif chiose == 'q':
            loading()
            return true
        else:
            print('\033[1;31;m请正确输入')

#充值
def top_up():
    print('\033[1;34;46m\t\t欢迎使用充值功能\t\033[0m')
    name_list = fil_info_name_list()
    login_name_ture = 0
    login_count =0
    if not name_list:
        print('\033[1;31;m没有用户注册请先注册\033[0m')
        loading()
        return false
    global login_name
    if not login_name[0]:
        print('\033[1;31;m没有用户登入请先登入\033[0m')
        loading()
        return false
    info_dict = fil_userinfo(login_name[0])
    print(f"\033[1;32;m当前账户{login_name[0]}可用余额为{info_dict['balance']}元\033[0m")
    while true :
        print('\033[1;34;43m\t\t请您输入充值的金额\t\t\033[0m')
        print('\033[1;31;m输入q退出程序\t\033[0m')
        balance = input('请输入:').strip()
        if balance == 'q':
            loading()
            return false
        elif len(balance.replace(' ', '')) != len(balance):
            print('\033[1;31;m输入金额中有宫格请重新输入\t\033[0m')
            continue
        elif not balance.isdigit():
            print('\033[1;31;m输入金额不为全数字\t\t\033[0m')
            continue
        else:
            balance_int = int(balance)
            info_dict['balance'] += balance_int
            fil_info_balance_amend(login_name[0],info_dict['balance'])
            print(f'\033[1;32;m充值成功\033[0m')
            print(f"\033[1;32;m当前账户{login_name[0]}可用余额为{info_dict['balance']}元\033[0m")
            print('\033[1;34;43m\t\t是否继续充值\t\t\033[0m')
            print('\033[1;31;m输入q退出y为继续\t\033[0m')
            while true:
                chiose = input('请输入')
                if chiose not in ['q','y']:
                    print(f'\033[1;32;m请好好输入\033[0m')
                elif chiose == 'q':
                    loading()
                    return false
                else:
                    break

#购物
def shopping():

    a = '0'
    print('\033[1;34;46m\t\t欢迎使用购物功能\t\033[0m')
    name_list = fil_info_name_list()
    login_name_ture = 0
    login_count =0
    if not name_list:
        print('\033[1;31;m没有用户注册请先注册\033[0m')
        loading()
        return false
    global login_name
    if not login_name[0]:
        print('\033[1;31;m没有用户登入请先登入\033[0m')
        loading()
        return false
    user_dict = fil_userinfo(login_name[0])
    balance = user_dict["balance"]
    while a == '0':
        print(38*'-')
        print("\033[0;30;46m\t\t输入0是*100元\t\t\t\t\033[5m")
        print("\033[0;30;46m\t\t输入1是《nick写真集》1元\t\t\t\033[5m")
        print("\033[0;30;46m\t\t输入2是奥特曼玩偶50元 \t\t\t\033[5m")
        print("\033[0;30;46m\t\t输入3是钢铁侠真人套装10000元 \t\033[5m")
        print("\033[0;30;46m\t\t输入4是《产品经理强哥自传》18888元\033[5m")
        print("\033[0;30;46m\t\t输入5是《马叉虫是如何炼成的》888元\033[5m")
        print("\033[0;30;46m\t\t输入6是《ywy自传》8888888888888元\033[5m")
        print("\033[0;31;m输入q退出程序\t\t\t\t\t\033[5m")
        print(38 * '-')
        goods_chiose = input('请输入你要购买的商品')
        if goods_chiose=='q':
            loading()
            return
        elif goods_chiose not in goods_dict:
            print('请好好输入')
            continue
        else:
            a = '2'
        while true:
            goods_nums = input('请输入商品的数量')
            if not goods_nums.isdigit():
                print('请输入数字')
            break
        goods = goods_dict[goods_chiose][0]
        price = goods_dict[goods_chiose][1]*int(goods_nums)

        #生成购物车
        global user_car
        if goods not in user_car:
            user_car[goods] = [goods_nums,price]
        else:
            user_car[goods][0] += goods_nums
            user_car[goods][1] += price
        print('\033[1;32;m-'*50)
        date_time = data_time()
        print(f'您好{login_name[0]}:')
        print(f'当前日期{date_time}\n\n')
        money = 0
        for user_car_info in user_car.items():
            print(f'{user_car_info[0]}{user_car_info[1][0]}个 合计{user_car_info[1][1]}元\n')
            money += int(user_car_info[1][1])
        print(f'\t\t\t\t\t一共{money}元')
        print('-' * 50)
        print('\033[0m',end='')
        judge = 1
        while judge == 1:
            print(50 * '\033[1;32;m-')
            jump = input('\033[0m输入0结算\n'
                         '输入1继续购买\n'
                         '输入2清空购物车继续购买\n'
                         '输入3清空购物车退出\n'
                         '请输入您的选择\n'
                         '\033[0m').strip()
            if jump not in ['0','1','2','3']:
                print('请正确输入0,1,2,3中任意数字')
                continue
            if jump == '1':
                judge = 4  # 跳出功能选择
                a = '0'  # 继续购买
            elif jump == '2':
                user_car = dict()  # 清空购物车
                judge = 4  # 跳出功能选择
                a = '0'  # 继续购买
            elif jump == '3':
                user_car = dict()
                judge = 4  # 跳出功能选择
                print("-" * 50)
                print('\033[1;42;m\t欢迎下次光临\t\033[0m')
            elif jump == '0':
                if  money > balance:
                    print('\033[1;31;m余额不足\033[0m')
                else:
                    judge = 4  # 跳出功能选择
                    print("\033[1;32;m-" * 50)
                    #打印内容
                    date_time = data_time()
                    money = 0
                    print(f'您好{login_name[0]}:')
                    print(f'当前日期{date_time}\n\n')
                    for user_car_info in user_car.items():
                        print(f'{user_car_info[0]}{user_car_info[1][0]}个 合计{user_car_info[1][1]}元\n')
                        money += int(user_car_info[1][1])
                    print(f'\t\t\t\t\t一共{money}元')
                    print("-" * 50)
                    print('\033[0m')
                    balance -= money
                    fil_info_balance_amend(login_name[0],balance)
                    print('\033[1;42;m\t欢迎下次光临\t\033[0m')
                    logger_shopping(login_name[0],user_car)
                    loading()
                    return

#余额查询
def balance_enquiry():
    print('\033[1;34;46m\t\t欢迎使用余额查询功能\t\033[0m')
    name_list = fil_info_name_list()
    login_name_ture = 0
    login_count =0
    if not name_list:
        print('\033[1;31;m没有用户注册请先注册\033[0m')
        loading()
        return false
    global login_name
    if not login_name[0]:
        print('\033[1;31;m没有用户登入请先登入\033[0m')
        loading()
        return false
    info_dict = fil_userinfo(login_name[0])
    print(f"\033[1;32;m当前账户{login_name[0]}可用余额为{info_dict['balance']}元\033[0m")
    print('\033[1;42;m5秒后返回主界面\033[0m',end='')
    loading()
    time.sleep(4)

#解冻
def freeze():
    print('\033[1;34;46m\t\t欢迎使用账号解冻功能\t\033[0m')
    name_list = fil_info_name_list()
    login_name_ture = 0
    login_count = 0
    if not name_list:
        print('\033[1;31;m没有用户注册请先注册\033[0m')
        loading()
        return false
    while true:
        print('\033[1;34;43m\t\t请您输入解冻账号\t\t\033[0m')
        print('\033[1;31;m输入q退出程序\t\033[0m')
        name = input('请输入:').strip()
        if name == 'q':
            loading()
            return false
        elif len(name.replace(' ', '')) != len(name):
            print('\033[1;31;m输入账号中有宫格请重新输入\t\033[0m')
            continue
        elif not name.isalpha():
            print('\033[1;31;m输入账号不为全英文字母\t\t\033[0m')
            continue
        elif name not in name_list:
            print('\033[1;31;m输入账号不存在\t\t\033[0m')
            continue
        else:
            user_dict = fil_userinfo(name)
            user_freeze = user_dict['freeze']
            user_pwd = user_dict['pwd']
            if user_freeze == 0:
                print(f'\033[1;31;m当前账户{name}未被冻结\t\t\033[0m')
                loading()
                return
            else:
                while true:
                    print('-' * 50)
                    a = input('输入:杨大爷请帮我解冻\n请输入:')
                    if a != '杨大爷请帮我解冻':
                        print('\033[1;31;m想解冻就好好输入\033[0m')
                        continue
                    fil_info_frzzez_amend(name, 0)
                    print(f'\033[1;32;m账号{name}解冻成功\033[0m')
                    loading()
                    return

#运行模块
#功能列表
msg_dict ={
    '1':login,
    '0':register,
    '2':top_up,
    '3':balance_enquiry,
    '4':shopping,
    '5':freeze,
    'q':'quit'
}
app_name_dict ={
    '1':'login',
    '0':'register',
    '2':'top_up',
    '3':'balance_enquiry',
    '4':'shopping',
    '5':'freeze'
}
#运行程序
if __name__ == '__main__':
    logger_start('程序主界面')
    while true:
        print("\033[0;31;44m\t\t杨大爷超市欢迎您\t\t\t\t\033[5m")
        print("\033[0;30;42m\t\t输入0进入注册界面\t\t\t\033[5m")
        print("\033[0;30;42m\t\t输入1进入登入界面\t\t\t\033[5m")
        print("\033[0;30;42m\t\t输入2进入充值界面\t\t\t\033[5m")
        print("\033[0;30;42m\t\t输入3进入余额查询界面\t\t\033[5m")
        print("\033[0;30;42m\t\t输入4进入购物界面\t\t\t\033[5m")
        print("\033[0;30;42m\t\t输入5进入解冻界面\t\t\t\033[5m")
        print("\033[0;30;42m\t\t输入q退出程序 \t\t\t\t\033[5m")
        print(38 * '-')
        user_shopping_chiose = input('请输入你要选择的功能')
        if user_shopping_chiose not in msg_dict:
            print('请好好输入')
            continue
        elif user_shopping_chiose=='q':
            print('再见')
            logger_end('程序主界面')
            break
        else:
            logger_start(f'{app_name_dict[user_shopping_chiose]}')
            msg_dict[user_shopping_chiose]()
            logger_end(f'{app_name_dict[user_shopping_chiose]}')

3.自定义辅助模块

1.用于文件的读取和写入

fil_mode.py

import json
import os
def fil_add_info_dict(dict,fil='用户注册信息.txt'):
    info_dict = json.dumps(dict)
    with open(fil,'a',encoding='utf8') as fa :
        fa.write(f'{info_dict}\n')
    return true

def fil_info_name_list(fil='用户注册信息.txt'):
    name_list = list()
    with open(fil,'a+',encoding='utf-8') as fa :
        fa.seek(0)
        data = fa.read()
        if data:
            with open(fil,'r',encoding='utf-8') as fr :
                for info_dict in fr:
                    info_dict = json.loads(info_dict)
                    name_list.append(info_dict.get('name'))
    return name_list

def fil_info_balance_amend(name,balance,fil='用户注册信息.txt'):
    name_list = fil_info_name_list(fil)  #fil_info_name_list为用字典里面的所有名字生成的列表
    if name in name_list:
        with open(fil,'r',encoding='utf8') as fr,\
            open('1.txt','w',encoding='utf8') as fw:
            for info_dict in fr:
                info_dict = json.loads(info_dict)
                if name == info_dict['name']:
                    info_dict['balance'] = balance
                info_dict =json.dumps(info_dict)
                fw.write(f'{info_dict}\n')
                fw.flush()
        os.remove(fil)
        os.rename('1.txt',fil)

def fil_userinfo(name,fil='用户注册信息.txt'):
    with open(fil,'a+',encoding='utf8') as far:
        far.seek(0)
        for a in far:
            a = json.loads(a)
            if a['name'] == name:
                info_dict = a
                return info_dict
        return false

def fil_info_frzzez_amend(name,freeze,fil='用户注册信息.txt'):
    name_list = fil_info_name_list(fil)  #fil_info_name_list为用字典里面的所有名字生成的列表
    if name in name_list:
        with open(fil,'r',encoding='utf8') as fr,\
            open('1.txt','w',encoding='utf8') as fw:
            for info_dict in fr:
                info_dict = json.loads(info_dict)
                if name == info_dict['name']:
                    info_dict["freeze"] = freeze
                info_dict =json.dumps(info_dict)
                fw.write(f'{info_dict}\n')
                fw.flush()
        os.remove(fil)
        os.rename('1.txt',fil)

2.用于子程序返回主界面来个延迟动画效果

loading.py

import time
def  loading():
    txt = '返回主界面中loading'
    print(f'\033[1;42;m{txt}\033[0m',end='')
    for a in range(10):
        print(f'\033[1;42;m.\033[0m',end='')
        time.sleep(0.1)
    print('')
    return true

3.用于记录时间

data_time.py用于记录时间

import time
def data_time():
    return time.strftime("%y-%m-%d %h:%m:%s", time.localtime())

4.记录日志(这部分有点问题)

logger.py

import logging
def logger_login(user):
    logger_login = logging.getlogger('user_login')
    fli_show = logging.filehandler('user_login.log')
    logger_format = logging.formatter('登入时间:%(asctime)s  %(levelname)s-用户:%(message)s',
                     datefmt='%y-%m-%d %x' )
    fli_show.setformatter(logger_format)
    logger_login.addhandler(fli_show)
    logger_login.setlevel(10)
    logger_login.info(user)


def logger_exit(user):
    logger_login = logging.getlogger('user_login')
    fli_show = logging.filehandler('user_login.log')
    logger_format = logging.formatter('退出时间:%(asctime)s  %(levelname)s-用户:%(message)s',
                     datefmt='%y-%m-%d %x' )
    fli_show.setformatter(logger_format)
    logger_login.addhandler(fli_show)
    logger_login.setlevel(10)
    logger_login.info(user)

def logger_start(app):
    logger_login = logging.getlogger('start')
    fli_show = logging.filehandler('app.log')
    logger_format = logging.formatter('%(message)s程序启动时间:%(asctime)s',
                     datefmt='%y-%m-%d %x' )
    fli_show.setformatter(logger_format)
    logger_login.addhandler(fli_show)
    logger_login.setlevel(10)
    logger_login.info(app)

def logger_end(app):
    logger_login = logging.getlogger('end')
    fli_show = logging.filehandler('app.log')
    logger_format = logging.formatter('%(message)s程序关闭时间:%(asctime)s',
                     datefmt='%y-%m-%d %x' )
    fli_show.setformatter(logger_format)
    logger_login.addhandler(fli_show)
    logger_login.setlevel(10)
    logger_login.info(app)

def logger_shopping(user,car):
    logger_login = logging.getlogger(user)
    fli_show = logging.filehandler('user_shopping.log')
    logger_format = logging.formatter('%(asctime)s  %(levelname)s-%(name)s:%(message)s',
                     datefmt='%y-%m-%d %x' )
    fli_show.setformatter(logger_format)
    logger_login.addhandler(fli_show)
    logger_login.setlevel(10)
    logger_login.info(car)