python - How to log for each script using logging (python)
问题描述
Im having an issue where currently I use two loggings where each script has its own logging. I have even used filename="Test1/Logs/hello.txt
and Test2 for second script so the filename is seperated. My problem is that whenever I run a script, it saves only to one folder and in my case is Test1. It doesn't never logs into Test2 folder even though I run test2.py script which should save to the Test2 folder logs.
What I have done is:
# -------------------------------------------------------------------------
# CLASS A
# -------------------------------------------------------------------------
logging.basicConfig(
filename='{}{}.txt'.format(/Test1/Logs, datetime.now().strftime("%a %d %B %Y %H_%M_%S")),
filemode='a',
level=logging.INFO,
format='[%(asctime)s]:%(levelname)s:%(funcName)s - %(message)s',
datefmt=datetime.now().strftime("%H:%M:%S.%f")[:-3]
)
loggingError = logging.getLogger()
logging.warning("Starting: {}".format(datetime.now().strftime("%a %d-%B-%Y %H:%M:%S")))
class A:
def __init__(self):
self.logging = loggingError
def aW1wb3J0RmlsZXM(self):
self.logging.error(sys.exc_info(), exc_info=True)
# -------------------------------------------------------------------------
# CLASS B
# -------------------------------------------------------------------------
logging.basicConfig(
filename='{}{}.txt'.format(/Test2/Logs, datetime.now().strftime("%a %d %B %Y %H_%M_%S")),
filemode='a',
level=logging.INFO,
format='[%(asctime)s]:%(levelname)s:%(funcName)s - %(message)s',
datefmt=datetime.now().strftime("%H:%M:%S.%f")[:-3]
)
loggingError = logging.getLogger()
logging.warning("Starting: {}".format(datetime.now().strftime("%a %d-%B-%Y %H:%M:%S")))
class B:
def __init__(self):
self.logging = loggingError
def aW1wb3J0RmlsZXM(self):
self.logging.error(sys.exc_info(), exc_info=True)
import A
import B
def main():
if True:
B.main()
break
if False:
A.main()
break
if __name__ == "__main__":
try:
main()
except Exception as e:
print(e)
as you can see the only difference between loggings are the folder name filename and yet even if I run Class B it still saves to Class A folder. What is the reason for that?
UPDATED TO EACH SCRIPT:
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('{}{}.txt'.format(logsPath, datetime.now().strftime("%a %d %B %Y %H_%M_%S")))
formatter = logging.Formatter('[%(asctime)s]:%(levelname)s:%(funcName)s - %(message)s', "%d-%m-%Y %H:%M:%S")
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.warning("Starting: {}".format(datetime.now().strftime("%a %d-%B-%Y %H:%M:%S")))
解决方案
This happens because when you import A
all the code inside of the file runs. Specifically the call to basicConfig
. The way this function works is that it only has an effect if logging is not configured already, otherwise it does nothing. So when you first import A
logging is configured, and the second call to basicConfig
in B doesn't have any effect.
This is documented well in the official python docs here.
Edit: File logging per module is easier done by doing something similar to this in each of the files:
import logging
local_logger = logging.getLogger(__name__)
local_logger.addHandler(logging.FileHandler('filename.log', 'a'))
local_logger.setLevel(logging.INFO)
推荐阅读
- hash - 是否有一个散列函数将相同间隔中的点分箱到相同的散列,所以我们可以在 O(1) 时间内识别包含间隔
- micro-frontend - 如何从 single-spa util 模块中导出功能并在 single-spa 微前端中导入相同的功能?
- java - OpenGL 不在 Mac M1 计算机上
- reactjs - 如何解决 TypeScript React Hook useState() 上的“预期 0 类型参数,但得到 1”错误?
- python-3.x - Tkinter:为什么它会带来一个从类中获取的空变量?
- python - .pop() 同时影响两个列表
- python - Pandas - 根据之前的行为进行插值
- debugging - 将 c# dll 引入 c++ dll 后,Visual Studio 2017 会跳过所有调试点
- python - EC2 实例未连接到互联网
- node.js - NodeJS CSV Parse 库删除 JSON 中的 "