这篇文章其实早在一个月以前就写好了。奈何,加班猛如虎,真的怕了。直至今天才幸运地有了个双休,赶忙排版一下文章发布了。如下为正文。 在初学 Python 的时候,咱们使用python
print("hello world")
复制代码
输出了咱们的第一行代码。在以后的日子里,便一直使用 print 进行调试(固然,还有 IDE 的 debug 模式)。可是,当你在线上运行 Python 脚本的时候,你并不可能一直守着你的运行终端。但是若是不守着的话,每当出现 bug ,错误又无从查起。这个时候,你须要对你的调试工具进行更新换代了,这里我推荐一个优雅的调试工具 logging。面试
那既然我推荐这个工具,它凭什么要被推荐呢?且来看看它有什么优点:算法
logging.basicConfig(level=log_level, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
logger.info("Log level info")
logger.debug("Log level debug")
logger.warning("Log level warning")
# 捕获异常,并打印出出错行数
try:
raise Exception("my exception")
except (SystemExit, KeyboardInterrupt):
raise
except Exception:
logger.error("there is an error =>", exc_info=True)
复制代码
level 为日志等级,分为:编程
FATAL:致命错误
CRITICAL:特别糟糕的事情,如内存耗尽、磁盘空间为空,通常不多使用
ERROR:发生错误时,如IO操做失败或者链接问题
WARNING:发生很重要的事件,可是并非错误时,如用户登陆密码错误
INFO:处理请求或者状态变化等平常事务
DEBUG:调试过程当中使用DEBUG等级,如算法中每一个循环的中间状态
复制代码
foamat 能够格式化输出,其参数有以下:json
%(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:打印日志信息
复制代码
捕获异常,如下两行代码都具备相同的做用小程序
logger.exception(msg,_args)
logger.error(msg,exc_info = True,_args)
复制代码
这个用法直接 copy 使用就行bash
import logging
# 写入文件
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("info.log")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info("Log level info")
logger.debug("Log level debug")
logger.warning("Log level warning")
# 写入文件,同时输出到屏幕
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level = logging.INFO)
handler = logging.FileHandler("info.log")
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("Log level info")
logger.debug("Log level debug")
logger.warning("Log level warning")
复制代码
被调用者的日志格式会与调用者的日志格式同样 main.py服务器
# -*- coding: utf-8 -*-
__auth__ = 'zone'
__date__ = '2019/6/17 下午11:46'
''' 公众号:zone7 小程序:编程面试题库 '''
import os
import logging
from python.logging_model.code import sub_of_main
logger = logging.getLogger("zone7Model")
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)
sub = sub_of_main.SubOfMain()
logger.info("main module log")
sub.print_some_log()
复制代码
sub_of_main.py函数
# -*- coding: utf-8 -*-
__auth__ = 'zone'
__date__ = '2019/6/17 下午11:47'
''' 公众号:zone7 小程序:编程面试题库 '''
import logging
module_logger = logging.getLogger("zone7Model.sub.module")
class SubOfMain(object):
def __init__(self):
self.logger = logging.getLogger("zone7Model.sub.module")
self.logger.info("init sub class")
def print_some_log(self):
self.logger.info("sub class log is printed")
def som_function():
module_logger.info("call function some_function")
复制代码
这里分别给出了两种配置文件的使用案例,都分别使用了三种输出,输出到命令行、输出到文件、将错误信息独立输出到一个文件工具
{
"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_handler2"],
"propagate":"no"
}
},
"root":{
"level":"INFO",
"handlers":["console","info_file_handler","error_file_handler"]
}
}
复制代码
经过 json 文件读取配置:
import json
import logging.config
import os
def set_log_cfg(default_path="log_cfg.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 record_some_thing():
logging.info("Log level info")
logging.debug("Log level debug")
logging.warning("Log level warning")
if __name__ == "__main__":
set_log_cfg(default_path="log_cfg.json")
record_some_thing()
复制代码
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 文件读取配置:
import yaml
import logging.config
import os
def set_log_cfg(default_path="log_cfg.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 record_some_thing():
logging.info("Log level info")
logging.debug("Log level debug")
logging.warning("Log level warning")
if __name__ == "__main__":
set_log_cfg(default_path="log_cfg.yaml")
record_some_thing()
复制代码
本文首发于公众号「zone7」,关注获取最新推文!