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

参考

posted @ 2019-03-03 18:29  Michael翔  阅读(432)  评论(0编辑  收藏  举报