zoukankan      html  css  js  c++  java
  • python 记录日志logging

    在项目开发中,往往要记录日志文件。用python记录日志有两种方式:

      1、利用python 自带的logging库,例如:

     # -*- coding: utf-8 -*-
    
    import os
    import codecs
    import datetime
    
    import logging
    
    #封装logging日志
    class LogFile:
        #构造函数 fileName:文件名
        def __init__(self,fileName,level=logging.INFO):
            fh = logging.FileHandler(fileName)
            self.logger = logging.getLogger()
            self.logger.setLevel(level)
            formatter = logging.Formatter('%(asctime)s : %(message)s','%Y-%m-%d %H:%M:%S')
            fh.setFormatter(formatter)
            self.logger.addHandler(fh)
    
        def WriteLog(self,message):
            self.logger.info(message)
    
        def WriteErrorLog(self,message):
            self.logger.setLevel(logging.ERROR)
            self.logger.error(message)


    2、自己写日志
      
    import os
    import time
    class Log:
        def __init__(self):
            pass
    
        def WriteLog(self,message,flag = False):
            strMessage = '
    ' + time.strftime('%Y-%m-%d %H:%M:%S')
            if flag:
                strMessage += ': %s' % message
            else:
                strMessage += ':
    %s' % message
    
            fileName = os.path.join(os.getcwd(), time.strftime('%Y-%m-%d')+ '.txt')
            with open(fileName, 'a',encoding='utf-8') as f: 
          f.write(strMessage)

    # log = Log() # log.WriteLog('aaa') # 输出结果: # 2017-11-24 10:39:52: # aaa # 2017-11-24 10:39:56:aaa
    
    
     
  • 相关阅读:
    使用国内镜像安装pyqt5
    python线程池 ThreadPoolExecutor 的用法及实战
    进程和线程、协程的区别
    python线程池实现
    python 多进程使用总结
    参与开源项目
    脑图——前端技术
    HTML中DTD使用小结
    浅谈面向对象——追溯法
    Dva.js 里面的几个概念
  • 原文地址:https://www.cnblogs.com/shaosks/p/6098387.html
Copyright © 2011-2022 走看看