• 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
    
    
     
  • 相关阅读:
    zabbix 安装(离线源码安装)
    云天励飞摄像头rtsp取流格式
    k8s创建deployment时出现错误ValidationError
    pod 生命周期
    十. Python基础(10)--装饰器
    九. Python基础(9)--命名空间, 作用域
    八. Python基础(8)--函数
    七. Python基础(7)--文件的读写
    六. Python基础(6)--语法
    五. Python基础(5)--语法
  • 原文地址:https://www.cnblogs.com/shaosks/p/6098387.html
Copyright © 2020-2023  润新知