logging.basicConfig(filename, filemode, format)
其中format格式:
%(levelno)s:打印日志级别的数值
%(levelname)s:打印日志级别的名称
%(pathname)s:打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s:打印当前执行程序名
%(funcName)s:打印日志的当前函数
%(lineno)d:打印日志的当前行号
%(asctime)s:打印日志的时间
%(thread)d:打印线程ID
%(threadName)s:打印线程名称
%(process)d:打印进程ID
%(message)s:打印日志信息
yaml配置
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
info_file_handler:
class: logging.handlers.RotatingFileHandler
level: INFO
formatter: simple
filename: test.log
maxBytes: 1024
backupCount: 5
encoding: "utf8"
loggers:
fileLogger:
level: DEBUG
handlers: [console, info_file_handler]
propagate: no
roots:
level: DEBUG
handlers: [console]
propagate: true
- 上面的配置中,
disable_existing_loggers默认为true, 说明当前的配置会覆盖调以前的配置; formatters, 定义了一组formatID, 没种都有自己的格式;handlers, 定义了一组handler的ID, 其中class是必须的, 其它参数是用于构建相应的handler类对象时使用到的参数; 这里的console的类, 用了默认的stdout来输出;loggers, 定义真正使用的loggerID和格式, 如这里的fileLogger, 就是在代码中通过logger = logging.getLogger("fileLogger")来获得该类型的logger;root, 默认情况下的输出配置, 当logging.getLogger("type")里面的type没有时, 就是用的这个默认的root, 如logging.getLogger(__name__)或logging.getLogger(); 没有这个, 则这些将不会有输出;
# coding:utf-8
import yaml
import logging.config
import os
import my_module
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:
logging.config.dictConfig(yaml.load(f))
else:
logging.basicConfig(level = default_level)
setup_logging(default_path="logging.yaml")
logger = logging.getLogger("fileLogger")
logger.info("aaaaaaaaaaa")
logger.debug("debug debug .....")
本文介绍了一种使用Python的logging模块进行日志记录的方法,并详细解释了如何通过YAML文件来配置日志级别、格式及输出方式。文章还提供了一个实际的例子,展示了如何设置不同级别的日志输出以及文件轮转。
2069





