美文网首页
python中日志详解---logging模块

python中日志详解---logging模块

作者: 木火_magic | 来源:发表于2024-01-23 17:14 被阅读0次

一、logging模块

1、Log_Format字符串

Log_Format = "%(levelname)s %(asctime)s - %(message)s"

Log_Format 字符串中为我们的日志创建了一个格式,这种格式包括日志的级别、发生的日期和时间以及要写入的消息

2、函数logging.basicConfig()

logging.basicConfig(
      filename="logfile.log", filemode="w", format=Log_Format, level=logging.ERROR)

参数讲解
lever:高于或者等于这个值时,那么我们才会几记录这条日志

总共有7等级:OFF 、FATAL 、ERROR、WARN、INFO、DEBUG、TRACE 、ALL
1.OFF 为最高等级 关闭了日志信息
2.FATAL 为可能导致应用中止的严重事件错误
3.ERROR 为严重错误 主要是程序的错误
4.WARN 为一般警告,比如session丢失
5.INFO 为一般要显示的信息,比如登录登出
6.DEBUG 为程序的调试信息
7.TRACE 为比DEBUG更细粒度的事件信息
8.ALL 为最低等级,将打开所有级别的日志
输出的规则是,大于等于当前设置的日志等级的才会被输出

filename:日志文件名,如果没有这个字段,则会显示在控制台上
format:日志显示的格式,如果字段为空,则为模式格式:level:log_name:content
filemode:a,append,可以追加,w,写入,会覆盖之前内容

lever测试
import logging
#日志格式
Log_Format = "%(levelname)s %(asctime)s - %(message)s"
#filemode =a,append,可以追加,w,写入,会覆盖之前内容
logging.basicConfig(
filename="logfile1.log", filemode="a", format=Log_Format, level=logging.ERROR
)
logger = logging.getLogger()
# Testing our Logger
logger.fatal("11111") #严重错误,可能会导致程序运行不正常
logger.error("22222") #错误,影响程序的正常运行
logger.warning("33333") #警告,不会影响程序运行,
logger.info("44444")   #一般信息,不影响程序的运行
logger.debug("55555")   #一般信息,调试信息,等同于 system.out

结果:低于lever的日志不会输出

输出结果

3、logging.getLogger()

创建一个记录器对象来写入日志消息,

4、logger.error(" ")

logger.error("22222")编写了错误消息。

logger.fatal("11111") #严重错误,可能会导致程序运行不正常
logger.error("22222") #错误,影响程序的正常运行
logger.warning("33333") #警告,不会影响程序运行,
logger.info("44444")   #一般信息,不影响程序的运行
logger.debug("55555")   #一般信息,调试信息,等同于 system.out

二、logging模块【第二中写法】

import logging

logger = logging.getLogger()
handler = logging.FileHandler("logfile.log")
logger.addHandler(handler)
logger.error("Our First Log Message")

1、首先创建了一个 logger 对象,使用该对象通过 logging.getLogger() 函数编写日志
2、创建一个文件处理程序 handler,并为其分配 logging.FileHandler('logfile.log')。
3、使用 logger.addHandler(handler) 将这个新的 handler 添加到我们的记录器对象中
4、使用 logger.error('Our First Log Message') 将错误消息写入我们的文件。

三【第三种写法】给出代码示例

"""
logging配置
"""

import os
import logging.config
import time

# 定义三种日志输出格式 开始

standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]'  # 其中name为getlogger指定的名字

console_format = '[%(asctime)s][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]'  # 其中name为getlogger指定的名字

# simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
simple_format = '%(message)s'
#自定义的一种格式
sender_format = 'from sender :  %(message)s'

# 定义日志输出格式 结束
# print(os.path.dirname(os.path.abspath(__file__)))
logfile_dir = os.path.dirname(os.path.abspath(__file__)) + "/" + "log"  # log文件的目录

if not os.path.exists(logfile_dir):
    os.makedirs(logfile_dir)

# if not os.path.exists(logfile_send_dir):
#     os.makedirs(logfile_send_dir)

current_day = time.strftime("%Y-%m-%d", time.localtime())

log_file_name = logfile_dir +'/'+ current_day +'.log'

app_file_name = logfile_dir + '/app.log'

send_file_name = logfile_dir + '/send.log'


# log文件的全路径
log_file_path = os.path.join(logfile_dir, log_file_name)
# print(logfile_path)
app_file_path = os.path.join(logfile_dir, app_file_name)
send_file_path = os.path.join(logfile_dir, send_file_name)
# print(logfile_send_path)

# log配置字典
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
        'sender':{
            'format': sender_format
        }
    },
    'filters': {},
    'handlers': {
        # 打印到终端的日志
        'console': {
            'level': 'INFO',
            'class': 'logging.StreamHandler',  # 打印到屏幕
            'formatter': 'standard'
        },
        # 打印到文件的日志,收集info及以上的日志
        'default': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
            'formatter': 'standard',
            'filename': log_file_path,  # 日志文件
            'maxBytes': 1024*1024*50,  # 日志大小 5M
            'backupCount': 20,
            'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
        },
        'timedRotating': {
            'level': 'INFO',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'when': 'midnight',
            'interval': 1,
            'filename': app_file_path,
            'encoding': 'utf-8',
            'backupCount': 5,
            'formatter': 'simple'
        },
        'sendRotating': {
            'level': 'INFO',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'when': 'midnight',
            'interval': 1,
            'filename': send_file_path,
            'encoding': 'utf-8',
            'backupCount': 5,
            'formatter': 'sender'
        }
    },
    'loggers': {
        # logging.getLogger(__name__)拿到的logger配置
        'dev': {
            'handlers': ['timedRotating','default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'INFO',
            'propagate': True,  # 向上(更高level的logger)传递
        },
        'prod': {
            'handlers': ['sendRotating','default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            'level': 'INFO',
            'propagate': True,  # 向上(更高level的logger)传递
        },
    },
}

logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
logger = logging.getLogger('dev')  # 生成一个log实例
send_logger = logging.getLogger('prod')  # 生成一个log实例


if __name__ == '__main__':
    for i in range(10):
        logger.info('It works! {}'.format(i))  # 记录该文件的运行状态
        send_logger.info('hhhhh --> {}'.format(i))

注意以下内容

image.png image.png

eg 其一

"""
logging配置
"""

import os
import logging.config
import time

# 定义三种日志输出格式 开始

standard_format = "[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]" \
                  "[%(levelname)s][%(message)s]"  # 其中name为getlogger指定的名字

simple_format = "[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s"

id_simple_format = "[%(levelname)s][%(asctime)s] %(message)s"

# 定义日志输出格式 结束

logfile_dir = os.path.dirname(os.path.abspath(__file__)) + "/" + "log"  # log文件的目录
current_data = time.strftime("%Y-%m-%d", time.localtime())
# logfile_name = "data/yolo_app.log"  # log文件名
logfile_name = logfile_dir + "/" + current_data + ".log"
have_result_file = logfile_dir + "/" + current_data + "_haveResults.log"
no_result_file = logfile_dir + "/" + current_data + "_noResults.log"
exclusive_file = logfile_dir + "/" + current_data + "_exclusive.log"
send_file = logfile_dir + "/" + current_data + "_send.log"


# 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):
    os.mkdir(logfile_dir)

# log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name)

# log配置字典
LOGGING_DIC = {
    "version": 1,
    "disable_existing_loggers": True,
    "formatters": {
        "standard": {
            "format": standard_format
        },
        "simple": {
            "format": simple_format
        },
    },
    "filters": {},
    "handlers": {
        # 打印到终端的日志
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",  # 打印到屏幕
            "formatter": "simple"
        },
        # 打印到文件的日志,收集info及以上的日志
        "default": {
            "level": "DEBUG",
            "class": "logging.handlers.RotatingFileHandler",  # 保存到文件
            "formatter": "standard",
            "filename": logfile_path,  # 日志文件
            "maxBytes": 1024*1024*5,  # 日志大小 5M
            "backupCount": 5,
            "encoding": "utf-8",  # 日志文件的编码,再也不用担心中文log乱码了
        },
        "have": {
            "level": "DEBUG",
            "class": "logging.handlers.RotatingFileHandler",  # 保存到文件
            "formatter": "simple",
            "filename": have_result_file,  # 日志文件
            "maxBytes": 1024*1024*5,  # 日志大小 5M
            "backupCount": 5,
            "encoding": "utf-8",  # 日志文件的编码,再也不用担心中文log乱码了
        },
        "no": {
            "level": "DEBUG",
            "class": "logging.handlers.RotatingFileHandler",  # 保存到文件
            "formatter": "simple",
            "filename": no_result_file,  # 日志文件
            "maxBytes": 1024 * 1024 * 5,  # 日志大小 5M
            "backupCount": 5,
            "encoding": "utf-8",  # 日志文件的编码,再也不用担心中文log乱码了
        },
        "exc": {
            "level": "DEBUG",
            "class": "logging.handlers.RotatingFileHandler",  # 保存到文件
            "formatter": "simple",
            "filename": exclusive_file,  # 日志文件
            "maxBytes": 1024 * 1024 * 5,  # 日志大小 5M
            "backupCount": 5,
            "encoding": "utf-8",  # 日志文件的编码,再也不用担心中文log乱码了
        },
        "s": {
            "level": "DEBUG",
            "class": "logging.handlers.RotatingFileHandler",  # 保存到文件
            "formatter": "simple",
            "filename": send_file,  # 日志文件
            "maxBytes": 1024 * 1024 * 5,  # 日志大小 5M
            "backupCount": 5,
            "encoding": "utf-8",  # 日志文件的编码,再也不用担心中文log乱码了
        },
    },
    "loggers": {
        # logging.getLogger(__name__)拿到的logger配置
        "dev": {
            # "handlers": ["default", "console"],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            "handlers": ["default"],
            "level": "DEBUG",
            "propagate": True,  # 向上(更高level的logger)传递
        },
        "haveResult": {
            # "handlers": ["default", "console"],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            "handlers": ["have"],
            "level": "DEBUG",
            "propagate": True,  # 向上(更高level的logger)传递
        },
        "noResult": {
            # "handlers": ["default", "console"],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            "handlers": ["no"],
            "level": "DEBUG",
            "propagate": True,  # 向上(更高level的logger)传递
        },
        "exclusive": {
            # "handlers": ["default", "console"],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            "handlers": ["exc"],
            "level": "DEBUG",
            "propagate": True,  # 向上(更高level的logger)传递
        },
        "send": {
            # "handlers": ["default", "console"],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
            "handlers": ["s"],
            "level": "DEBUG",
            "propagate": True,  # 向上(更高level的logger)传递
        },
    },
}

logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
# logger = logging.getLogger(__name__)  # 生成一个log实例
logger = logging.getLogger("dev")  # 生成一个log实例
haveRes_logger = logging.getLogger("haveResult")  # 生成一个log实例
noRes_logger = logging.getLogger("noResult")  # 生成一个log实例
exclusive_logger = logging.getLogger("exclusiveResult")  # 生成一个log实例
send_logger = logging.getLogger("sendResult")  # 生成一个log实例
# logger.setLevel(logging.DEBUG)
# print(logger)

# logger.info("It works!")   # 记录该文件的运行状态

其二

# -*- coding: utf-8 -*-
import time
import logging
import os
from logging.handlers import RotatingFileHandler

project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(project_dir)
log_path = project_dir + "/log"
print(log_path)


class Log(logging.Logger):
    def __init__(self, logname):
        # super(MyLogger, self).__init__(filename)
        filename = log_path + logname + '.log'
        logging.Logger.__init__(self, filename)

        # 设置日志格式
        fmtHandler = logging.Formatter('%(asctime)s [%(filename)s:%(lineno)s][%(levelname)s] %(message)s')

        # 终端log输出流设置
        try:
            consoleHd = logging.StreamHandler()
            consoleHd.setLevel(logging.ERROR)
            consoleHd.setFormatter(fmtHandler)
            self.addHandler(consoleHd)
        except Exception as reason:
            self.error("%s" % reason)

            # 设置log文件
        try:
            os.makedirs(os.path.dirname(filename))
        except Exception as reason:
            pass
        try:
            # 设置回滚日志,每个日志最大10M,最多备份5个日志
            fileHd = logging.handlers.RotatingFileHandler(
                filename, maxBytes=10 * 1024 * 1024, backupCount=5)
            # fileHd = logging.FileHandler(filename)
            fileHd.setLevel(logging.INFO)
            fileHd.setFormatter(fmtHandler)
            self.addHandler(fileHd)
        except Exception as reason:
            self.error("%s" % reason)

        return


if __name__ == '__main__':
    test1 = Log('test1')
    test2 = Log('test2')
    # while True:
    test1.info("test1")
    test2.error("test2")
image.png image.png

相关文章

网友评论

      本文标题:python中日志详解---logging模块

      本文链接:https://www.haomeiwen.com/subject/bptpodtx.html