python将logger内容保存到日志文件中 + 将控制台信息保存到日志文件中 + 生成时间戳记录

本文介绍了如何在Python中使用logging模块创建Logger对象,实现控制台和文件的日志记录,并展示了如何通过TerminalLogger重定向控制台输出。同时,文中提及了生成时间戳的功能以增强日志的时序性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

总览

分为三个部分:
1、使用Logger对象输出,记录日志
2、使用重定向控制台输出,记录日志
3、生成时间戳

使用Logging模块记录日志

import logging
import sys
import os
import time
from datetime import datetime

class Logger():
    """ 使用logging模块创建logger对象,记录由logger输出的日志信息
    """
    def __init__(self, LoggerName, FileName, CmdLevel, FileLevel):
        # LoggerName:实例化对象的名字  FileName:外部文件名   CmdLevel:设置控制台中日志输出的级别  FileLevel:设置文件日志输出的级别
        self.logger = logging.getLogger(LoggerName)
        # 设置日志的级别
        self.logger.setLevel(logging.DEBUG)
        # 设置日志的输出格式
        fmt = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')

        # 借助handle将日志输出到test.log文件中
        fh = logging.FileHandler(FileName, encoding='utf-8')
        fh.setLevel(FileLevel)

        # 借助handle将日志输出到控制台
        ch = logging.StreamHandler()
        # ch.setLevel(CmdLevel)

        # 配置logger
        fh.setFormatter(fmt)
        # ch.setFormatter(fmt)

        # 给logger添加handle
        self.logger.addHandler(fh)
        # self.logger.addHandler(ch)

    def debug(self, message):
        self.logger.debug(message)

    def info(self, message):
        self.logger.info(message)

    def warn(self, message):
        self.logger.warning(message)

    def error(self, message):
        self.logger.error(message)

    def critical(self, message):
        self.logger.critical(message)

    def close(self):
        self.logger.disabled = True

测试

logger = Logger("my_log","./my_log.log",CmdLevel=logging.DEBUG,FileLevel=logging.INFO)

logger.debug("debug message!")
logger.info("info message!")
logger.warn("warning message!")
logger.error("error message!")
logger.critical("critical message!")

输出

控制台:
2020-09-10 10:32:46,230-appium-DEBUG-debug message!
2020-09-10 10:32:46,230-appium-INFO-info message!
2020-09-10 10:32:46,230-appium-WARNING-warning message!
2020-09-10 10:32:46,230-appium-ERROR-error message!
2020-09-10 10:32:46,230-appium-CRITICAL-critical message!
 
my_log.log 外部文件:
20-09-10 10:32:46,230-appium-INFO-info message!
2020-09-10 10:32:46,230-appium-WARNING-warning message!
2020-09-10 10:32:46,230-appium-ERROR-error message!
2020-09-10 10:32:46,230-appium-CRITICAL-critical message

参考:Python接口自动化测试输出日志到控制台和文件

重定向控制台输出记录日志


class TerminalLogger(object):
    """ 将控制台上输出重定向,将控制台内容输入到log_path文件内
    """
    def __init__(self, log_path, stream=sys.stdout):
        self.terminal = stream
        self.log = open(log_path, 'a')

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)
        self.terminal.flush()  # 不启动缓冲,实时输出
        self.log.flush()

    def flush(self):
        pass

调用

sys.stdout = Logger('./my_log.log', sys.stdout)
sys.stderr = Logger('./my_log.log', sys.stderr)
print(123456)
print('==========')

输出

控制台:
123456
 ==========
 
my_log.log 外部文件:
123456
 ==========

参考文章:python记录日志,保存控制台输出

生成时间戳

def record_timestamp():
    """ 生成当前时间

    Returns: 当前时间

    """
    now = datetime.now()
    return now

调用

now = record_timestamp()
print(now)

输出

2024-01-23 17:56:56.064402

参考文章:python生成日期

构建日志记录库文件,封装后方便调用

import logging
import sys
import os
import time
from datetime import datetime

class Logger():
    """ 使用logging模块创建logger对象,记录由logger输出的日志信息
    """
    def __init__(self, LoggerName, FileName, CmdLevel, FileLevel):
        # LoggerName:实例化对象的名字  FileName:外部文件名   CmdLevel:设置控制台中日志输出的级别  FileLevel:设置文件日志输出的级别
        self.logger = logging.getLogger(LoggerName)
        # 设置日志的级别
        self.logger.setLevel(logging.DEBUG)
        # 设置日志的输出格式
        fmt = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')

        # 借助handle将日志输出到test.log文件中
        fh = logging.FileHandler(FileName, encoding='utf-8')
        fh.setLevel(FileLevel)

        # 借助handle将日志输出到控制台
        ch = logging.StreamHandler()
        # ch.setLevel(CmdLevel)

        # 配置logger
        fh.setFormatter(fmt)
        # ch.setFormatter(fmt)

        # 给logger添加handle
        self.logger.addHandler(fh)
        # self.logger.addHandler(ch)

    def debug(self, message):
        self.logger.debug(message)

    def info(self, message):
        self.logger.info(message)

    def warn(self, message):
        self.logger.warning(message)

    def error(self, message):
        self.logger.error(message)

    def critical(self, message):
        self.logger.critical(message)

    def close(self):
        self.logger.disabled = True


class TerminalLogger(object):
    """ 将控制台上输出重定向,将控制台内容输入到log_path文件内
    """
    def __init__(self, log_path, stream=sys.stdout):
        self.terminal = stream
        self.log = open(log_path, 'a')

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)
        self.terminal.flush()  # 不启动缓冲,实时输出
        self.log.flush()

    def flush(self):
        pass

def record_terminal(log_path):
    """ 调用TerminalLogger的方法

    Args:
        log_path: log文件路径

    Returns:

    """
    # 记录正常的 print 信息
    sys.stdout = TerminalLogger(log_path, sys.stdout)
    # 记录 traceback 异常信息
    sys.stderr = TerminalLogger(log_path, sys.stderr)

def record_timestamp():
    """ 生成当前时间

    Returns: 当前时间

    """
    now = datetime.now()
    return now

if __name__ == '__main__':
	# 方式一:调用控制台重定向将控制台中信息记录到指定路径文件中
	record_terminal('./my_log.log')
	# 方式二:调用Logger对象,使用logging模块记录日志
	logger = Logger("my_log","./my_log.log",CmdLevel=logging.DEBUG,FileLevel=logging.INFO)
	
	# 将时间信息输出到控制台,让日志记录中有时间信息
	new = record_timestamp()
要实现实时将logcat中的错误和异常信息保存到文件中,您可以使用Python的subprocess模块和threading模块。使用subprocess模块启动一个子进程运行adb命令获取logcat日志,并使用threading模块启动一个新线程实时读取子进程的输出,筛选出错误和异常信息并将其写入文件中。以下是一个示例代码: ```python import subprocess import threading import re # 定义一个函数来实时读取子进程输出并将错误和异常信息写入文件中 def save_log_errors(file_path): # 运行adb命令获取logcat日志 adb_command = "adb logcat" process = subprocess.Popen(adb_command.split(), stdout=subprocess.PIPE) # 使用正则表达式筛选出错误和异常信息 error_pattern = re.compile(r'\bError\b|\bException\b') # 实时读取子进程输出并将错误和异常信息写入文件中 with open(file_path, 'w') as file: while True: output = process.stdout.readline().decode('utf-8') if output == '' and process.poll() is not None: break if error_pattern.search(output): file.write(output) # 启动一个新线程来实时读取logcat输出并将错误和异常信息保存到文件中 thread = threading.Thread(target=save_log_errors, args=('log_errors.txt',)) thread.start() # 主线程可以在这里执行其他任务 ``` 该代码会将实时读取到的错误和异常信息保存到名为"log_errors.txt"的文件中。您可以根据需要修改文件名和路径。注意,子进程会一直运行,直到您手动停止它。因此,在您的应用程序退出时,应该停止子进程以释放资源。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

辰阳星宇

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

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

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

打赏作者

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

抵扣说明:

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

余额充值