1.日志级别Level

日志记录级别的数值在下表中给出。日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET

我们设置了输出 level,系统便只会输出 level 数值大于或等于该 level 的的日志结果,例如我们设置了输出日志 level 为 INFO,那么输出级别大于等于 INFO 的日志,如 WARNING、ERROR 等,DEBUG 和 NOSET 级别的不会输出。默认的输出level为INFO。

级别

数值

CRITICAL

50

ERROR

40

WARNING

30

INFO

20

DEBUG

10

NOTSET

0

2.logging.basicConfig函数:

通过logging.basicConfig函数对日志的输出格式及方式做相关配置

def basicConfig(level=INFO, filename=None, stream=None, format=None, style="%"):global _level_level = levelif filename:h = FileHandler(filename)else:h = StreamHandler(stream)h.setFormatter(Formatter(format, style=style))root.handlers.clear()root.addHandler(h)

logging.basicConfig函数各参数:

level: 设置日志级别,默认为logging.WARNING

filename: 指定日志文件名

format: 指定输出的格式和内容 ,

    %(asctime)s: 打印日志的时间

    %(message)s: 打印日志信息

3.记录器(Logger)

Logger:即 Logger Main Class,是我们进行日志记录时创建的对象

如果没有显式的进行创建,则默认创建一个root logger,并应用默认的日志级别(WARN),处理器Handler(StreamHandler,即将日志信息打印输出在标准输出上),和格式化器Formatter(默认的格式%(message)s)。

创建方法:logger = logging.getLogger()

def getLogger(name=None):if name is None:name = "root"if name in _loggers:return _loggers[name]if name == "root":l = Logger(name)sh = StreamHandler()sh.formatter = Formatter()l.addHandler(sh)else:l = Logger(name)_loggers[name] = lreturn l

创建Logger实例后,可以使用以下方法进行日志级别设置,增加处理器Handler。

  • logger.setLevel(logging.ERROR)   # 设置日志级别为ERROR,即只有日志级别大于等于ERROR的日志才会输出
  • logger.addHandler(handler_name) # 为Logger实例增加一个处理器

4.处理器(Handler)

处理器将日志记录发送给其他输出终端,他们获取日志记录并用相关函数中处理它们。

比如,一个文件处理器将会获取一条日志记录,并且把它添加到文件中。

本logging 模块提供的 Handler 有:

  • StreamHandler:logging.StreamHandler;日志输出到流,可以是 sys.stderr,sys.stdout 。
  • FileHandler:logging.FileHandler;日志输出到文件。

StreamHandler创建方法:sh = logging.StreamHandler()

class StreamHandler(Handler):def __init__(self, stream=None):self._stream = stream or sys.stderrself.terminator = "\n"self.formatter = Formatter()def emit(self, record):self._stream.write(self.formatter.format(record) + self.terminator)def flush(self):pass

FileHandler创建方法:fh = logging.FileHandler(filename)

class FileHandler(Handler):def __init__(self, filename, mode="a", encoding=None, delay=False):super().__init__()self.encoding = encodingself.mode = modeself.delay = delayself.terminator = "\n"self.filename = filenameself._f = Nonedef emit(self, record):self._f = open(self.filename, self.mode)self._f.write(self.formatter.format(record) + self.terminator)def close(self):if self._f is not None:self._f.close()

创建完fh/sh后,可以给它设置一个格式化器Formatter

例如:fh.setFormatter(formatter_name)
class Handler:def __init__(self):self.formatter = Formatter()def setFormatter(self, fmt):self.formatter = fmt

5.格式化器(Formatter)

使用Formatter对象设置日志信息最后的规则、结构和内容

formatter创建方法: formatter = logging.Formatter(fmt="%(asctime)s:%(massage)s", datefmt=None)

其中,fmt是消息的格式化字符串,datefmt是日期字符串,但本logging模块不支持。如果不指明fmt,将使用'%(message)s'。

class Formatter:converter = utime.localtimedef __init__(self, fmt=None, datefmt=None, style="%"):self.fmt = fmt or "%(message)s"self.datefmt = datefmtif style not in ("%", "{"):raise ValueError("Style must be one of: %, {")self.style = styledef usesTime(self):if self.style == "%":return "%(asctime)" in self.fmtelif self.style == "{":return "{asctime" in self.fmtdef format(self, record):# The message attribute of the record is computed using msg % args.record.message = record.msg % record.args# If the formatting string contains '(asctime)', formatTime() is called to# format the event time.if self.usesTime():record.asctime = self.formatTime(record, self.datefmt)# If there is exception information, it is formatted using formatException()# and appended to the message. The formatted exception information is cached# in attribute exc_text.if record.exc_info is not None:record.exc_text += self.formatException(record.exc_info)record.message += "\n" + record.exc_text# The record’s attribute dictionary is used as the operand to a string# formatting operation.if self.style == "%":return self.fmt % record.__dict__elif self.style == "{":return self.fmt.format(**record.__dict__)else:raise ValueError("Style {0} is not supported by logging.".format(self.style))def formatTime(self, record, datefmt=None):assert datefmt is None  # datefmt is not supportedct = utime.localtime(record.created)return "{0}-{1}-{2} {3}:{4}:{5}".format(*ct)def formatException(self, exc_info):raise NotImplementedError()def formatStack(self, stack_info):raise NotImplementedError()

6.简单使用:

import logginglogging.debug('debug message')
logging.info('info message')
logging.warning('warn message')
logging.error('error message')
logging.critical('critical message') 

输出:

info message
warn message
error message
critical message

7.简单配置:

logging.basicConfig(level=logging.DEBUG,format='%(asctime)s :  %(message)s')
logging.debug('debug message')

输出:

2019-6-18 16:49:10 :  debug message

8.记录日志到文件

import logging
logging.basicConfig(level=logging.DEBUG,filename='/flash/logger.log',format='%(asctime)s :  %(message)s')
logging.debug('debug message should go to the log file')
logging.info('info message should go to the log file')
logging.warning('warn message should go to the log file')
logging.error('error message should go to the log file')
logging.critical('critical message should go to the log file') 

logger.log文件会写入如下内容:

2019-6-18 17:2:20 :  debug message should go to the log file
2019-6-18 17:2:25 :  info message should go to the log file
2019-6-18 17:2:29 :  warn message should go to the log file
2019-6-18 17:2:34 :  error message should go to the log file
2019-6-18 17:2:39 :  critical message should go to the log file

9.把日志同时输出到标准输出和日志文件:

import logginglogger=logging.getLogger()fh = logging.FileHandler('a.log')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.setLevel(level = logging.DEBUG)
logger.addHandler(fh)logger.debug('debug message')
logger.info('info message')

标准输出:

info message

a.log文件中的内容:

2019-6-18 19:11:22 - root - DEBUG - debug message
2019-6-18 19:11:22 - root - INFO - info message

转载于:https://www.cnblogs.com/wuweixiong/p/11046286.html

micropython logging文档相关推荐

  1. 再见丑陋的 SwaggerUI,这款API文档生成神器界面更炫酷,逼格更高!

    欢迎关注方志朋的博客,回复"666"获面试宝典 一般在使用 Spring Boot 开发前后端分离项目的时候,都会用到 Swagger.Swagger 是一个规范和完整的框架,用于 ...

  2. Pentaho部署文档校验过程中遇到的一些问题和解决对策

    为什么80%的码农都做不了架构师?>>>    Pentaho部署文档校验过程中遇到的一些问题和解决对策 1.quartz.EmbeddedQuartzSystemListener发 ...

  3. Python工程的文档结构

    Python工程的文档结构,可以参考https://stackoverflow.com/questions/193161/what-is-the-best-project-structure-for- ...

  4. ORA-01578和ORA-26040--NOLOGGING操作引起的坏块-错误解释和解决方案(文档ID 1623284.1)...

    ORA-01578和ORA-26040--NOLOGGING操作引起的坏块-错误解释和解决方案(文档ID 1623284.1) (一)NOLOGGING操作引起的坏块(ORA-01578和ORA-26 ...

  5. ASP.NET CORE 1.0 MVC API 文档用 SWASHBUCKLE SWAGGER实现

    from:https://damienbod.com/2015/12/13/asp-net-5-mvc-6-api-documentation-using-swagger/ 代码生成工具: https ...

  6. discuz 文档说明

    Discuz  文档说明 基于7.0的标准程序,部分与插件无关的文件不作说明 文件颜色说明: 红色:程序核心文件,修改这类文件时千万要注意安全! 橙色:做插件几乎不会用到的文件,大概了解功能就可以了, ...

  7. 【FFmpeg】FFmpeg 帮助文档使用

    FFmpeg 系列文章目录 [FFmpeg]Windows 搭建 FFmpeg 命令行运行环境 [FFmpeg]FFmpeg 相关术语简介 [FFmpeg]FFmpeg 相关术语简介 二 文章目录 F ...

  8. 文档型数据库mongodb介绍2-副本集

    一. 副本集介绍 之前的文章介绍了 mongodb主从 mongodb提供了另外一种 基于副本集的集群 该方式 是一主一从的升级版  一主多从, 仍然是主节点负责写入 从节点定时同步主节点数据 使用该 ...

  9. gnokii 短信猫 中文安装使用文档

    gnokii 短信猫 中文安装使用文档 2010年11月19日 - admin 8月份做的一个东东,重新整理了一下发上来.当日后使用文档! 环境: centos 5.2,短信猫设备: wave 安装软 ...

  10. gnokii 中文安装使用文档

    gnokii 中文安装使用文档 2010年11月19日 - admin 8月份做的一个东东,重新整理了一下发上来.当日后使用文档! 环境: centos 5.2,设备: wave 安装软件地址: ht ...

最新文章

  1. Python学习笔记:Import详解2
  2. 「Jupyter」ubuntu下安装jupyterlab后jupyterlab:未找到命令
  3. 2018年一线互联网公司Java高级面试题总结
  4. Springboot 传递 List「Long」 IdList
  5. github快速通道
  6. 如何查看IIS的80端口被占用?
  7. php表格列宽拖拽,JavaScript_JQuery拖动表头边框线调整表格列宽效果代码,类似于桌面程序中的表格拖动 - phpStudy...
  8. ssh相关命令Linux,Linux SSH常用命令 [长期更新]...
  9. Solana 海湾流(Gulf Stream)海平面(Sealevel)区别
  10. python最新版安装图集_[python] plist图集拆分小图
  11. 银行即将关闭直接代扣通道,第三方支付有麻烦了
  12. 无卡时代存取款的N种姿势:刷脸、扫码、手机Pay
  13. 【没有刀剑,如何行走江湖】半晌私语(上)
  14. hadoop运行程序时报错java.net.ConnectException: java.net.ConnectException: 拒绝连接;
  15. java实验报告之模拟银行存取款业务
  16. java 类大写_记java实体类属性名为全部为大写踩的坑(基础)
  17. 超图对接伟景行osg数据使用说明
  18. 有利可图的NFT,NA公链(Nirvana Chain)NAC公链怎么面对高额Gas费的?
  19. android vitamio集成教程,集成Vitamio实现万能播放器(示例代码)
  20. How to customize the UI in IBM ITIM Solution

热门文章

  1. spark 算子使用类变量_SparkCore的常用算子
  2. Java之数组(上)
  3. 简述python文件操作_python 文件操作总结
  4. Java SecureRandom 简单生成随机正整数
  5. ElasticSearch+kibana安装
  6. 基于SSM的教学质量系统
  7. 计算机名汉字 oracle,修改计算机名对ORACLE的影像
  8. Web(4)servlet
  9. c语言课程建设与改革,C语言程序设计课程教学改革的研究与实践
  10. Hibernate.cfg.xml 整理