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. PHP乘法表

    <?php //一行*$a="*";echo ("$a <br>"); //一行50个*for($j=1;$j<=50;$j++){ e ...

  2. 记在Archlinux中安装python的pymssql模块过程中遇到的问题

    为什么要安装这个模块?因为要连接SQLServer数据库. 看到可以使用pyodbc这个模块进行连接,但对odbc不熟悉,所以选用了看起来更简单的 pymssql. 直接执行: pip install ...

  3. 5.JVM的内存区域划分

    一.JVM介绍 1. 什么是JVM? JVM是Java Virtual Machine(Java虚拟机)的缩写,JVM是一种用于计算设备的规范,它是一个虚构出来的计算机,是通过在实际的计算机上仿真模拟 ...

  4. vs2013未找到与约束匹配的导出

    解决方法: 1.关闭VS: 2.去C:/Users/<your users name>/AppData/Local/Microsoft/VisualStudio/12.0/Componen ...

  5. Mini-Batch 、Momentum、Adam算法的实现

    Mini-Batch 1. 把训练集打乱,但是X和Y依旧是一一对应的 import numpy as np a = np.random.randn(3,3) print(a) b = list(np. ...

  6. super和this关键字

    super关键字: this关键字: 栈内存和堆内存和方法区内存分析: 其中,new出来的即对象都在堆内存区: main方法先进栈: 方法区中 [[ super_class ]]是编译器生成,代码表现 ...

  7. C# 选项卡控件

    选项卡控件,它提供一系列操作按钮,单击不同的按钮可以在各个页面之间进行切换. 在Windows Form应用程序中,选项卡控件即“TebPage”控件,它公开“TebPage”属性,表示一个由“Tab ...

  8. Django 自定义

    from django.db import models class MyCharfield(models.Field): def __init__(self,max_length,*args,**k ...

  9. build docker deivcemapper

    1.创建一个虚拟快设备 dd if=/dev/zero of=4G.img bs=1M count=4096 2.创建loop device 可以先用losetup -f 查看空闲的loop设备 lo ...

  10. error C2504: “XXXXXXX”: 未定义基类

    今天犯到了一个低级错误,记下来加深印象. 造成这一现象主要的原因是头文件相互包含,文件构成一个环形结构,从而编译时循环包含出错 如: AA.h中包含BB.h BB.h中包含CC.h CC.h中包含AA ...