Python之日志模块

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文件见下图

 

posted @ 2020-12-16 18:32  DeyouKong  阅读(69)  评论(0编辑  收藏  举报