博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python logging 模块学习
阅读量:5772 次
发布时间:2019-06-18

本文共 5084 字,大约阅读时间需要 16 分钟。

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 function.
Creating a dictionary of configuration information and passing it to the function.
For the reference documentation on the last two options, see . The following example configures a very simple logger, a console handler, and a simple formatter using Python code:

import logging# create loggerlogger = logging.getLogger('simple_example')logger.setLevel(logging.DEBUG)# create console handler and set level to debugch = logging.StreamHandler()ch.setLevel(logging.DEBUG)# create formatterformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# add formatter to chch.setFormatter(formatter)# add ch to loggerlogger.addHandler(ch)# 'application' codelogger.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 message2018-05-28 19:23:50,651 - simple_example - INFO - info message2018-05-28 19:23:50,651 - simple_example - WARNING - warn message2018-05-28 19:23:50,651 - simple_example - ERROR - error message2018-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 loggingimport logging.configlogging.config.fileConfig('logging.conf')# create loggerlogger = logging.getLogger('simpleExample')# 'application' codelogger.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=DEBUGhandlers=consoleHandler[logger_simpleExample]level=DEBUGhandlers=consoleHandlerqualname=simpleExamplepropagate=0[handler_consoleHandler]class=StreamHandlerlevel=DEBUGformatter=simpleFormatterargs=(sys.stdout,)[formatter_simpleFormatter]format=%(asctime)s - %(name)s - %(levelname)s - %(message)sdatefmt=

The output is nearly identical to that of the non-config-file-based example:

$ python simple_logging_config.py2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message2005-03-19 15:38:55,979 - simpleExample - INFO - info message2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message2005-03-19 15:38:56,055 - simpleExample - ERROR - error message2005-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 osimport loggingimport sysdef 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

参考

转载于:https://www.cnblogs.com/michael-xiang/p/10466800.html

你可能感兴趣的文章
Linux 常用命令
查看>>
NodeJS 工程师必备的 8 个工具
查看>>
CSS盒模型
查看>>
ng2路由延时加载模块
查看>>
使用GitHub的十个最佳实践
查看>>
全面了解大数据“三驾马车”的开源实现
查看>>
脱离“体验”和“安全”谈盈利的游戏运营 都是耍流氓
查看>>
慎用!BLEU评价NLP文本输出质量存在严重问题
查看>>
基于干净语言和好奇心的敏捷指导
查看>>
Node.js 2017企业用户调查结果发布
查看>>
“软”苹果水逆的一周:杂志服务崩溃,新机型遭泄露,芯片首架离职
查看>>
JAVA的优势就是劣势啊!
查看>>
ELK实战之logstash部署及基本语法
查看>>
帧中继环境下ospf的使用(点到点模式)
查看>>
BeanShell变量和方法的作用域
查看>>
LINUX下防恶意扫描软件PortSentry
查看>>
由数据库对sql的执行说JDBC的Statement和PreparedStatement
查看>>
springmvc+swagger2
查看>>
软件评测-信息安全-应用安全-资源控制-用户登录限制(上)
查看>>
cacti集成
查看>>