在日常开发或者运维中,日志是必不可少的。不仅方便我们排查问题,更能进行深一层数据挖掘。在Python的标准库中logging模块提供了日志记录的功能。

logger 配置包括以下四个方面:

  • Loggers # 日志记录器,是程序中直接调用的接口
  • Handlers # 日志处理器,可配置存储路径等信息
  • Filters # 过滤器,例如定义输出级别等信息
  • Formatters # 格式化日志的输出格式

logger 日志级别分为以下:

  • DEBUG: Low level system information for debugging purposes
  • INFO: General system information
  • WARNING: Information describing a minor problem that has occurred.
  • ERROR: Information describing a major problem that has occurred.
  • CRITICAL: Information describing a critical problem that has occurred

简单举个例子:

1
2
3
4
5
6
7
8
9
import logging
FORMAT ='%(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT,level=logging.DEBUG)

logging.debug('debug message')
logging.info('info message')
logging.warn('warn message')
logging.error('error message')
logging.critical('critical message')

输出结果如下:

1
2
3
4
5
2018-05-25 16:00:13,181 - DEBUG - debug message
2018-05-25 16:00:13,181 - INFO - info message
2018-05-25 16:00:13,181 - WARNING - warn message
2018-05-25 16:00:13,181 - ERROR - error message
2018-05-25 16:00:13,181 - CRITICAL - critical message

如果我们去掉指定的DEBUG级别会不怎么样尼?

1
2
3
4
5
6
7
8
9
import logging
FORMAT ='%(asctime)s - %(levelname)s - %(message)s'
logging.basicConfig(format=FORMAT)

logging.debug('debug message')
logging.info('info message')
logging.warn('warn message')
logging.error('error message')
logging.critical('critical message')

输出结果如下:

1
2
3
2018-05-25 16:00:13,181 - WARNING - warn message
2018-05-25 16:00:13,181 - ERROR - error message
2018-05-25 16:00:13,181 - CRITICAL - critical message

这样我们是否会困惑尼?为何debug和info的日志并没有输出的尼?
通常按照博主的思维习惯,默认肯定是上官网查找问题,因为一般官网基本能解决80%的困惑。我们可以通过官网发现https://docs.python.org/3/library/logging.html以下

Level Numeric value
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0

简单总结:当我们定义日志级别为INFO时候,当Numeric value>=20时候才会输出的对应级别的日志

Django配置实例

settings.py新增以下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
},
'handlers': {
'file': {
'class': 'logging.FileHandler',
'formatter': 'verbose',
'filename': os.path.join(BASE_DIR, 'logs', 'ansible.log'),
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
},
},
}

views.py配置如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
from django.http import HttpResponse
import json
import logging.config
logging.getLogger('django') #引用settings配置中的loggers下的django
# Create your views here.


def test(request):
logging.info(request.method)
data={
'status':'success'
}
return HttpResponse(json.dumps(data), content_type="application/json")

启动django,模拟访问test接口,然后到logs目录下的ansible.log查看日志吧

附官网文档地址:

Comments

2018-05-28