python 日志写入文件,参数说明及动态判断文件是创建还是追加

import logging
import os


'''
格式符    含义
%(levername)s    日志级别名称
%(pathname)s    当前执行程序的路径(即脚本所在的位置)
%(filename)s    执行脚本程序名
%(lineno)d        日志当前的行号
%(asctime)s        打印日志的时间
%(message)s        日志信息

常用的日志 fromat 常用方案:fromat = '%(asctime)s %(filename)s[line:%(lineno)d] %(levername)s %(message)s'
'''
# fmt = "%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s: %(message)s %(pathname)s"

'''
参数名    作用                举例
lever    日志输出的最低等级    lever=logging.DEBUG
format    日志输出格式        见下文的 format 具体格式
filename    存储位置        filename=‘d://debug.log’
filemode    输入模式        filemode=“w”    'w' 模式为没有文件时创建文件;'a' 模式为追加内容写入日志文件
'''
# logging.basicConfig(
#     level=logging.DEBUG,
#     format=fmt,
#     filename="D:\logs-220817.txt",
#     filemode="w",
#     datefmt="%a, %d %b %Y %H:%M:%S"
# )


'''
debug:可以帮助我们在平时的开发过程中,帮助我们查看一些输出的信息是否正确。它可以替代我们平时使用的 print() 函数。
info:它代表了一般的消息类信息,只是为了记录一些程序的行为,比如程序执行到了某个位置,进行一些简单的记录。
warnning:该等级是一种警告,一般来说程序不会出错,但是可能存在一定的潜在风险。
error:一般对应业务中出现了重大问题。比如异常或者业务逻辑不应该执行到某种情况。我们都可以通过error来进行记录。
critical:比 error 更严重的级别,不过一般来说 error 级别已经很严重了,所以 critical 很少使用。
'''


def init_log(path):
    if os.path.exists(path):
        mode = 'a'
    else:
        mode = 'w'
    logging.basicConfig(  # 针对 basicConfig 进行配置(basicConfig 其实就是对 logging 模块进行动态的调整,之后可以直接使用)
        level=logging.INFO,  # INFO 等级以下的日志不会被记录
        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',  # 日志输出格式
        filename='back.log',  # 日志存放路径(存放在当前相对路径)
        filemode=mode,  # 输入模式;如果当前我们文件已经存在,可以使用 'a' 模式替代 'w' 模式
        # 与文件写入的模式相似,'w' 模式为没有文件时创建文件;'a' 模式为追加内容写入日志文件
    )

    return logging


current_path = os.getcwd()
path = os.path.join(current_path, 'back.log')

log = init_log(path)  # 初始化返回的 init_log() 函数 , 其实就是 return logging


logging.debug("this is debug logger2")
logging.info("this is info logger2")

logging.warn("this is warn logger2")
logging.error("this is error logger2")
logging.critical("this is critical logger2")


# 文件输出
# 2022-08-30 16:20:50,738 testlogger2.py[line:68] INFO this is info logger
# 2022-08-30 16:20:50,738 testlogger2.py[line:70] WARNING this is warn logger
# 2022-08-30 16:20:50,739 testlogger2.py[line:71] ERROR this is error logger
# 2022-08-30 16:20:50,739 testlogger2.py[line:72] CRITICAL this is critical logger
# 2022-08-30 16:22:21,908 testlogger2.py[line:68] INFO this is info logger2
# 2022-08-30 16:22:21,909 testlogger2.py[line:70] WARNING this is warn logger2
# 2022-08-30 16:22:21,909 testlogger2.py[line:71] ERROR this is error logger2
# 2022-08-30 16:22:21,909 testlogger2.py[line:72] CRITICAL this is critical logger2

 

posted on 2022-08-30 16:32  oktokeep  阅读(548)  评论(1)    收藏  举报