logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等;相比于print:
Logger从来不直接实例化,经常通过logging模块级方法(Module-Level Function)logging.getLogger(name)来获得,其中如果name不给定就用root。名字是以点号分割的命名方式命名的(a.b.c)。如果对同一个名字多次调用logging.getLogger()方法会返回同一个logger对象。这种命名方式里面,后面的logger是前面logger的子logger,自动继承父logger的log信息,正因为此,没有必要把一个应用的所有logger都配置一遍,只要把顶层的logger配置好了,然后子logger根据需要继承就行了。
logging.Logger对象扮演了三重角色:
啥也不说,先导入logging模块。
import logging
配置longging的基本设置,然后在控制台输出。
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('logger')
logger1 = logging.getLogger('logger1')
logger.info('start print log')
logger.debug('debug something')
logger.warning('something may be wrong')
logger.info('finish')
logger1.info('start print log')
logger1.debug('debug something')
logger1.warning('something may be wrong')
logger1.info('finish')
输出为
2020-05-26 11:19:49,948 - logger - INFO - start print log
2020-05-26 11:19:49,948 - logger - WARNING - something may be wrong
2020-05-26 11:19:49,948 - logger - INFO - finish
2020-05-26 11:19:49,949 - logger1 - INFO - start print log
2020-05-26 11:19:49,949 - logger1 - WARNING - something may be wrong
2020-05-26 11:19:49,949 - logger1 - INFO - finish
上面定义了两个logger,并将logger的消息级别设置为info,logger还有很多级别(后续会仔细讲):
通过赋予logger或者handler不同的级别,开发者就可以只输出错误信息到特定的记录文件,或者在调试时只记录调试信息。
将logger的级别改为DEBUG,再观察一下输出结果。
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('logger')
logger1 = logging.getLogger('logger1')
logger.info('start print log')
logger.debug('debug something')
logger.warning('something may be wrong')
logger.info('finish')
logger1.info('start print log')
logger1.debug('debug something')
logger1.warning('something may be wrong')
logger1.info('finish')
输出为:
2020-05-26 11:26:44,179 - logger - INFO - start print log
2020-05-26 11:26:44,179 - logger - DEBUG - debug something
2020-05-26 11:26:44,179 - logger - WARNING - something may be wrong
2020-05-26 11:26:44,179 - logger - INFO - finish
2020-05-26 11:26:44,179 - logger1 - INFO - start print log
2020-05-26 11:26:44,179 - logger1 - DEBUG - debug something
2020-05-26 11:26:44,179 - logger1 - WARNING - something may be wrong
2020-05-26 11:26:44,179 - logger1 - INFO - finish
可以看出把debug的信息打印出来了。
logging.basicConfig()函数的各种参数
Formatter定义了logger记录的输出格式,定义了最终log信息的内容格式,可以直接实例化Formatter类,信息个税字符串用%(
风格的字符串做替换。
属性名称 | 格式 | 说明 |
---|---|---|
name | %(name)s | 日志的名称 |
asctime | %(asctime)s | 可读时间,默认格式‘2020-02-02 20:20:20,200’,逗号之后是毫秒 |
filename | %(filename)s | 文件名,pathname的一部分 |
pathname | %(pathname)s | 文件的全路径名称 |
funcName | %(funcName)s | 调用日志对应的方法名 |
levelname | %(levelname)s | 日志的等级 |
levelno | %(levelno)s | 数字化的日志等级 |
lineno | %(lineno)d | 被记录日志在源码中的行数 |
module | %(module)s | 模块名 |
msecs | %(msecs)d | 时间中的毫秒部分 |
process | %(process)d | 进程的ID |
processName | %(processName)s | 进程的名称 |
thread | %(thread)d | 线程的ID |
threadName | %(threadName)s | 线程的名称 |
relativeCreated | %(relativeCreated)d | 日志被创建的相对时间,以毫秒为单位 |
设置logging,创建一个FileHandler,并对输出消息的格式进行设置,将其添加到logger,然后将日志写入到指定的文件中。
import logging
logger = logging.getLogger('logger')
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
输出:
2020-05-26 12:13:52,769 - logger - INFO - Start print log
2020-05-26 12:13:52,769 - logger - WARNING - Something maybe fail.
2020-05-26 12:13:52,771 - logger - INFO - Finish
在logger中添加StreamHandler,可以将日志输出到控制台中。
logger = logging.getLogger('logger')
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logger.addHandler(handler)
logger.addHandler(console)
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
文件中输出的是:
2020-05-26 12:49:18,404 - logger - INFO - Start print log
2020-05-26 12:49:18,404 - logger - WARNING - Something maybe fail.
2020-05-26 12:49:18,437 - logger - INFO - Finish
控制台输出的是:
Start print log
Something maybe fail.
Finish
可以看出,控制台的输出没有格式,那是应为控制台只设置了level, 并没有设置格式。
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)
控制台就输出了格式:
2020-05-26 12:52:36,847 - logger - INFO - Start print log
2020-05-26 12:52:36,847 - logger - WARNING - Something maybe fail.
2020-05-26 12:52:36,848 - logger - INFO - Finish
logging有一个日志处理的主对象,其他处理方式都是通过addHandler添加进去,logging中包含的handler主要有如下几种:
使用RotatingFileHandler,可以实现日志回滚
from logging.handlers import RotatingFileHandler
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
#定义一个RotatingFileHandler,最多备份3个日志文件,每个日志文件最大1K
rHandler = RotatingFileHandler("log.txt", maxBytes = 1*1024, backupCount = 3)
rHandler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
rHandler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger.addHandler(rHandler)
logger.addHandler(console)
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
logger.info("Finish")
会把原来log.txt
变成log.txt.1
,再新建一个log.txt
存储目前的信息。
可以设置不同的日志等级,用于控制日志的输出,日志等级:
定义处理log的最低等级,内建的级别为:DEBUG,INFO,WARNING,ERROR,CRITICAL,也可以输入对应的数值
级别 | 数值 |
---|---|
CRITICAL | 50 |
ERROR | 40 |
WARNING | 30 |
INFO | 20 |
DEBUG | 10 |
NOTSET | 0 |
Python中的traceback模块被用于跟踪异常返回信息,可以在logging中记录下traceback
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
logger.addHandler(handler)
logger.addHandler(console)
logger.info("Start print log")
logger.debug("Do something")
logger.warning("Something maybe fail.")
try:
open("sklearn.txt","rb")
except (SystemExit,KeyboardInterrupt):
raise
except Exception:
logger.error("Faild to open sklearn.txt from logger.error",exc_info = True)
logger.info("Finish")
文件输出:
2020-05-26 13:08:21,977 - __main__ - INFO - Start print log
2020-05-26 13:08:21,977 - __main__ - WARNING - Something maybe fail.
2020-05-26 13:08:21,977 - __main__ - ERROR - Faild to open sklearn.txt from logger.error
Traceback (most recent call last):
File "E:/pycharm/test/log.py", line 90, in
open("sklearn.txt", "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'sklearn.txt'
2020-05-26 13:08:22,017 - __main__ - INFO - Finish
也可以使用logger.exception(msg,_args),它等价于logger.error(msg,exc_info = True,_args),
将
logger.error("Faild to open sklearn.txt from logger.error",exc_info = True)
替换为,
logger.exception("Failed to open sklearn.txt from logger.exception")
主模块mainModule.py
import logging
import subModule
logger = logging.getLogger("mainModule")
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger.addHandler(handler)
logger.addHandler(console)
logger.info("creating an instance of subModule.subModuleClass")
a = subModule.SubModuleClass()
logger.info("calling subModule.subModuleClass.doSomething")
a.doSomething()
logger.info("done with subModule.subModuleClass.doSomething")
logger.info("calling subModule.some_function")
subModule.som_function()
logger.info("done with subModule.some_function")
子模块subModule.py
import logging
module_logger = logging.getLogger("mainModule.sub")
class SubModuleClass(object):
def __init__(self):
self.logger = logging.getLogger("mainModule.sub.module")
self.logger.info("creating an instance in SubModuleClass")
def doSomething(self):
self.logger.info("do something in SubModule")
a = []
a.append(1)
self.logger.debug("list a = " + str(a))
self.logger.info("finish something in SubModuleClass")
def som_function():
module_logger.info("call function some_function")
首先在主模块定义了logger’mainModule’,并对它进行了配置,就可以在解释器进程里面的其他地方通过getLogger(‘mainModule’)得到的对象都是一样的,不需要重新配置,可以直接使用。定义的该logger的子logger,都可以共享父logger的定义和配置,所谓的父子logger是通过命名来识别,任意以’mainModule’开头的logger都是它的子logger,例如’mainModule.sub’。
实际开发一个application,首先可以通过logging配置文件编写好这个application所对应的配置,可以生成一个根logger,如’PythonAPP’,然后在主函数中通过fileConfig加载logging配置,接着在application的其他地方、不同的模块中,可以使用根logger的子logger,如’PythonAPP.Core’,'PythonAPP.Web’来进行log,而不需要反复的定义和配置各个模块的logger。
尽管可以在Python代码中配置logging,但是这样并不够灵活,最好的方法是使用一个配置文件来配置。在Python 2.7及以后的版本中,可以从字典中加载logging配置,也就意味着可以通过JSON或者YAML文件加载日志的配置。
JSON配置文件
{
"version":1,
"disable_existing_loggers":false,
"formatters":{
"simple":{
"format":"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
}
},
"handlers":{
"console":{
"class":"logging.StreamHandler",
"level":"DEBUG",
"formatter":"simple",
"stream":"ext://sys.stdout"
},
"info_file_handler":{
"class":"logging.handlers.RotatingFileHandler",
"level":"INFO",
"formatter":"simple",
"filename":"info.log",
"maxBytes":"10485760",
"backupCount":20,
"encoding":"utf8"
},
"error_file_handler":{
"class":"logging.handlers.RotatingFileHandler",
"level":"ERROR",
"formatter":"simple",
"filename":"errors.log",
"maxBytes":10485760,
"backupCount":20,
"encoding":"utf8"
}
},
"loggers":{
"my_module":{
"level":"ERROR",
"handlers":["info_file_handler"],
"propagate":"no"
}
},
"root":{
"level":"INFO",
"handlers":["console","info_file_handler","error_file_handler"]
}
}
通过JSON加载配置文件,然后通过logging.dictConfig配置logging
import json
import logging.config
import os
def setup_logging(default_path = "logging.json",default_level = logging.INFO,env_key = "LOG_CFG"):
path = default_path
value = os.getenv(env_key,None)
if value:
path = value
if os.path.exists(path):
with open(path,"r") as f:
config = json.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level = default_level)
def func():
logging.info("start func")
logging.info("exec func")
logging.info("end func")
if __name__ == "__main__":
setup_logging(default_path = "logging.json")
func()
通过YAML文件进行配置,比JSON看起来更加简介明了
version: 1
disable_existing_loggers: False
formatters:
simple:
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
info_file_handler:
class: logging.handlers.RotatingFileHandler
level: INFO
formatter: simple
filename: info.log
maxBytes: 10485760
backupCount: 20
encoding: utf8
error_file_handler:
class: logging.handlers.RotatingFileHandler
level: ERROR
formatter: simple
filename: errors.log
maxBytes: 10485760
backupCount: 20
encoding: utf8
loggers:
my_module:
level: ERROR
handlers: [info_file_handler]
propagate: no
root:
level: INFO
handlers: [console,info_file_handler,error_file_handler]
通过YAML加载配置文件,然后通过logging.dictConfig配置logging
import yaml
import logging.config
import os
def setup_logging(default_path = "logging.yaml",default_level = logging.INFO,env_key = "LOG_CFG"):
path = default_path
value = os.getenv(env_key,None)
if value:
path = value
if os.path.exists(path):
with open(path,"r") as f:
config = yaml.load(f)
logging.config.dictConfig(config)
else:
logging.basicConfig(level = default_level)
def func():
logging.info("start func")
logging.info("exec func")
logging.info("end func")
if __name__ == "__main__":
setup_logging(default_path = "logging.yaml")
func()