logging模块实际使用调试说明


start.py :

[Python] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

import sys,os                                   #应该把项目的根目录添加到环境变量中

BASE_DIR=os.path.dirname(os.path.dirname(__file__)#os.path.dirname(__file__) 获取当前文件上一级路径名

sys.path.append(BASE_DIR)                       #拿到ATM所在的文件夹

from core import src

src.run()

sys.path.append(r'D:\code\SH_fullstack_s1\day15\ATM') 添加的是绝对路径,不支持移植到别的硬件上运行

 

src.py :

 

from conf import settings

from lib import common

logger1=common.get_logger('atm')

def login():

    print('登录....')

    with open(settings.DB_PATH,encoding='utf-8') as f:

        for line in f:

            print(line)

def register():

    print('注册....')

def shop():

    print('购物....')

def pay():

    print('支付...')

def transter():

    print('转账...')

    common.logger('xxxx给他爹xx转账10000')

    logger1.debug('xxxx给他爹xx转账10000')

    logger1.error('xxxx给他爹xx转账10000,转账失败')

def run():

    while True:

        print("""

        1 登录

        2 注册

        3 购物

        4 支付

        5 转账

        """)

        choice=input('>>: ').strip()

        if choice == '1':

            login()

        elif choice == '2':

            register()

        elif choice == '3':

            shop()

        elif choice == '4':

            pay()

        elif choice == '5':

            transter()

        else:

            print('输入错误指令')


settings.py:

[Python] 纯文本查看 复制代码

?

1

2

3

DB_PATH=r'D:\code\SH_fullstack_s1\day15\ATM\db\db.txt' #自定义设置的文件路径

LOG_PATH=r'D:\code\SH_fullstack_s1\day15\ATM\log\access.log'

LOGGING_DIC = {.....}               #log配置字典


common.py :

[Python] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

from conf import settings

def logger(msg):

    with open(settings.LOG_PATH,'a',encoding='utf-8') as f:

        f.write('%s\n' %msg)

         

import logging.config

import logging

from conf import settings

def get_logger(name): #name='atm'

    logging.config.dictConfig(settings.LOGGING_DIC)  # 导入上面定义的logging配置

    l1=logging.getLogger(name)

    return l1


logging 模块

[Python] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

import logging

logging.basicConfig(      #为logging模板指定全局配置,针对所有logger有效,控制打印到文件中

filename='access.log',          # /stream=sys.stdout 打印在屏幕上,但和filename只能存在其一

format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',

datefmt='%Y-%m-%d %H:%M:%S %p',

level=40

)

logging.debug('debug...') # 10

logging.info('info....') #20

logging.warning('.....') #30

logging.error('......') # 40

logging.critical('.....') #50

 

[Python] 纯文本查看 复制代码

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

6.51 logging模块的四类对象

logger:负责产生日志

 

logger1=logging.getLogger('xxx')

filter:过滤日志(不常用)

 

handler:控制日志打印到文件or终端

 

fh1=logging.FileHandler(filename='a1.log',encoding='utf-8')

fh2=logging.FileHandler(filename='a2.log',encoding='utf-8')

sh=logging.StreamHandler()

formatter:控制日志的格式

 

formatter1=logging.Formatter(

fmt='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',

datefmt='%Y-%m-%d %H:%M:%S %p',

)

formatter2=logging.Formatter(fmt='%(asctime)s - %(message)s',)

logger ---->多个file handler <----多个formatter

 

绑定关系:

 

1.为logger1对象绑定handler:

 

logger1.addHandler(fh1)

logger1.addHandler(fh2)

logger1.addHandler(sh)

2.为handler对象绑定日志格式

 

fh1.setFormatter(formatter1)

fh2.setFormatter(formatter1)

sh.setFormatter(formatter2)

设定日志级别: 两层关卡,必须都通过,日志才能正常记录

 

logger1.setLevel(10)

fh1.setLevel(10)

fh2.setLevel(10)

sh.setLevel(10)

#调用logger1对象下的方法,产生日志,然后交给不同的handler,控制日志记录到不同的地方

logger1.debug('调试信息')   #调用logger1,产生日志

日志的继承

 

import logging

logger1=logging.getLogger('xxx')

logger2=logging.getLogger('xxx.son')

logger3=logging.getLogger('xxx.son.grandson')

sh=logging.StreamHandler()

formatter2=logging.Formatter(fmt='%(asctime)s - %(message)s',)

sh.setFormatter(formatter2)

logger1.addHandler(sh)

logger2.addHandler(sh)

logger3.addHandler(sh)

logger1.setLevel(10)

logger2.setLevel(10)

logger3.setLevel(10)

sh.setLevel(10)

logger1.debug('测试。。。。')

logger2.debug('测试。。。。')

logger3.debug('测试。。。。')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值