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条答案
按热度按时间mmvthczy1#
我还希望在运行python脚本时在控制台中进行日志记录,但也希望将其保存在日志文件中以供以后或并行引用。此外,我希望能够为控制台和文件设置不同级别的输出。例如,在文件中,我希望具有所有级别(DEBUG,INFO,WARNING,ERROR,CRITICAL),但在终端中我只想有WARNING,ERROR,CRITICAL。此外,我想改变,如果我追加到日志文件,或覆盖它。
1.创建一个文件,并将其命名为
logging_handler.py
,例如包含以下内容:1.在主文件中,导入
logging_handler
,访问该记录器并给予一些参数:有关
logging_handler.py
中的参数,请参见说明。现在你可以把日志记录语句放到你的代码中,比如:
结果如下所示:
希望有帮助!