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
, 定义了一组format
ID, 没种都有自己的格式;handlers
, 定义了一组handler
的ID, 其中class
是必须的, 其它参数是用于构建相应的handler
类对象时使用到的参数; 这里的console
的类, 用了默认的stdout
来输出;loggers
, 定义真正使用的logger
ID和格式, 如这里的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 .....")