loging模块

1 1,Alex Li,22,13651054608,IT,2013-04-01
2 2,Jack Wang,30,13304320533,HR,2015-05-03
3 3,Rain Liu,25,1383235322,Saies,2016-04-22
4 4,Mack Cao,40,1356145343,HR,2009-03-01
xinxi.txt
 1 # _*_ coding:utf-8 _*_
 2 staff_table = []
 3 def file_to_date(file_path):
 4     global staff_table
 5     staff_table=[{'staff_id':int(line.strip().split(',')[0]),'name':line.strip().split(',')[1],'age':line.strip().split(',')[2],'phone':line.strip().split(',')[3],'dept':line.strip().split(',')[4],'enroll_date':line.strip().split(',')[5]} for line in open(file_path,encoding='utf-8')]
 6 def output(line,cmd):
 7     for key in line:
 8         if key in cmd[0].split(',') or cmd[0] == '*':
 9             print(line[key], end=' ')
10     print()
11 def select():   #查询功能
12     '''
13     select name,age from staff_table where age > 22
14     select * from staff_table where dept = "IT"
15     select * from staff_table where enroll_date like "2013"
16     显示查询的条数
17     '''
18     while True:
19         n=0
20         file_to_date('xinxi.txt')
21         cmd=input('please input cmd:').strip().lower().split()
22         cmd=[cmd[1], cmd[5:]]
23         if '\''in cmd[1][2]:cmd[1][2]=cmd[1][2].strip('\'')
24         elif '\"'in cmd[1][2]:cmd[1][2]=cmd[1][2].strip('\"')
25         for line in staff_table:
26             if cmd[1][1] == '>'and int(line[cmd[1][0]]) > int(cmd[1][2]):
27                 output(line, cmd)
28                 n += 1
29             elif cmd[1][1] == '='and (line[cmd[1][0]] in [cmd[1][2] ,cmd[1][2].strip('\''),cmd[1][2].strip('\"'),cmd[1][2].lower()] or (cmd[1][2].isdigit() and line[cmd[1][0]] == int(cmd[1][2]))):
30                 output(line,cmd)
31                 n += 1
32             elif cmd[1][1] == 'like' and cmd[1][2] in line[cmd[1][0]].split('-') or cmd[1][2] in line[cmd[1][0]] or cmd[1][2] in line[cmd[1][0]].lower():
33                 output(line,cmd)
34                 n += 1
35         print('相关查询共%d条' % n)
36 select()
查询功能
 1 # _*_ coding:utf-8 _*_
 2 staff_table = []
 3 def file_to_date(file_path):
 4     global staff_table
 5     staff_table=[{'staff_id':int(line.strip().split(',')[0]),'name':line.strip().split(',')[1],'age':line.strip().split(',')[2],'phone':line.strip().split(',')[3],'dept':line.strip().split(',')[4],'enroll_date':line.strip().split(',')[5]} for line in open(file_path,encoding='utf-8')]
 6 def date_to_file(file_path):
 7     global staff_table
 8     with open(file_path,'w',encoding='utf-8') as f:
 9         for line in staff_table:
10             res='%d,%s,%s,%s,%s,%s\n'%(line['staff_id'],line['name'],line['age'],line['phone'],line['dept'],line['enroll_date'])
11             f.write(res)
12 def output(line,cmd):
13     for key in line:
14         if key in cmd[0].split(',') or cmd[0] == '*':
15             print(line[key], end=' ')
16     print()
17 def select():   #查询功能
18     '''
19     select name,age from staff_table where age > 22
20     select * from staff_table where dept = "IT"
21     select * from staff_table where enroll_date like "2013"
22     显示查询的条数
23     '''
24     while True:
25         n=0
26         file_to_date('xinxi.txt')
27         cmd=input('please input cmd:').strip().lower().split()
28         cmd=[cmd[1], cmd[5:]]
29         if '\''in cmd[1][2]:cmd[1][2]=cmd[1][2].strip('\'')
30         elif '\"'in cmd[1][2]:cmd[1][2]=cmd[1][2].strip('\"')
31         for line in staff_table:
32             if cmd[1][1] == '>'and int(line[cmd[1][0]]) > int(cmd[1][2]):
33                 output(line, cmd)
34                 n += 1
35             elif cmd[1][1] == '='and (line[cmd[1][0]] in [cmd[1][2] ,cmd[1][2].strip('\''),cmd[1][2].strip('\"'),cmd[1][2].lower()] or (cmd[1][2].isdigit() and line[cmd[1][0]] == int(cmd[1][2]))):
36                 output(line,cmd)
37                 n += 1
38             elif cmd[1][1] == 'like' and cmd[1][2] in line[cmd[1][0]].split('-') or cmd[1][2] in line[cmd[1][0]] or cmd[1][2] in line[cmd[1][0]].lower():
39                 output(line,cmd)
40                 n += 1
41         print('相关查询共%d条' % n)
42 def create():   #创建
43     global staff_table
44     phone=[]
45     file_to_date('xinxi.txt')
46     while True:
47         info=input('Please enter your name,age,phone number,dept and enroll_date\n(use \',\' to separate):').strip().split(',')
48         info={'staff_id':len(staff_table)+1,'name':info[0].strip(),'age':info[1].strip(),'phone':info[2].strip(),'dept':info[3].strip(),'enroll_date':info[4].strip()}
49         for line in staff_table:
50             phone.append(line['phone'])
51         if info['phone'] in phone:
52             print('The phone number already exists')
53             continue
54         if len(info['phone'])!=11 or not info['phone'].isdigit() or not info['phone'].startswith('1'):
55             print('Incorrect phone number format')
56             continue
57         staff_table.append(info)
58         date_to_file('a.txt')
59 create()
新增用户
  1 # _*_ coding:utf-8 _*_
  2 import time  #自动获取日期
  3 staff_table = []
  4 file_path=r'E:\PycharmProjects\qz5\day9\a.txt'
  5 def table_format():     #格式化输出
  6     global staff_table
  7     for line in staff_table:
  8         res = '%d,%s,%s,%s,%s,%s\n' % (line['staff_id'], line['name'], line['age'], line['phone'], line['dept'], line['enroll_date'])
  9         yield res
 10 def print_table(file_path):      #打印表格
 11     file_to_date(file_path)
 12     for i in table_format():
 13         print(i,end='')
 14 def file_to_date(file_path):        #读取文件
 15     global staff_table
 16     staff_table=[{'staff_id':int(line.strip().split(',')[0]),'name':line.strip().split(',')[1],'age':line.strip().split(',')[2],'phone':line.strip().split(',')[3],'dept':line.strip().split(',')[4],'enroll_date':line.strip().split(',')[5]} for line in open(file_path,encoding='utf-8')]
 17 def date_to_file(file_path):        #写入文件
 18     with open(file_path,'w',encoding='utf-8') as f:
 19         for i in table_format():
 20             f.write(i)
 21 def output(line,cmd):       #筛选输出
 22     for key in line:
 23         if key in cmd[0].split(',') or cmd[0] == '*':
 24             print(line[key], end=' ')
 25     print()
 26 def select():   #查询功能  可忽略大小写、单双引号
 27     print('Syntax examples:\n   select name,age from staff_table where age > 22\n   select * from staff_table where dept = \"IT\"\n   select * from staff_table where enroll_date like \"2013\"')
 28     while True:
 29         n=0
 30         file_to_date(file_path)
 31         cmd=input('please input cmd(q break):').strip().lower().split()
 32         if cmd[0]=='q':break
 33         cmd=[cmd[1], cmd[5:]]
 34         if '\''in cmd[1][2]:cmd[1][2]=cmd[1][2].strip('\'')
 35         if '\"'in cmd[1][2]:cmd[1][2]=cmd[1][2].strip('\"')
 36         for line in staff_table:
 37             if cmd[1][1] in  ['>','<','>=','<=']:
 38                 if (cmd[1][1]=='>'and int(line[cmd[1][0]]) > int(cmd[1][2])) or (cmd[1][1]=='>='and int(line[cmd[1][0]]) >= int(cmd[1][2])) or (cmd[1][1]=='<'and int(line[cmd[1][0]]) < int(cmd[1][2])) or (cmd[1][1]=='<='and int(line[cmd[1][0]]) <= int(cmd[1][2])):
 39                     output(line, cmd)
 40                     n += 1
 41             elif cmd[1][1] == '='and (line[cmd[1][0]] in [cmd[1][2] ,cmd[1][2].strip('\''),cmd[1][2].strip('\"'),cmd[1][2].lower()] or (cmd[1][2].isdigit() and line[cmd[1][0]] == int(cmd[1][2]))):
 42                 output(line,cmd)
 43                 n += 1
 44             elif cmd[1][1] == 'like' and cmd[1][2] in line[cmd[1][0]].split('-') or cmd[1][2] in line[cmd[1][0]] or cmd[1][2] in line[cmd[1][0]].lower():
 45                 output(line,cmd)
 46                 n += 1
 47         print('相关查询共%d条' % n)
 48 def create():   #创建  只判断年龄、手机号格式,入职时间为当前时间
 49     phone=[]
 50     file_to_date(file_path)
 51     while True:
 52         info=input('Please enter your name,age,phone number and dept\nuse \',\' to separate(q for break):').strip().split(',')
 53         if info[0]=='q':break
 54         info={'staff_id':len(staff_table)+1,'name':info[0].strip(),'age':info[1].strip(),'phone':info[2].strip(),'dept':info[3].strip(),'enroll_date':time.strftime('%Y-%m-%d', time.localtime()) }
 55         if not info['age'].isdigit() or int(info['age'])not in range(1,110):
 56             print('Incorrect age format')
 57             continue
 58         for line in staff_table:
 59             phone.append(line['phone'])
 60         if info['phone'] in phone:
 61             print('The phone number already exists')
 62             continue
 63         if len(info['phone'])!=11 or not info['phone'].isdigit() or not info['phone'].startswith('1'):
 64             print('Incorrect phone number format')
 65             continue
 66         if not info['age'].isdigit() or int(info['age'])not in range(1,110):
 67             print('Incorrect age format')
 68             continue
 69         staff_table.append(info)
 70         date_to_file(file_path)
 71 def delete():   #删除
 72     while True:
 73         print_table(file_path)
 74         cmd_n=int(input('Please enter the number to delete(0 for break):'))
 75         if  cmd_n==0:break
 76         staff_table.pop(cmd_n-1)
 77         for i,line in enumerate(staff_table,1):
 78             line['staff_id']=i
 79         date_to_file(file_path)
 80 def update():   #更新  可去除单引号、双引号
 81     global staff_table
 82     while True:
 83         print_table(file_path)
 84         print('Syntax examples:\n   UPDATE staff_table SET dept=\'Market\' WHERE where dept=\'IT\' ')
 85         cmd = input('Please enter the modified information(q for break):\n').split()
 86         if cmd[0]=='q':break
 87         cmd=[cmd[3],cmd[6]]
 88         sort=cmd[0].split('=')[0]
 89         where=cmd[1].split('=')[0]
 90         after = cmd[0].split('=')[1]
 91         before = cmd[1].split('=')[1]
 92         if '\"' in cmd[0] or '\"' in cmd[1]:
 93             after = cmd[0].split('=')[1].strip('\"')
 94             before = cmd[1].split('=')[1].strip('\"')
 95         if '\''in cmd[0] or '\''in cmd[1]:
 96             after=cmd[0].split('=')[1].strip('\'')
 97             before=cmd[1].split('=')[1].strip('\'')
 98         for line in staff_table:
 99             if line[where]== before:
100                 line[sort]= after
101         date_to_file(file_path)
102 def main():
103     while True:
104         print('The function menu:1、select  2、create  3、delete  4、update  5、view all(\'q\' for break)')
105         cmd=input('please input the cmd:').strip()
106         if cmd == '1':select()
107         elif cmd == '2':create()
108         elif cmd == '3':delete()
109         elif cmd == '4':update()
110         elif cmd == '5':print_table(file_path)
111         elif cmd == 'q':break
112         else:continue
113 main()
完整版

 

 单文件日志

import logging
  
  
logging.basicConfig(filename='log.log',
                    format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S %p',
                    level=10)
  
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')

对于上述记录日志的功能,只能将日志记录在单文件中,如果想要设置多个日志文件,logging.basicConfig将无法完成,需要自定义文件和日志操作对象。

# 定义文件
file_1_1 = logging.FileHandler('l1_1.log', 'a', encoding='utf-8')
fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s")
file_1_1.setFormatter(fmt)

file_1_2 = logging.FileHandler('l1_2.log', 'a', encoding='utf-8')
fmt = logging.Formatter()
file_1_2.setFormatter(fmt)

# 定义日志
logger1 = logging.Logger('s1', level=logging.ERROR)
logger1.addHandler(file_1_1)
logger1.addHandler(file_1_2)


# 写日志
logger1.critical('1111')

 

# 定义文件
file_2_1 = logging.FileHandler('l2_1.log', 'a')
fmt = logging.Formatter()
file_2_1.setFormatter(fmt)

# 定义日志
logger2 = logging.Logger('s2', level=logging.INFO)
logger2.addHandler(file_2_1)

 日志等级

CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
posted @ 2017-06-17 17:03  maple-shaw  阅读(304)  评论(0)    收藏  举报