将python CMD输出保存到文件,同时仍在CMD上打印

gijlo24d  于 2023-04-19  发布在  Python
关注(0)|答案(1)|浏览(311)

我想把我的python程序输出保存在一个日志文件中,并且仍然能够在控制台中看到它。
我的程序每30分钟运行一次,30分钟后,我的程序进程被我的BATCH文件杀死,强制关闭它。
因此,我不能使用显示程序输出并将其保存到程序结束时的日志文件的解决方案,因为没有“结束”,因为它在运行时被BTACH文件杀死。
有任何解决方案,将能够显示我的程序输出,并写它活的日志文件?,甚至当我会杀死的进程(和程序),我会得到所有的输出,直到它被杀死的点日志文件?

mmvthczy

mmvthczy1#

我还希望在运行python脚本时在控制台中进行日志记录,但也希望将其保存在日志文件中以供以后或并行引用。此外,我希望能够为控制台和文件设置不同级别的输出。例如,在文件中,我希望具有所有级别(DEBUG,INFO,WARNING,ERROR,CRITICAL),但在终端中我只想有WARNING,ERROR,CRITICAL。此外,我想改变,如果我追加到日志文件,或覆盖它。
1.创建一个文件,并将其命名为logging_handler.py,例如包含以下内容:

import logging
import os

def logger(
    stream_logger=dict(),
    file_logger=dict(),
    logger_name="",
) -> logging.Logger:
    """
    Set up and returns a logger with specified formatting and handlers.

    If you work with a package which implements the Python's standard logging module you
    can provide the namespace of that package's logging. (e.g., "sqlalchemy.engine",
    "sqlalchemy.pool" etc.)
    If you create several loggers the "mode" might interfere.

    Parameters
    ----------
    stream_logger: dict. The valid keys and values are:
        - active: bool
        - level: str. The logging level for the stream logger. Must be one of: "DEBUG",
            "INFO", "WARNING", "ERROR", "CRITICAL".

    file_logger: dict. The valid keys are:
        - active: bool
        - level: str. The logging level for the file logger. Must be one of: "DEBUG",
            "INFO", "WARNING", "ERROR", "CRITICAL".
        - fname: str. The filename of the log file (without extension). Will be stored
            in logs/{fname}.log
        - mode: str. The file mode to use when opening the log file. Must be one of:
            "a" (append) or "w" (overwrite).

    logger_name: str, optional, default ""
        String that will be used as the name of the logger instance.

    Returns
    -------
    logging.Logger
        The logger object.
    """
    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - Line#: %(lineno)d in Function: %(funcName)s - Message: %(message)s",
        "%d.%m.%Y %H:%M:%S",
    )
    logger = logging.getLogger(logger_name)
    logger.setLevel(
        "DEBUG"
    )  # Leave this set to DEBUG, otherwise it will cut off the logging level of the handlers

    valid_levels = ("DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL")
    valid_modes = ("a", "w")

    if stream_logger["active"] and stream_logger["level"].upper() in valid_levels:
        stream_handler = logging.StreamHandler()
        stream_handler.setLevel((stream_logger["level"].upper()))
        stream_handler.setFormatter(formatter)
        logger.addHandler(stream_handler)
    elif not stream_logger["active"]:
        pass
    else:
        print("No valid logging level for stream")

    if (
        file_logger["active"]
        and file_logger["level"].upper() in valid_levels
        and file_logger["mode"].lower() in valid_modes
    ):
        file_handler = logging.FileHandler(
            filename=f"logs/{file_logger['fname']}.log",
            mode=file_logger["mode"].lower(),
        )
        file_handler.setLevel(file_logger["level"].upper())
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)
        os.makedirs(os.path.dirname(f"logs/{file_logger['fname']}.log"), exist_ok=True)
    elif not file_logger["active"]:
        pass
    else:
        print("No valid logging level or file mode.")
    return logger

1.在主文件中,导入logging_handler,访问该记录器并给予一些参数:

import logging_handler

logging = logging_handler.logger(
    stream_logger={"active": True, "level": "debug"},
    file_logger={
        "active": True,
        "level": "debug",
        "fname": "output",
        "mode": "a",
    },
    logger_name="smooLogger",
)

有关logging_handler.py中的参数,请参见说明。
现在你可以把日志记录语句放到你的代码中,比如:

logging.debug("Debug message")
logging.info("Info message")
logging.warning("Warning message")
logging.error("Error message")
logging.critical("Critical message")

结果如下所示:

13.04.2023 12:34:25 - DEBUG - Line#: 36 in Function: __init__ - Message: DB connection established and cursor created.

希望有帮助!

相关问题