log案例
# 案例
# -*- coding: utf-8 -*-
import time
import sys
import logging
from logging import handlers
class Log(object):
@classmethod
def get_logger(cls, filename, level=logging.DEBUG):
# 创建日志对象
log = logging.getLogger(filename)
# 设置日志级别
log.setLevel(level)
# 日志输出格式
fmt = logging.Formatter('%(asctime)s %(thread)d %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
# 数据流
stream_handler = logging.StreamHandler(sys.stdout)
stream_handler.setFormatter(fmt)
# 输出到文件
# 日志文件按天进行保存,每天一个日志文件
file_handler = handlers.TimedRotatingFileHandler(filename=filename, when='D', backupCount=1, encoding='utf-8')
# 按照大小自动分割日志文件,一旦达到指定的大小重新生成文件
# file_handler = handlers.RotatingFileHandler(filename=filename,
# maxBytes=1 * 1024 * 1024 * 1024,
# backupCount=1,
# encoding='utf-8')
file_handler.setFormatter(fmt)
log.addHandler(stream_handler)
log.addHandler(file_handler)
return log
logger = Log.get_logger('./api_{}.log'.format(time.strftime('%Y-%m-%d', time.localtime()), level=logging.INFO))
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
26
27
28
29
30
31
32
33
34
35
36
2
3
4
5
6
7
8
9
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
上次更新: 2023/09/04, 18:39:45