Python学习day13-2 logging模块

 

用于便捷记录日志且线程安全的模块

单文件日志

1.import logging
2.
3.
4.logging.basicConfig(filename='log.log',
5. format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
6. datefmt='%Y-%m-%d %H:%M:%S %p',
7. level=10)
8.
9.logging.debug('debug')
10.logging.info('info')
11.logging.warning('warning')
12.logging.error('error')
13.logging.critical('critical')
14.logging.log(10,'log')

分析:
上面代码中level = 10;表示日志等级;且只有当前写等级大于,等于10(日志等级)的才能执行上面的代码,进行操作、记录;不然不执行。

logging.log():logging方法本质就是调用的这个方法

1.logging.log(2, "5435")
2.# 创建了一个等级为2;且内容为5435的序列

注意:
上面日志的等级
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0

问题:那我们在代码中怎么应用这些那?
可以看到上面的对象对应的等级是不同的;有的是数字有的却是字符
所以:在实际应用中;我们尽量不要写数字;
这样写:logging.ERROR 直接写logging.对应的日志名(注意是大写)

问题:这个模块的作用?
1、方便
2、线程安全;多人操作的时候不会出现脏数据(没用的数据)

多文件日志

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

1.# 定义文件
2.file_1_1 = logging.FileHandler('l1_1.log', 'a', encoding='utf-8')
3.# 创建格式
4.fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")
5.# 文件应用格式
6.file_1_1.setFormatter(fmt)
7.
8.# 定义第二个文件
9.file_1_2 = logging.FileHandler('l1_2.log', 'a', encoding='utf-8')
10.fmt = logging.Formatter()
11.file_1_2.setFormatter(fmt)
12.
13.# 定义日志
14.logger1 = logging.Logger('s1', level=logging.ERROR)
15.logger1.addHandler(file_1_1)
16.logger1.addHandler(file_1_2)
17.
18.
19.# 写日志
20.logger1.critical('1111')

日志二

1.# 定义文件
2.file_2_1 = logging.FileHandler('l2_1.log', 'a')
3.fmt = logging.Formatter()
4.file_2_1.setFormatter(fmt)
5.
6.# 定义日志
7.logger2 = logging.Logger('s2', level=logging.INFO)
8.logger2.addHandler(file_2_1)

如上述创建的两个日志对象

  • 当使用【logger1】写日志时,会将相应的内容写入 l1_1.log 和 l1_2.log 文件中
  • 当使用【logger2】写日志时,会将相应的内容写入 l2_1.log 文件中

posted on 2016-10-27 02:22  jayafs  阅读(100)  评论(0编辑  收藏  举报

导航