zoukankan      html  css  js  c++  java
  • 七、logging模块

    1. 日志等级

      CRITICAL : 'CRITICAL',
      ERROR : 'ERROR',
      WARNING : 'WARNING',
      INFO : 'INFO',
      DEBUG : 'DEBUG',
      NOTSET : 'NOTSET'

     【note】:等级是从高到低,当为某一程序设置日志等级时,只会输出高于或等于这级别的日志信息,如,日志等级设置为 error,则只会输出 日志信息级别为 error和critical 的日志信息

    2. 代码

      ###导入 logging模块和colorlog,colorlog模块是console输出带颜色log

      import logging,colorlog

      def log(self,message,log_level):

        ###设置console输出log的颜色,此处也是默认颜色

        log_colors={

              'DEBUG': 'white',
              'INFO': 'green',
              'WARNING': 'yellow',
              'ERROR': 'red',
              'CRITICAL': 'bold_red'

              }

        ###打印不同level的log

        level = { "debug": logging.DEBUG,
            "info": logging.INFO,
            "warning": logging.WARNING,
            "error": logging.ERROR,
            "critical": logging.CRITICAL
          }.get(log_level)

          ### 创建DEBUG级别的记录器
        logger = logging.getLogger(__name__)
             logger.setLevel(logging.DEBUG)

          ### 判断logger.handlers 列表是否为空,如果为空,则添加handlers,否则直接打印日志,此处可以解决重复打印问题
     
            if not logger.handlers:

            # file日志格式,, 创建日志处理程序,并将log命名为log.txt,保存在当前目录下
          handler_file = logging.FileHandler('log.txt', 'w','utf-8')
          formatter_file = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
          # console日志格式
          handler_console = logging.StreamHandler()
          formatter_console=colorlog.ColoredFormatter(fmt='%(log_color)s%(asctime)s - %(log_color)s%(name)s - %(log_color)s%(levelname)s - %(log_color)s%(message)s', og_colors=log_colors)
          #设置格式
          handler_console.setFormatter(formatter_console)
          handler_file.setFormatter(formatter_file)
          # 将日志处理程序加入到记录器
          logger.addHandler(handler_console)
          logger.addHandler(handler_file)
        logger.log(level,message)
        return logger

    3. formatter其他参数

    • %(levelno)s:输出日志级别的数值。
    • %(levelname)s:输出日志level的名称。
    • %(pathname)s:输出当前脚本路径。
    • %(filename)s:输出当前执行程序名。
    • %(funcName)s:输出日志的当前函数。
    • %(lineno)d:输出日志的当前行号。
    • %(asctime)s:输出日志的时间。
    • %(thread)d:输出线程ID。
    • %(threadName)s:输出线程名称。
    • %(process)d:输出进程ID。
    • %(processName)s:输出进程名称。
    • %(module)s:输出模块名称。
    • %(message)s:输出日志具体信息。
  • 相关阅读:
    docker是PaaS,与openstack是IaaS的关系
    nuget安装.net standard
    GitHub sync the original repository by pull request
    Is there a way to include commas in CSV columns without breaking the formatting?
    How to determine why visual studio might be skipping projects when building a solution
    IHttpHandler vs IHttpModule
    .NET 3.0 SDK Projects not Loading
    Microsoft Edge version
    Microsoft Edge High CPU and Memory
    Google Analytics
  • 原文地址:https://www.cnblogs.com/cj1138187197/p/12895430.html
Copyright © 2011-2022 走看看