知识记录:Logging库使用方法简单来说就是提供了一个打印日志的载体(logger),而handler就是这个工具中的模块,具体打印日志是handler决定的(输出地点,格式等等),执行logger相当于执行里头所有的handler(互不干扰)。

功能:在文件当前存储目录下创建Logs文件夹,根据时间(精确到小时)生成日志文件

使用方法:在项目目录创建py文件,将代码copy过去,然后在项目中如果有需要打印日志的地方直接调用对应等级的方法就行。

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import logging
import os
import time

class Log:
def __init__(self):
self.logger = logging.getLogger() #创建logger
self.logger.setLevel(logging.INFO) #日志root等级
self.log_path = os.path.dirname(os.path.realpath(__file__)) + '/Logs/' #日志目录
#日志内容格式
self.formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
if os.path.exists(self.log_path) == False: #目录不存在就创建
os.makedirs(self.log_path)

def printLog(self,log_type,log_content): #输出日志
logTime = time.strftime('%Y%m%d%H', time.localtime(time.time())) #当前时间到小时
log_file = self.log_path + logTime + '.log' #文件名
if os.path.exists(log_file) == False: #日志文件不存在就创建
fd = open(log_file, mode="w", encoding="utf-8")
fd.close()

handler = logging.FileHandler(log_file, mode='a')
handler.setLevel(logging.DEBUG) # handler的日志等级
handler.setFormatter(self.formatter) # 设置日志格式
self.logger.addHandler(handler) #添加handler
if log_type == 0:
self.logger.info(log_content)
elif log_type == 1:
self.logger.warning(log_content)
elif log_type == 2:
self.logger.error(log_content)
else:
self.logger.critical(log_content)
self.logger.removeHandler(handler) #记得删除handler防止重复打印

def printInfo(self,log_content):
self.printLog(0,log_content)

def printWarning(self,log_content):
self.printLog(1,log_content)

def printError(self,log_content):
self.printLog(2,log_content)

def printCritical(self,log_content):
self.printLog(3,log_content)

if __name__ == '__main__':
Log = Log()
Log.printInfo('不')
Log.printWarning('点')
Log.printError('赞')
Log.printCritical('吗')
Log.printWarning('( ´͈ ᵕ `͈ )◞♡')

参考博客:https://blog.csdn.net/vocaloid01/article/details/108896540