当前位置:   article > 正文

Python 记录日志到文件_模块封装_同时写入多个文件错乱解决_python logging 同时写多个文件

python logging 同时写多个文件

功能

分享自用日志记录功能模块
主要功能如下
1、正常日志写入、错误日志写入单独封装,导入即用。
2、多任务写入不同的日志文件时,避免功能函数生成的同一日志信息写入了不同日志文件内。
3、按天生成日志文件。
4、覆盖模式生成日志文件。

补充

1.同时启用按天生成日志文件和覆盖模式后,在第二天时将不会再继续覆盖前天的日志文件。
2.启用按天生成日志文件后生成日志文件名时会追加当天时间如:LogName_2023-02-14.log
3.启用覆盖模式生成日志文件,写入日志文件大小至指定条件后会重命名当前日志文件并重新生成,日志文件数量达到限制数量后会替换最先的日志文件,以此类推。文件名如下:
LogName.log
LogName.log.1
LogName.log.2
LogName.log.3
LogName.log.4
LogName.log.5

代码

Logger.py

import logging,os,sys,time
import logging.handlers
import traceback

'''
format 可以指定输出的内容和格式,其内置的参数如下:
%(name)s:Logger的名字
%(levelno)s:打印日志级别的数值
%(levelname)s:打印日志级别的名称
%(pathname)s:打印当前执行程序的路径
%(filename)s:打印当前执行程序名
%(funcName)s:打印日志的当前函数
%(lineno)d:打印日志的当前行号
%(asctime)s:打印日志的时间
%(thread)d:打印线程ID
%(threadName)s:打印线程名称
%(process)d:打印进程ID
%(message)s:打印日志信息
'''

def Write_logger(name='log',file_name='log',info='runlog msg',absolute_path=False,by_day=False,sub_dir='',
    rotating=False,max_size=1024*1024*10,backup_count=5):# 写入日志信息
    """
    写正常log的函数
    :param name: 类型名称,区分log文件
    :param file_name: log文件名
    :param info: 写入的信息
    :param absolute_path: 绝对路径模式
    :param by_day: 是否按天生成log文件
    :param sub_dir: 存放子目录
    :param rotating: 是否启用覆盖模式
    :param max_size: 启用覆盖模式后,单个文件大小(bytes/默认10M)
    :param backup_count: 启用覆盖模式后,可存在文件数量(默认5)
    """
    day = '' if not by_day else f'_{time.strftime("%Y-%m-%d")}'  # 按天文件名
    sub_dir_ = f'{sub_dir}/' if sub_dir else ''  # 存放子目录
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)# 设置等级为DEBUG
    if absolute_path:  # 按照模式来设置文件名
        logfile=f'{file_name}{day}.log'
    else:
        if len(os.path.dirname(sys.argv[0])):
            logpath = os.path.dirname(sys.argv[0])+f'/Log/{sub_dir_}'
        else:
            logpath = os.getcwd()+f'/Log/{sub_dir_}'
        if not os.path.exists(logpath):
            try:
                os.makedirs(logpath)
            except Exception as e:
                print(traceback.format_exc())
        logfile=logpath+f'{file_name}{day}.log'
    if not rotating:  #是否启用覆盖模式
        filehandler = logging.FileHandler(logfile,encoding="utf-8",mode="a")
    else:
        filehandler = logging.handlers.RotatingFileHandler(logfile,encoding="utf-8",mode="a", maxBytes=max_size, backupCount=backup_count)
    filehandler.setLevel(logging.DEBUG)
    filehandler_formatter = logging.Formatter('[%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s : %(message)s ]')
    
    filehandler.setFormatter(filehandler_formatter)
    logger.addHandler(filehandler)
    logger.debug(info)
    logger.removeHandler(filehandler)

def Write_errorlogger(name='errorlog',file_name='errorlog',info='errorlog msg',absolute_path=False,by_day=False,sub_dir='',
    rotating=False,max_size=1024*1024*10,backup_count=5):# 写入错误日志信息
    """
    写错误log的函数
    :param name: 类型名称 区分log文件
    :param file_name: log文件名
    :param info: 写入的信息
    :param absolute_path: 绝对路径模式
    :param by_day: 是否按天生成log文件
    :param sub_dir: 存放子目录
    :param rotating: 是否启用覆盖模式
    :param max_size: 启用覆盖模式后,单个文件大小(bytes/默认10M)
    :param backup_count: 启用覆盖模式后,可存在文件数量(默认5)
    """
    day = '' if not by_day else f'_{time.strftime("%Y-%m-%d")}'  # 按天文件名
    sub_dir_ = f'{sub_dir}/' if sub_dir else ''  # 存放子目录
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)# 设置等级为DEBUG
    if absolute_path:  # 按照模式来设置文件名
        logfile=f'{file_name}{day}.log'
    else:
        if len(os.path.dirname(sys.argv[0])):
            logpath = os.path.dirname(sys.argv[0])+f'/Log/{sub_dir_}'
        else:
            logpath = os.getcwd()+f'/Log/{sub_dir_}'
        if not os.path.exists(logpath):
            try:
                os.makedirs(logpath)
            except Exception as e:
                print(traceback.format_exc())
        logfile=logpath+f'{file_name}{day}.log'
    if not rotating:  #是否启用覆盖模式
        filehandler = logging.FileHandler(logfile,encoding="utf-8",mode="a")
    else:
        filehandler = logging.handlers.RotatingFileHandler(logfile,encoding="utf-8",mode="a", maxBytes=max_size, backupCount=backup_count)
    filehandler.setLevel(logging.DEBUG)
    filehandler_formatter = logging.Formatter('{%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s : %(message)s }')
    filehandler.setFormatter(filehandler_formatter)
    logger.addHandler(filehandler)
    logger.error(info,exc_info=True)
    logger.removeHandler(filehandler)

    
if __name__ == "__main__":
    
    # 写入正常log
    Write_logger(name='log',file_name='runlog',info='我是一段正常信息')

    # 写入错误log
    try:
        a = 1
        b = a + '我不是数字'
    except Exception as e:
        Write_errorlogger(name='error',file_name='errorlog',info='我是一段错误信息')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
'
运行

效果

runlog.log

[2023-02-14 10:28:10,564 - Logger.py[line:66] - DEBUG : 我是一段正常信息 ]
  • 1

errorlog.log

{2023-02-14 10:28:10,564 - Logger.py[line:108] - ERROR : 我是一段错误信息 }
Traceback (most recent call last):
  File "E:/PythonProject/demo/Logger.py", line 120, in <module>
    b = a + '我不是数字'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/在线问答5/article/detail/963184
推荐阅读
相关标签
  

闽ICP备14008679号