7、模块之三 logging模块

1、logging模块

# python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为
# debug(), info(), warning(), error() and critical() 5个级别
# Level            When it’s used
# DEBUG            Detailed information, typically of interest only when diagnosing problems.
# INFO             Confirmation that things are working as expected.
# 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.
# ERROR            Due to a more serious problem, the software has not been able to perform some function.
# CRITICAL         A serious error, indicating that the program itself may be unable to continue running.

不同的日志级别对应不同的数值,具体如下:
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10


格式化:

logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
%(name)s            Name of the logger (logging channel)
%(levelno)s         Numeric logging level for the message (DEBUG, INFO,
                    WARNING, ERROR, CRITICAL)
%(levelname)s       Text logging level for the message ("DEBUG", "INFO",
                    "WARNING", "ERROR", "CRITICAL")
%(pathname)s        Full pathname of the source file where the logging
                    call was issued (if available)
%(filename)s        Filename portion of pathname
%(module)s          Module (name portion of filename)
%(lineno)d          Source line number where the logging call was issued
                    (if available)
%(funcName)s        Function name
%(created)f         Time when the LogRecord was created (time.time()
                    return value)
%(asctime)s         Textual time when the LogRecord was created
%(msecs)d           Millisecond portion of the creation time
%(relativeCreated)d Time in milliseconds when the LogRecord was created,
                    relative to the time the logging module was loaded
                    (typically at application startup time)
%(thread)d          Thread ID (if available)
%(threadName)s      Thread name (if available)
%(process)d         Process ID (if available)
%(message)s         The result of record.getMessage(), computed just as
                    the record is emitted

打印日志到屏幕:

##日志打印到屏幕
logging.warning("user [alex] attempted wrong password more than 3 times")
logging.critical("server is down")

日志输出到文件:

logging.basicConfig(filename='python.log',level=logging.INFO,format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')

 

屏幕日志双向输出:

#如果需要日志和屏幕同时输出的话,需要下面的操作
# The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.

# Loggers expose the interface that application code directly uses.
# Handlers send the log records (created by loggers) to the appropriate destination.
# Filters provide a finer grained facility for determining which log records to output.
# Formatters specify the layout of log records in the final output.
# 1、创建一个log对象
logger=logging.getLogger('test_log')
logger.setLevel(logging.DEBUG)

# 2、创建console handler 并设置等级
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)

fh = logging.FileHandler()
fh.setLevel(logging.DEBUG)

# 3、创建日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)

# 4、将日志实例添加到handler
logger.addHandler(ch)
logger.addHandler(fh)

# 5、打印日志测试
import logging


#create logger
logger = logging.getLogger('TEST-LOG')
logger.setLevel(logging.DEBUG)


# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)

# create file handler and set level to warning
fh = logging.FileHandler("python.log")
fh.setLevel(logging.WARNING)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# add formatter to ch and fh
ch.setFormatter(formatter)
fh.setFormatter(formatter)

# add ch and fh to logger
logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

  

posted @ 2016-06-11 15:03  马业胜  阅读(193)  评论(0编辑  收藏  举报