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的第一步就是创建一个解析器对象,并告诉它将会有些什么参数.那么当你的程序运行时,该解析器就可以用于处理命令行参数. 解 ...
随机推荐
- Nodejs【单机】多进程模式集群
Nodejs[单机]多进程模式集群实例: 1.安装:npm install -s cluster 2.服务代码: var debug = require('debug'); var express = ...
- C# mongodb中内嵌文档数组条件查询
样例数据: { "_id" : "1064621564857", "cNo" : "1064621564857 ...
- 17. Letter Combinations of a Phone Number(bfs)
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that th ...
- 详解Linux下iptables中的DNAT与SNAT设置(转)
详解Linux下iptables中的DNAT与SNAT设置 这篇文章主要介绍了Linux下iptables中的DNAT与SNAT设置,是Linux网络配置中的基础知识,需要的朋友可以参考下 原文连 ...
- C# 队列(Queue)和 堆栈(Stack)
C# 队列(Queue)和 堆栈(Stack) C# 队列(Queue) 队列(Queue)代表了一个先进先出的对象集合.当您需要对各项进行先进先出的访问时,则使用队列.当您在列表中添加一项,称为入队 ...
- uvalive 3353 Optimal Bus Route Design
题意: 给出n个点,以及每个点到其他点的有向距离,要求设计线路使得每一个点都在一个环中,如果设计的线路拥有最小值,那么这个线路就是可选的.输出这个最小值或者说明最小线路不存在. 思路: 在DAG的最小 ...
- RSA 加密 解密 公钥 私钥 签名 加签 验签
http://blog.csdn.net/21aspnet/article/details/7249401# http://www.ruanyifeng.com/blog/2013/06/rsa_al ...
- HDU 1879 继续畅通工程(最小生成树)
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可).现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经 ...
- POJ 1018 Communication System (动态规划)
We have received an order from Pizoor Communications Inc. for a special communication system. The sy ...
- 第一周java测验感想
在正式开学的第一周,建民老师就给我们来了一个下马威.我本身的编程基础比较差,不知道怎么去想,怎么去一步步的去完成这么一个工程.所以我在星期四的下午十分的痛苦…因为不知道怎么搞嘛.尽管在暑假的时候看了 ...