PYthon之日志模块
1、目录结构
File
|-----logFiles
|-----utils
|------handle_log.py
|------test.py
2、handle_log.py 代码如下

# coding = utf-8
# author: DeyouKong
# 时间: 2020年12月16日
import os
import sys
import logbook
sys.path.append("../")
BASE_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
sys.path.append(BASE_DIR)
from logbook import Logger, StreamHandler, FileHandler, TimedRotatingFileHandler
from logbook.more import ColorizedStderrHandler
def log_content(record, handler):
log = "[{date}] [{level}] [{filename}] [{func_name}] [{lineno}] {msg}".format(
date=record.time, # log time
level=record.level_name, # log level
filename=os.path.split(record.filename)[-1], # ffilename
func_name=record.func_name, # function name
lineno=record.lineno, # line number in run file
msg=record.message # log message
)
return log
""" The path to save log file """
LOG_DIR = BASE_DIR + "/logFiles"
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
""" The log message print to the screen """
log_std = ColorizedStderrHandler(bubble=True)
log_std.formatter = log_content
""" The log message write to the file """
log_file = TimedRotatingFileHandler(
os.path.join(LOG_DIR, "%s.log" % "log"), date_format='%Y-%m-%d', bubble=True, encoding='utf-8'
)
log_file.formatter = log_content
""" Log for script """
run_log = Logger("global_log")
def init_logger():
logbook.set_datetime_format("local")
run_log.handlers = []
run_log.handlers.append(log_file)
run_log.handlers.append(log_std)
return ""
'''
日志等级:
critical 严重错误,会导致程序退出
error 可控范围内的错误
warning 警告信息
notice 大多情况下希望看到的记录
info 大多情况不希望看到的记录
debug 调试程序时详细输出的记录
'''
# 实例化,默认调用
logger = init_logger()
if __name__ == "__main__":
run_log.info("Test info log message")
run_log.notice("Test notice log message")
run_log.warning("Test warning log message")
run_log.error("Test error log message")

运行后,屏幕输出
[2020-12-16 18:06:01.594226] [INFO] [handle_log.py] [] [68] Test info log message
[2020-12-16 18:06:01.594957] [NOTICE] [handle_log.py] [] [69] Test notice log message
[2020-12-16 18:06:01.595196] [WARNING] [handle_log.py] [] [70] Test warning log message
[2020-12-16 18:06:01.595355] [ERROR] [handle_log.py] [] [71] Test error log message
logFiles下面新建了 logFiles/log-2020-12-16.log文件 ,内容与屏幕输出一致
3、同目录下新建 test.py
test.py
from handle_log import run_log as logger
import requests
import json
def TestOne():
logger.info("start run Test One")
if 1==1:
logger.notice("into the first check")
if __name__ == "__main__":
TestOne()
运行 test.py,屏幕输出
[2020-12-16 18:30:53.563785] [INFO] [test.py] [TestOne] [6] start run Test One
[2020-12-16 18:30:53.564630] [NOTICE] [test.py] [TestOne] [8] into the first check
log文件见下图

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)