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 模块学习的更多相关文章

  1. python logging模块学习(转)

    前言 日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法.本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表. 另外,Python的H ...

  2. python logging模块使用流程

    #!/usr/local/bin/python # -*- coding:utf-8 -*- import logging logging.debug('debug message') logging ...

  3. (转)python logging模块

    python logging模块 原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python ...

  4. python logging模块使用教程

    简单使用 #!/usr/local/bin/python # -*- coding:utf-8 -*- import logging logging.debug('debug message') lo ...

  5. python logging模块【转载】

    转自:https://www.cnblogs.com/dahu-daqing/p/7040764.html 参考:老顽童log模块,讲的很细致,基本上拿到手就可以直接用了,很赞 1 logging模块 ...

  6. python logging模块可能会令人困惑的地方

    python logging模块主要是python提供的通用日志系统,使用的方法其实挺简单的,这块就不多介绍.下面主要会讲到在使用python logging模块的时候,涉及到多个python文件的调 ...

  7. python logging模块使用

    近来再弄一个小项目,已经到收尾阶段了.希望加入写log机制来增加程序出错后的判断分析.尝试使用了python logging模块. #-*- coding:utf-8 -*- import loggi ...

  8. 读懂掌握 Python logging 模块源码 (附带一些 example)

    搜了一下自己的 Blog 一直缺乏一篇 Python logging 模块的深度使用的文章.其实这个模块非常常用,也有非常多的滥用.所以看看源码来详细记录一篇属于 logging 模块的文章. 整个 ...

  9. python - argparse 模块学习

    python - argparse 模块学习 设置一个解析器 使用argparse的第一步就是创建一个解析器对象,并告诉它将会有些什么参数.那么当你的程序运行时,该解析器就可以用于处理命令行参数. 解 ...

随机推荐

  1. c++将lambda作为callback函数

    想用c++发送http_post请求,用到了libcurl. 想将其包装一下,因为默认http的响应结果是打印到stdout的,如果想将响应结果另外处理,需要自己定义一个callback函数. 考虑到 ...

  2. shell作业控制(后台前台命令)

    ctrl+z暂停命令(任务) fg调回命令    |          fg +id号 bg放在后台持续执行 vmstat 1 &  在后面加上‘&’ 即相当于bg jobs列出当前的 ...

  3. MyEclipse10中文乱码

    1 进入window->preferences general->content types,可以设置Text对应的default encoding值为UTF-8或为空,然后点击updat ...

  4. DataSet 读取xml 报错有非法字符

    private void Bind() { string strLogPath = ConfigurationSettings.AppSettings["LOG_PATH"].To ...

  5. 使用淘宝npm镜像

    我们都知道淘宝大量采用了Nodej技术,所以它的镜像还是值得肯定的!更多相关可查看:淘宝NPM镜像 npm的官方镜像在国内访问是比较慢的,所以替代方法是使用淘宝npm镜像! 淘宝 NPM 镜像是一个完 ...

  6. Xfire基础

    XFire 是与Axis 2并列的新一代Web Service框架,通过提供简单的API支持Web Service各项标准协议,能够快速地开发Web Service应用.和其他Web服务引擎相比,XF ...

  7. 输入一串字符,检查是否可以组成friend

    """输入一串字符,检查是否可以组成friend""" from collections import Counter def foo(nu ...

  8. 20165316 预备作业3 Linux安装及学习

    Linux安装 我下载的是VirtualBox 5.2.6和Ubuntu 17.10.1,感觉这两个版本的兼容性不是太好,因为我在Oracle的官网社区中看到不少新版本的问题没有得到解决,而老版本(V ...

  9. tft屏图像显示也成功完成

    2010-04-30 14:18:00 tft屏图像显示也成功完成. 其实有了刷屏的经验,图像显示就很简单. void address_set(uint x1,uint y1,uint x2,uint ...

  10. RBAC

    什么是rbac? -- 基于角色的权限控制  Role-Based Access Control 一个url就代表一个权限 // url分配给角色,角色分配给用户 -- 6个model,4张表 菜单表 ...