一个计算机技术爱好者与学习者

0%

好好学Python:Python打印日志

1. 输出日志到控制台

1
2
3
4
5
6
7
8
import sys
import logging

log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
log.addHandler(logging.StreamHandler(sys.stdout)) #默认sys.error

log.info('print info level log to console')

2. 输出日志到文件

1
2
3
4
5
6
7
8
import sys
import logging

log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
log.addHandler(logging.FileHandler('python.log'))

log.info('print info level log to file')

日志文件默认存储到执行命令的路径下,可以通过使用绝对路径来指定日志文件路径。

3. 封装日志模块

1、封装一个日志模块 log.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
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
56
57
58
59
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import logging
import logging.handlers

def init_log(log_path, level=logging.INFO, when="D", backup=7,
format="%(levelname)s: %(asctime)s: %(filename)s:%(lineno)d * %(thread)d %(message)s",
datefmt="%m-%d %H:%M:%S"):
"""
init_log - initialize log module

Args:
log_path - Log file path prefix.
Log data will go to two files: log_path.log and log_path.log.wf
Any non-exist parent directories will be created automatically
level - msg above the level will be displayed
DEBUG < INFO < WARNING < ERROR < CRITICAL
the default value is logging.INFO
when - how to split the log file by time interval
'S' : Seconds
'M' : Minutes
'H' : Hours
'D' : Days
'W' : Week day
default value: 'D'
format - format of the log
default format:
%(levelname)s: %(asctime)s: %(filename)s:%(lineno)d * %(thread)d %(message)s
INFO: 12-09 18:02:42: log.py:40 * 139814749787872 HELLO WORLD
backup - how many backup file to keep
default value: 7

Raises:
OSError: fail to create log directories
IOError: fail to open log file
"""
formatter = logging.Formatter(format, datefmt)
logger = logging.getLogger()
logger.setLevel(level)

dir = os.path.dirname(log_path)
if not os.path.isdir(dir):
os.makedirs(dir)

handler = logging.handlers.TimedRotatingFileHandler(log_path + ".log",
when=when,
backupCount=backup)
handler.setLevel(level)
handler.setFormatter(formatter)
logger.addHandler(handler)

handler = logging.handlers.TimedRotatingFileHandler(log_path + ".log.wf",
when=when,
backupCount=backup)
handler.setLevel(logging.WARNING)
handler.setFormatter(formatter)
logger.addHandler(handler)

2、使用日志模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import logging

import log

class VKTest(object):
def __init__(self):
logging.info('print info level log to file')

if __name__=="__main__":
# 日志保存到./log/vk.log和./log/vk.log.wf,按天切割,保留7天
log.init_log("./log/vk")
logging.info("程序启动!!!")

vk = VKTest()

logging.info("程序结束!!!")

执行脚本后,日志内容会输出到 log/vk.log 中。

4. 封装日志模块2.0

1、封装一个日志模块 log.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
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import logging
import logging.handlers

DEFAULT_LOG_PATH = './log/'

class Log(object):

def __init__(self,
logfile_name='default',
log_path=DEFAULT_LOG_PATH,
level=logging.INFO,
when="D",
backup=7,
format="%(levelname)s: %(asctime)s: %(filename)s:%(lineno)d * %(thread)d %(message)s",
datefmt="%m-%d %H:%M:%S"):
"""
init_log - initialize log module

Args:
log_path - Log file path prefix.
Log data will go to two files: log_path.log and log_path.log.wf
Any non-exist parent directories will be created automatically
level - msg above the level will be displayed
DEBUG < INFO < WARNING < ERROR < CRITICAL
the default value is logging.INFO
when - how to split the log file by time interval
'S' : Seconds
'M' : Minutes
'H' : Hours
'D' : Days
'W' : Week day
default value: 'D'
format - format of the log
default format:
%(levelname)s: %(asctime)s: %(filename)s:%(lineno)d * %(thread)d %(message)s
INFO: 12-09 18:02:42: log.py:40 * 139814749787872 HELLO WORLD
backup - how many backup file to keep
default value: 7

Raises:
OSError: fail to create log directories
IOError: fail to open log file
"""
formatter = logging.Formatter(format, datefmt)
# getLogger一定要传参,否则多次调用对象创建,得到的会是同一个logger对象
# 后果就是相同的日志内容,会同时写到多个不同的日志文件中
self.logger = logging.getLogger(logfile_name)
self.logger.setLevel(level)

if not os.path.exists(log_path):
os.makedirs(log_path)

common_log = os.path.join(log_path, logfile_name + ".log")
handler = logging.handlers.TimedRotatingFileHandler(common_log,
when=when,
backupCount=backup)
handler.setLevel(level)
handler.setFormatter(formatter)
self.logger.addHandler(handler)

wf_log = os.path.join(log_path, logfile_name + ".log.wf")
handler = logging.handlers.TimedRotatingFileHandler(wf_log,
when=when,
backupCount=backup)
handler.setLevel(logging.WARNING)
handler.setFormatter(formatter)
self.logger.addHandler(handler)

def get_logger(self):
return self.logger

# 同时输出内容到日志和控制台
def get_console_logger(self):
self.logger.addHandler(logging.StreamHandler(sys.stdout))
return self.logger

2、使用日志模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import log

# 日志保存到./log/vk.log和./log/vk.log.wf,按天切割,保留7天
logger = log.Log(logfile_name='vk').get_logger()
# logger = log.Log(logfile_name='vk').get_console_logger()

class VKTest(object):
def __init__(self):
logger.info('print info level log to file')

if __name__=="__main__":
logger.info("程序启动!!!")
vk = VKTest()
logger.info("程序结束!!!")

执行脚本后,日志内容会输出到 log/vk.log 中。

5. 参考文档

  • 本文作者: 好好学习的郝
  • 原文链接: https://www.voidking.com/dev-python-log/
  • 版权声明: 本文采用 BY-NC-SA 许可协议,转载请注明出处!源站会即时更新知识点并修正错误,欢迎访问~
  • 微信公众号同步更新,欢迎关注~