码迷,mamicode.com
首页 > 编程语言 > 详细

python使用logging模块实现日志写入

时间:2018-04-27 02:33:46      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:功能   file   arm   handle   set   filename   pychar   author   输出   

python实现的logging写入日志的功能。logging模块还是挺好用的

 

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 
 4 # @Time    : 2018/4/25 17:05
 5 # @Author  : zms
 6 # @Site    : 
 7 # @File    : Log.py
 8 # @Software: PyCharm Community Edition
 9 
10 import time
11 import logging
12 import os
13 from logging.handlers import RotatingFileHandler
14 
15 project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16 log_path = project_dir + r"\log\\"
17 
18 
19 class Log(logging.Logger):
20     def __init__(self, logname):
21         # super(MyLogger, self).__init__(filename)
22         filename = log_path + logname + .log
23         logging.Logger.__init__(self, filename)
24 
25         # 设置日志格式
26         fmtHandler = logging.Formatter(%(asctime)s [%(filename)s:%(lineno)s][%(levelname)s] %(message)s)
27 
28         # 终端log输出流设置
29         try:
30             consoleHd = logging.StreamHandler()
31             consoleHd.setLevel(logging.ERROR)
32             consoleHd.setFormatter(fmtHandler)
33             self.addHandler(consoleHd)
34         except Exception as reason:
35             self.error("%s" % reason)
36 
37             # 设置log文件
38         try:
39             os.makedirs(os.path.dirname(filename))
40         except Exception as reason:
41             pass
42         try:
43             # 设置回滚日志,每个日志最大10M,最多备份5个日志
44             fileHd = logging.handlers.RotatingFileHandler(
45                 filename, maxBytes=10 * 1024 * 1024, backupCount=5)
46             # fileHd = logging.FileHandler(filename)
47             fileHd.setLevel(logging.INFO)
48             fileHd.setFormatter(fmtHandler)
49             self.addHandler(fileHd)
50         except Exception as reason:
51             self.error("%s" % reason)
52 
53         return
54 
55 
56 
57 if __name__ == __main__:
58     test1 = Log(test1)
59     test2 = Log(test2)
60     while True:
61         test1.error("test1")
62         test2.error("test2")

 

python使用logging模块实现日志写入

标签:功能   file   arm   handle   set   filename   pychar   author   输出   

原文地址:https://www.cnblogs.com/bluezms/p/8955427.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!