前言
py 中确实有logging 包来打印日志和写入文件,但是handler 写法比较复杂,这里使用了一个三方库loguru
安装 loguru
pip install loguru
简单进行使用
logger.info("If you're using Python {}, prefer {feature} of course!", 3.6, feature="f-strings")
logger.debug("this is a debug log")
logger.warning("this is waring log , because time over 1ms, taskId is {taskId}", taskId="123456")
logger.error("this is error log")
logger.success("gRPC server serve")
logger.critical("something is error")
对方法进行堆栈抓包
@logger.catch
def trace_test(x, y, z):
return x * y / z
# 这里除以0 来进行模拟
trace_test(1, 2, 0)
对全局的try except 进行输出
logger.add(diagnose=True)
def func(a, b):
return a / b
def nested(c):
try:
func(5, c)
except ZeroDivisionError:
logger.exception("What?!")
nested(0)
写入文件,切分,等级限制 完整版设置
# log path
LOG_FILE = "/var/log/logfilename.log"
# log size 大于20MB 生成新文件
LOG_SIZE = '20 MB'
# 或者按照时间来切分, 这里到12点会生成一个新文件
# LOG_SIZE = '12:00'
logger.add(LOG_FILE, rotation=LOG_SIZE, diagnose=True, level=logging.INFO)
结尾
赶鸭子上架写了点py代码,不敢卖弄。