Python logging 模块学习
logging example
| Level | When it’s used | Numeric value |
|---|---|---|
| DEBUG | Detailed information, typically of interest only when diagnosing problems. | 10 |
| INFO | Confirmation that things are working as expected. | 20 |
| WARNING | An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. | 30 |
| ERROR | Due to a more serious problem, the software has not been able to perform some function. | 40 |
| CRITICAL | A serious error, indicating that the program itself may be unable to continue running. | 50 |
The default level is WARNING, which means that only events of this level and above will be tracked, unless the logging package is configured to do otherwise.
logging to a file
if you run the above script several times, the messages from successive runs are appended to the file example.log. If you want each run to start afresh, not remembering the messages from earlier runs, you can specify the filemode argument, by changing the call in the above example to:
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
Configuring Logging
Programmers can configure logging in three ways:
Creating loggers, handlers, and formatters explicitly using Python code that calls the configuration methods listed above.
Creating a logging config file and reading it using the fileConfig() function.
Creating a dictionary of configuration information and passing it to the dictConfig() function.
For the reference documentation on the last two options, see Configuration functions. The following example configures a very simple logger, a console handler, and a simple formatter using Python code:
import logging
# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
output:
2018-05-28 19:23:50,651 - simple_example - DEBUG - debug message
2018-05-28 19:23:50,651 - simple_example - INFO - info message
2018-05-28 19:23:50,651 - simple_example - WARNING - warn message
2018-05-28 19:23:50,651 - simple_example - ERROR - error message
2018-05-28 19:23:50,651 - simple_example - CRITICAL - critical message
The following Python module creates a logger, handler, and formatter nearly identical to those in the example listed above, with the only difference being the names of the objects:
import logging
import logging.config
logging.config.fileConfig('logging.conf')
# create logger
logger = logging.getLogger('simpleExample')
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
Here is the logging.conf file:
[loggers]
keys=root,simpleExample
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
The output is nearly identical to that of the non-config-file-based example:
$ python simple_logging_config.py
2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
Example
例1
logging模块最简单的用法,是直接使用basicConfig方法来对logging进行配置
import logging
# 设置默认的level为DEBUG
# 设置log的格式
logging.basicConfig(
level=logging.DEBUG,
format="[%(asctime)s] %(name)s:%(levelname)s: %(message)s"
)
例2
import os
import logging
import sys
def test_log_level():
# set default logging configuration
logger = logging.getLogger() # initialize logging class
logger.setLevel(logging.DEBUG) # default log level
format = logging.Formatter("%(asctime)s - %(message)s") # output format
sh = logging.StreamHandler() # output to standard output
sh.setFormatter(format)
logger.addHandler(sh)
# use logging to generate log ouput
logger.info("this is info")
logger.debug("this is debug")
logger.warning("this is warning")
logging.error("this is error")
logger.critical("this is critical")
test_log_level()
[Running] python "d:\OneDrive\02-coding\test\test-logging.py"
[2018-03-11 20:08:37,533] root:DEBUG: hello
[2018-03-11 20:08:37,533] root:INFO: world111
[2018-03-11 20:08:37,533] root:WARNING: world
[2018-03-11 20:08:37,534] root:ERROR: world
[2018-03-11 20:08:37,534] root:CRITICAL: world
参考
Python logging 模块学习的更多相关文章
- python logging模块学习(转)
前言 日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法.本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表. 另外,Python的H ...
- python logging模块使用流程
#!/usr/local/bin/python # -*- coding:utf-8 -*- import logging logging.debug('debug message') logging ...
- (转)python logging模块
python logging模块 原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python ...
- python logging模块使用教程
简单使用 #!/usr/local/bin/python # -*- coding:utf-8 -*- import logging logging.debug('debug message') lo ...
- python logging模块【转载】
转自:https://www.cnblogs.com/dahu-daqing/p/7040764.html 参考:老顽童log模块,讲的很细致,基本上拿到手就可以直接用了,很赞 1 logging模块 ...
- python logging模块可能会令人困惑的地方
python logging模块主要是python提供的通用日志系统,使用的方法其实挺简单的,这块就不多介绍.下面主要会讲到在使用python logging模块的时候,涉及到多个python文件的调 ...
- python logging模块使用
近来再弄一个小项目,已经到收尾阶段了.希望加入写log机制来增加程序出错后的判断分析.尝试使用了python logging模块. #-*- coding:utf-8 -*- import loggi ...
- 读懂掌握 Python logging 模块源码 (附带一些 example)
搜了一下自己的 Blog 一直缺乏一篇 Python logging 模块的深度使用的文章.其实这个模块非常常用,也有非常多的滥用.所以看看源码来详细记录一篇属于 logging 模块的文章. 整个 ...
- python - argparse 模块学习
python - argparse 模块学习 设置一个解析器 使用argparse的第一步就是创建一个解析器对象,并告诉它将会有些什么参数.那么当你的程序运行时,该解析器就可以用于处理命令行参数. 解 ...
随机推荐
- EL语言表达式 (一)【语法和特点】
一.基本语法规则: EL表达式语言以“${”开头,以"}"结尾的程序段,具体格式如下: ${expression} 其中expression:表示要指定输出的内容和字符串以及EL运 ...
- WIN32窗口类风格和窗口风格(备查询)
一.WNDCLASS typedef struct { UINT cbSize //这个结构体的长度,一般用sizeof(WNDCLASSEX)设置 UINT style //窗口式样 WNDPROC ...
- 谷歌Cookies无法写入
写Cookies页面加这个ok: Response.AddHeader("P3P", "CP=CAO PSA OUR");
- Sitecore CMS中如何命名项目名称
如何在Sitecore CMS中命名项目,以及配置命名限制,“显示名称”是什么以及如何使用它. 任何其他名称的项目 当创建Sitecore的项目,内容编辑器要求制作者为新建项目提供名称.输入的名称将其 ...
- 【2017-2-19】C#数据类型,数据转换,变量,常量,转义符
数据类型 一.基本数据类型 1.值类型(不可以为null) ⑴整型(可以为负数) byle,int,short,long(从小到大排列) 常用整型 int a=值(小于10位数) long b=值(1 ...
- 使用SpringAOP获取一次请求流经方法的调用次数和调用耗时
引语 作为工程师,不能仅仅满足于实现了现有的功能逻辑,还必须深入认识系统.一次请求,流经了哪些方法,执行了多少次DB操作,访问了多少次文件操作,调用多少次API操作,总共有多少次IO操作,多少CPU操 ...
- flask用宏渲染表单模板时,表单提交后,如果form.validate_on_submit()返回的是false的可能原因
flask用宏渲染表单模板时,表单提交后,提交的内容符合DataRequired()校验, 但是form.validate_on_submit()返回的是False, 原因可能是表单模板中的<f ...
- MySQL存储引擎MyISAM与InnoDB区别总结整理
在MySQL的 可重复读隔离级别 中,是解决了幻读的读问题的. 1. MySQL默认存储引擎的变迁 在MySQL 5.5之前的版本中,默认的搜索引擎是MyISAM,从MySQL 5.5之后的版本中,默 ...
- Linux基础命令---ipcalc计算IP
ipcalc ipcalc提供了一种计算主机IP信息的简单方法.各种选项指定ipcalc应该在标准输出上显示什么信息.可以指定多个选项.必须始终指定要操作的IP地址.大多数操作还需要一个 ...
- C#中对Web.Config、App.Config字符串加密与解密的方法
我们平常的项目里面的配置文件通常都是明文形式的存在,现在就是为了项目安全性增强,同时又显得高逼格点, 我们可以采用加密的方式,而我们C#很强大,因为他内置的一些指令方式,很方便而且使用起来还不用解密, ...