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

Posted pythonywy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了前面程序整合加自定义日志,日志会记录重目前还在找问题相关的知识,希望对你有一定的参考价值。

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

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;mlogin_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;mtxt\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)

以上是关于前面程序整合加自定义日志,日志会记录重目前还在找问题的主要内容,如果未能解决你的问题,请参考以下文章

TOMCAT的catalina.out日志没有内容输出

Python 记录器 - 将 STDOUT 重定向到日志文件以及任何调试消息

ORACLE配置重做日志文件

Oracle学习笔记—归档模式

Centos 6.4 /var/log/secure 日志不记录问题

oracle数据库归档详解