python篇----python使用logging模块实现日志写入

python使用logging模块实现日志写入

其一

"""
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))

注意事项:
在这里插入图片描述在这里插入图片描述在这里插入图片描述

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")

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: Python logging 模块Python 标准库中的一个模块,用于记录程序运行时的日志信息。使用 logging 模块可以方便地记录程序的运行状态,以便在出现问题时进行排查。 使用 logging 模块需要先导入模块,然后创建一个 logger 对象,设置日志级别和输出格式,最后在程序中使用 logger 对象记录日志信息。 下面是一个简单的示例代码: ``` import logging # 创建 logger 对象 logger = logging.getLogger('mylogger') # 设置日志级别 logger.setLevel(logging.DEBUG) # 创建一个输出到控制台的 handler console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) # 创建一个输出到文件的 handler file_handler = logging.FileHandler('mylog.log') file_handler.setLevel(logging.INFO) # 设置输出格式 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') console_handler.setFormatter(formatter) file_handler.setFormatter(formatter) # 将 handler 添加到 logger 对象中 logger.addHandler(console_handler) logger.addHandler(file_handler) # 记录日志信息 logger.debug('debug message') logger.info('info message') logger.warning('warning message') logger.error('error message') logger.critical('critical message') ``` 在上面的示例代码中,我们创建了一个名为 `mylogger` 的 logger 对象,并设置了日志级别为 `DEBUG`。然后创建了一个输出到控制台的 handler 和一个输出到文件的 handler,并设置了输出格式。最后将这两个 handler 添加到 logger 对象中。 在程序中使用 logger 对象记录日志信息时,可以使用 `debug()`、`info()`、`warning()`、`error()`、`critical()` 等方法,分别对应不同的日志级别。例如,`logger.debug('debug message')` 就会记录一条 DEBUG 级别的日志信息。 以上就是 Python logging 模块的基本使用方法。 ### 回答2: Pythonlogging模块是一个强大的日志记录工具。它提供了一种灵活的方式来在程序中记录日志,以便在程序运行过程中获取有用的信息和诊断数据。下面是如何使用Python logging模块的基本步骤。 1. 导入logging模块: ```python import logging ``` 2. 配置日志记录器: ```python logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', filename='app.log', filemode='w') ``` 在配置方法中,level参数设置日志级别,可选项包括DEBUG、INFO、WARNING、ERROR和CRITICAL。format参数定义日志记录的格式,其中asctime表示日志记录的时间,levelname表示日志级别,message表示要记录的消息。filename参数指定日志文件的名称,filemode参数定义日志写入模式,例如'w'表示写入模式,'a'表示追加模式。 3. 记录日志: ```python logging.debug('Debug message') logging.info('Info message') logging.warning('Warning message') logging.error('Error message') logging.critical('Critical message') ``` 使用logging模块中的不同方法来记录不同级别的日志。 4. 进一步配置日志记录器: ```python logger = logging.getLogger('my_logger') logger.setLevel(logging.DEBUG) ``` 如果需要更多的配置选项,可以创建一个logger对象,并使用setLevel方法设置日志级别。 通过这些步骤,可以在程序中使用logging模块记录日志。这样,可以根据需要记录不同级别的日志,并通过指定的格式将日志写入到文件中。日志记录对于程序的调试和问题排查非常有帮助。 ### 回答3: Python中的logging模块是一个内置的日志记录工具。它提供了一种简单而灵活的方式来记录运行时的信息,帮助我们调试程序和追踪错误。下面是使用logging模块的一些主要步骤: 1. 导入logging模块: ```python import logging ``` 2. 设置日志记录的级别: ```python logging.basicConfig(level=logging.DEBUG) ``` 这里设置的是日志记录的最低级别为DEBUG,即记录所有级别的日志信息。还有其他的级别可选择,如:INFO、WARNING、ERROR等,可以根据需要设置。 3. 编写日志信息: ```python logging.debug("This is a debug message") logging.info("This is an info message") logging.warning("This is a warning message") logging.error("This is an error message") ``` 4. 输出日志信息: 日志信息可以输出到控制台、文件或其他地方。默认情况下,日志信息会输出到控制台。 ```python logging.debug("This is a debug message") ``` 可以通过配置logging模块日志信息输出到文件。 ```python logging.basicConfig(filename='example.log', level=logging.DEBUG) ``` 这里将日志信息输出到文件"example.log"中。 以上是使用logging模块的基本步骤。logging模块还支持更高级的用法,如添加时间戳、设置日志的格式等。可以通过查阅官方文档来了解更多关于logging模块的详细信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

心惠天意

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值