简单用法
import logginglogging.warning("user [mufeng] attempted wrong password more than 3 times")logging.critical("server is down")
日志级别
数值越大,级别越高
CRITICAL = 50FATAL = CRITICALERROR = 40WARNING = 30WARN = WARNINGINFO = 20DEBUG = 10NOTSET = 0
level参数
参数值大于等于level才有效
import logginglogging.basicConfig(level=logging.INFO)logging.debug('i am debug')logging.info('i am info')logging.warning('i am warning')
日志文件
一般来说,日志会写到文件,因为写到内存有太多不确定性,如项目运行停止,机器断电或重启等故障
import logginglogging.basicConfig(filename='log.txt', level=logging.INFO)logging.debug('i am debug')logging.info('i am info')logging.warning('i am warning')
自定义日志格式
import logginglogging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')logging.warning('i am info')

除了加时间,还可以自定义一大堆格式,下表就是所有支持的格式
| %(name)s | Logger的名字 |
|---|---|
| %(levelno)s | 数字形式的日志级别 |
| %(levelname)s | 文本形式的日志级别 |
| %(pathname)s | 调用日志输出函数的模块的完整路径名,可能没有 |
| %(filename)s | 调用日志输出函数的模块的文件名 |
| %(module)s | 调用日志输出函数的模块名 |
| %(funcName)s | 调用日志输出函数的函数名 |
| %(lineno)d | 调用日志输出函数的语句所在的代码行 |
| %(created)f | 当前时间,用UNIX标准的表示时间的浮 点数表示 |
| %(relativeCreated)d | 输出日志信息时的,自Logger创建以 来的毫秒数 |
| %(asctime)s | 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 |
| %(thread)d | 线程ID。可能没有 |
| %(threadName)s | 线程名。可能没有 |
| %(process)d | 进程ID。可能没有 |
| %(message)s | 用户输出的消息 |
同时输出日志到屏幕和文件
import logging# create loggerlogger = logging.getLogger('TEST-LOG')logger.setLevel(logging.DEBUG)# create console handler and set level to debugch = logging.StreamHandler()ch.setLevel(logging.DEBUG)# create file handler and set level to warningfh = logging.FileHandler("access.log")fh.setLevel(logging.WARNING)# create formatterformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# add formatter to ch and fhch.setFormatter(formatter)fh.setFormatter(formatter)# add ch and fh to loggerlogger.addHandler(ch)logger.addHandler(fh)# 'application' codelogger.debug('debug message')logger.info('info message')logger.warning('warn message')logger.error('error message')logger.critical('critical message')
