1-2 高级应用
最后更新于:2022-04-02 07:44:53
~~~
#!/usr/bin/env python
# coding: utf-8
# @Time : 2021/11/10 17:23
# @Author : YD
# @Email : dinhe_1985@126.com
# @File : log-2.py
# @Software: PyCharm
# @Blog : www.noteshare.cn
import logging
# 实例化记录器,设置记录器名称
logger = logging.getLogger(name='dinghe')
logger.setLevel(logging.CRITICAL)
# 创建处理器
# 屏幕输出
console = logging.StreamHandler()
console.setLevel(logging.WARN)
# 文件输出
file = logging.FileHandler(filename='addDemo.log')
file.setLevel(logging.ERROR)
# formatter格式化
# formatter = logging.Formatter("%(name)s|%(asctime)s|%(levelname)s|%(filename)s:%(lineno)s|%(message)s")
formatter = logging.Formatter("%(asctime)s|%(levelname)s|%(filename)s:%(lineno)s|%(message)s")
# 给处理器设置格式
console.setFormatter(formatter)
file.setFormatter(formatter)
# 创建过滤器(过滤标记),可以作用在Handler
flt = logging.Filter('root')
# logger.addFilter(flt)
# 记录器设置处理器
file.addFilter(flt)
logger.addHandler(console)
logger.addHandler(file)
logger.debug('This is debug log')
logger.info('This is info log')
logger.warning('this is warning log')
logger.error('this is error log root')
logger.critical('this is critical log')
~~~
#### 时间格式详细格式参考
```
https://docs.python.org/zh-cn/3.8/library/logging.html#logrecord-attributes
https://docs.python.org/zh-cn/3.8/library/time.html#time.strftime
```
';