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



我想把我的python程序输出保存在一个日志文件中,并且仍然能够在控制台中看到它。

我的程序每30分钟运行一次,30分钟后我的程序进程被杀死,我的批处理文件强制关闭它。

因此,我不能使用显示我的程序输出并将其保存到程序末尾的日志文件的解决方案,因为没有"结束",因为它在运行时中间被BTACH文件杀死。

有任何解决方案,将能够显示我的程序输出,并把它写到日志文件?并且,即使我将终止进程(和程序),我将得到所有的输出,直到它被终止到日志文件?

我还希望在运行python脚本时在控制台中进行日志记录,但也希望将其保存在日志文件中以供以后或并行参考。此外,我希望能够为控制台和文件设置不同级别的输出。例如,在文件中,我想拥有所有级别(DEBUG, INFO, WARNING, ERROR, CRITICAL),但在终端中,我只想拥有WARNING, ERROR, CRITICAL。此外,如果我附加到日志文件,或者覆盖它,我想更改。

  1. 创建一个文件,命名为logging_handler.py,例如,内容如下:
import logging
from pathlib import Path

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
):
Path("logs").mkdir(parents=True, exist_ok=True)
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)
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.

希望有帮助!

最新更新