zoukankan      html  css  js  c++  java
  • python日志篇-基础版

       对常用python日志语法做记录,方便以后重复使用

     print内容记录到文件:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    ##______________________命令行执行test.py文件并写入执行结果到abc.log文件_____________________
    # -*- coding: UTF-8 -*-
    for i in range(1,21):
        print("the number is {}".format(i))
    
    '''
    在cmd中运行
    python test.py>adc.log
    '''
    
    ##————————————————————————直接运行就可以记录打印内容———————————————————————————————— #!/usr/bin/env python # -*- coding: utf-8 -*- import sys origin = sys.stdout#标准输出文件 #打开文件并执行控制台 f = open('file.txt', 'w') sys.stdout = f print ('开始记录打印内容') a=555 print('a=',a) print ('Start of progeeeeeeeeeeeeeeeeeeeram') # 你的程序放到这里,过程中所有print到屏幕的内容都同时保存在file.txt里面了。 print ('End of program') sys.stdout = origin f.close()

    #——————————————————print_wire.py模块——————直接执行或通过导入模块名执行即可———————————————————————————————— #!/usr/bin/env python # encoding: utf-8 import sys import time class Logger(object): def __init__(self, filename="Default.log"): self.terminal = sys.stdout self.log = open(filename, "a")#a表示追加,w覆盖写入 def write(self, message): self.terminal.write(message) if '下载进度' not in message:#过滤下载进度的日志 #a=str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))) self.log.write(message) def flush(self): pass now = time.strftime("%Y-%m-%d", time.localtime())#获取当前日期 sys.stdout = Logger('123456.txt')#存放文件名 if __name__ == '__main__': __console__=sys.stdout print('---------start---------') print('1234567890123456789') print('---------stop---------') sys.stdout=__console__ time.sleep(10) ''' 如果在其他模块需要记录print内容,只需import rint_wire即可 '''

    python logging日志封装:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Author: zhangjun
    # @Date  : 2018/7/26 9:20
    # @Desc  : Description
    
    import logging
    import logging.handlers
    import os
    import time
    
    class logs(object):
        def __init__(self):
            self.logger = logging.getLogger("")
            ## 设置输出的等级
            LEVELS = {'NOSET': logging.NOTSET,
                      'DEBUG': logging.DEBUG,
                      'INFO': logging.INFO,
                      'WARNING': logging.WARNING,
                      'ERROR': logging.ERROR,
                      'CRITICAL': logging.CRITICAL}
            ##_________________________同时打印控制台并写入文件____________________________________
            ## 创建文件目录
            logs_dir="logs2"
            if os.path.exists(logs_dir) and os.path.isdir(logs_dir):
                pass
            else:
                os.mkdir(logs_dir)
            ## 修改log保存位置
            timestamp=time.strftime("%Y-%m-%d",time.localtime())
            logfilename='%s.txt' % timestamp
            logfilepath=os.path.join(logs_dir,logfilename)
            rotatingFileHandler = logging.handlers.RotatingFileHandler(filename =logfilepath,
                                                                       maxBytes = 1024 * 1024 * 50,
                                                                       backupCount = 5)
            ## 设置输出格式
            formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
            rotatingFileHandler.setFormatter(formatter)
            ## 控制台句柄
            console = logging.StreamHandler()
            console.setLevel(logging.NOTSET)
            console.setFormatter(formatter)
            ## 添加内容到日志句柄中
            self.logger.addHandler(rotatingFileHandler)
            self.logger.addHandler(console)
            self.logger.setLevel(logging.NOTSET)
    
            ##___________________________只打印控制台不写入文件____________________________________________
            # logging.basicConfig(level=logging.DEBUG,
            #             format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
            
    
            #__________________________只写入文件不打印控制台______________________________________________
            # ## 创建文件目录
            # logs_dir="logs2"
            # if os.path.exists(logs_dir) and os.path.isdir(logs_dir):
            #     pass
            # else:
            #     os.mkdir(logs_dir)
            # ## 修改log保存位置
            # timestamp=time.strftime("%Y-%m-%d",time.localtime())
            # logfilename='%s.txt' % timestamp
            # logfilepath=os.path.join(logs_dir,logfilename)
            # rotatingFileHandler = logging.handlers.RotatingFileHandler(filename =logfilepath, maxBytes = 1024 * 1024 * 50,backupCount = 5)
            # ## 设置输出格式
            # formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', '%Y-%m-%d %H:%M:%S')
            # rotatingFileHandler.setFormatter(formatter)
            # ## 添加内容到日志句柄中
            # self.logger.addHandler(rotatingFileHandler)
            # self.logger.setLevel(logging.NOTSET)
    
    
        def info(self, message):
            self.logger.info(message)
    
        def debug(self, message):
            self.logger.debug(message)
    
        def warning(self, message):
            self.logger.warning(message)
    
        def error(self, message):
            self.logger.error(message)
    
    
    
    if __name__ == '__main__':
        logger = logging.getLogger(__name__)
        logger=logs()
        logger.info("this is info")
        logger.debug("this is debug")
        logger.error("this is error")
        #logger.warning("this is warning")
        
    
        
    # #在其他模块调用日志
    # import logging
    # logger = logging.getLogger(__name__)
    # import 日志的模块
    # if __name__ == '__main__':
    #     logger=日志模块.logs()
    #     logger.info("this is info")
    #     logger.debug("this is debug")
    #     logger.error("this is error")
    #     logger.warning("this is warning")

    第三方loguru模块处理日志:

       如果想更简洁,可用loguru库,python3安装:pip3 install loguru。

       loguru默认的输出格式是上面的内容,有时间、级别、模块名、行号以及日志信息,不需要手动创建 logger,直接使用即可,另外其输出还是彩色的,看起来会更加友好。

    from loguru import logger
    
    logger.debug('this is a debug message')
    logger.info('this is another debug message')
    logger.warning('this is another debug message')
    logger.error('this is another debug message')
    logger.info('this is another debug message')
    logger.success('this is success message!')
    logger.critical('this is critical message!')
    

     写入文件:

    from loguru import logger
    
    logger.add('my_log.log')
    logger.debug('this is a debug')

    运行之后会发现目录下 my_log.log 出现了刚刚控制台输出的 DEBUG 信息

    相关连接:

    https://mp.weixin.qq.com/s?__biz=MzkxNDI3NjcwMw==&mid=2247493818&idx=1&sn=1b913b843f60b522041dcd0807f2ba2f .....................loguru一行代码搞定Python日志

    https://blog.csdn.net/cui_yonghua/article/details/107498535 ........................................................................................................................loguru详细用法(好处:不用学代码直接调用即可

    https://www.jb51.net/article/201169.htm .........................................................................................................................................................python 如何对logging日志封装
     

    日志服务相关连接(详情在数据分类):

    https://c4ys.com/archives/552 ....................................................................python+logstash+elasticsearch+Kibana日志方案

    https://www.cnblogs.com/xuzhongtao/p/12466351.html ..............................Kibana搭建

  • 相关阅读:
    JNI_Android项目中调用.so动态库实现详解
    Android动态加载so文件
    Android多媒体开发(3)————使用Android NKD编译havlenapetr-FFMpeg-7c27aa2
    Android的NDK开发(5)————Android JNI层实现文件的read、write与seek操作
    Android的NDK开发(4)————JNI数据结构之JNINativeMethod
    Android的NDK开发(3)————JNI数据类型的详解
    ORACLE 实验二
    ORA-12705: Cannot access NLS data files or invalid environment specified
    内存对齐的规则以及作用
    13.怎样自学Struts2之Struts2本地化[视频]
  • 原文地址:https://www.cnblogs.com/chen-xia/p/15469230.html
Copyright © 2011-2022 走看看