以最简单的方式记录多个 modules/functions 不同格式

Logging multiple modules/functions with different formats in the simplest way

我有 4 个函数:
main.py
处理程序
func1.py
func2.py
func3.py
我想用一些独特的格式记录每个函数异常;例如我在 main.py

中有下面的 logging
import logging
from Handlers.func1 import firstfunc

logging.basicConfig(level=logging.WARNING, filename='./main.log', filemode='a+', encoding='utf-8',
format=f"{''*50}\n %(asctime)s  ⚠ #%(levelname)s   %(message)s",
datefmt='%Y-%m-%d %H:%M:%S')

def main(param):
    try:
        mainvar = firstfunc(param)
    except Exception as e:
        logging.exception(e)
    ...

我想为每个函数(func1.py)创建另一个像上面 3 行代码一样简单的日志记录,保存到相同的文件(我知道这可能是不可能的,但我不知道为什么!)

import logging
from Handlers.func2 import secondfunc

logging.basicConfig(level=logging.INFO, filename='./main.log', filemode='a+', encoding='utf-8',
format=f"{''*50}\n⚠ #%(levelname)s  %(message)s")

def firstfunc(fpar):
    try:
        firstvar = secondfunc(sfunc)
    except Exception as e:
        logging.exception(e)
    ...

是否可以像调用 logging.basicConfig 一样简单地做到这一点?
如果不是,我如何编写 logger 来做同样的事情?
最终输出应该是这样的:

basicConfig实例化不像
loggerFunc1 = logging.basicConfig(level=logging.WARNING)...
那么简单 但是,可以通过将 fh 定义为 FileHandler 并将其作为列表元素传递给 handlers 函数来记录,如下所示:

func1.py

# Should be added to each file (include main.py).
import logging
from pathlib import Path

# Gets the Absolute path of the main.log
LogFileAPath = Path('./main.log').resolve()
fh = logging.FileHandler(LogFileAPath, encoding='utf-8')
logging.basicConfig(
    level=logging.INFO,
    format=f"\n{''*50}\n%(asctime)s  ⚠ #%(levelname)s   %(message)s",
    datefmt='%Y-%m-%d %H:%M:%S',
    handlers=[fh]
    )
# use __name__ to automatically detect the module name, or any optional string.
logger = logging.getLogger(__name__)
# Stop getting duplicate logs from both functions
logger.propagate = False
#

def firstfunc(fpar):
    try:
        firstvar = secondfunc(sfunc)
    except Exception as e:
        logger.exception(e)
    ...

或者您应该在 main.py...

中仅使用一个 basicConfig 在每个文件中添加记录器

main.py

import logging

logging.basicConfig(
    level=logging.WARNING,
    filename='./main.log',
    filemode='a+',
    encoding='utf-8',
    format=f"\n{''*50}\n %(asctime)s  ⚠ #%(levelname)s   %(message)s",
    datefmt='%Y-%m-%d %H:%M:%S')

func1.py

# Should be added to each function file.
import logging
from pathlib import Path

# Gets the Absolute path of the main.log
LogFileAPath = Path('./main.log').resolve()
fh = logging.FileHandler(LogFileAPath, encoding='utf-8')
fh.setLevel(logging.INFO)
formatter = logging.Formatter(f"{''*50}\n⚠ #%(levelname)s  %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
logger = logging.getLogger(__name__)
# Prevents getting duplicate logs
logger.propagate = False
#

def firstfunc(fpar):
    try:
        firstvar = secondfunc(sfunc)
    except Exception as e:
        logger.exception(e)
    ...

func2.py

import logging
from pathlib import Path

LogFileAPath = Path('./main.log').resolve()
fh = logging.FileHandler(LogFileAPath, encoding='utf-8')
fh.setLevel(logging.INFO)
formatter = logging.Formatter(f"{''*50}\n⚠ #%(levelname)s  %(message)s")
fh.setFormatter(formatter)
logger.addHandler(fh)
logger = logging.getLogger(__name__)
logger.propagate = False

def secondfunc(spar):
    try:
        secondvar = thirdfunc(tfunc)
    except Exception as e:
        logger.exception(e)
    ...

注意文件目录,如果你的main.pyHandlers文件夹之外,你应该在FileHandler中使用./main.log ,如果您在 Handlers 文件夹中定义日志文件,则应使用 ../main.log,(⭐:使用 Path().resolve())。否则你将在两个不同的目录中有两个单独的日志文件。