内建模块--logging

日志模块

级别:默认为warning级别。(高到低:critical、error、warning、info、debug、notset)所以,只打印warning及以上的警告

线程安全: 


例子:

logging.basicConfig(level=logging.DEBUG,

                   format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s ',

                   datefmt='%a,%d %b %Y %H:%M:%S',

                   filename='/tmp/test/test.log',

                   filemode='w'

                   )

format中参数:

   # %(asctime)s 为日志记录时间与datefmt格式对应。

   # %(filename)s 为记录的日志名称

   # %(lineno)s 为程序中触发的行号

   # %(levelname)s 为级别名称

   # %(message)s 为日志内容主题

   # %(levelno)d 为以数字形式记录级别

   # %(name)s 为logger的名字

   # %(levelname)s 为以文本形式记录日志级别

   # %(pathname)s 为调用日志输出函数的模块的完整路径名。

   # %(module)s 为调用日志输出函数的模块名

   # %(funcName)s 为调用日志输出函数的函数名

   # %(created)s 为当前时间,以浮点数表示。

   # %(thread)d 为线程ID

   # %(threadName)s 为线程名称

   # %(process)d 为进程ID

# filemode:追加‘a’,覆盖写‘w’

# filename:如果定义路径则表示日志保存的文件路径。如果没有filename则默认屏幕打印

# stream:

logging.debug('debug msg')

logging.info('info msg')

logging.warning('warning msg')

logging.error('error msg')

logging.critical('critical msg')


日志记录与屏幕打印同时输出

import logging

logger = logging.getLogger()

# 创建一个handler(文件输出流对象),用于写入日志文件

fh = logging.FileHandler('test.log')

# 创建一个handler(屏幕输出流对象),用于输出到控制台

ch = logging.StreamHandler()

# 创建格式对象

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# fh对象设置为formatter格式

fh.setFormatter(formatter)

# ch对象设置为formatter格式

ch.setFormatter(formatter)

# 增加fh,ch对象到logger对象中

logger.addHandler(fh)

logger.addHandler(ch)

# 设置logger显示级别

logger.setLevel(logging.Debug)

logger.debug('debug msg')

logger.info('info msg')

logger.warning('warning msg')

logger.error('error msg')

logger.critical('critical msg')

你可能感兴趣的:(内建模块--logging)