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
    
    
     
  • 相关阅读:
    两数之和
    IntelliJ IDEA为类和方法自动添加注释
    IDEA main 函数的快捷键
    Mac终端开启代理
    Pycharm节能模式
    使用正则表达式替换构造字典
    使用代理爬取微信文章
    利用 Scrapy 爬取知乎用户信息
    Scrapy选择器的用法
    Scrapy命令行基本用法
  • 原文地址:https://www.cnblogs.com/shaosks/p/6098387.html
Copyright © 2011-2022 走看看