[英]Python logging using modules
我有多個模塊,由主腳本調用。 每個都使用 package 內置的日志記錄 Python 記錄消息。
如何在所有模塊中記錄在主腳本執行期間設置的 session ID,而無需在每個模塊中推送此變量?
我設置了一個名為 config 的 python 配置文件,其中包含:
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(filename)s:%(lineno)s|%(funcName)3s()|%(asctime)s|%(levelname)s|%(message)s",
handlers=[
logging.FileHandler("debug.log"),
logging.StreamHandler()
]
)
其他模塊正在使用這個預先配置的日志記錄 object,通過導入,所以我使用這個:
from config import logging
但是我需要從我當前的 session 中記錄一個 ID,我的日志應該如下所示:
模塊名稱.py:25|函數名稱()|2020-04-27 18:28:26,518|信息| Session_ID=abc123 |some_message_here
I have tried to put this variable in the config file, set it, and then use it in a function named "log_info" and "log_debug" in this file, but my output log does not trace python script name and function name any more.
有誰知道如何處理這種情況?
我不知道這是否是 100% 最好的解決方案,或者確定它是否適用於您的情況,但我將它用於類似的事情(在多個腳本中持續存在的冗長打印級別)。
創建一個 Python 文件,命名為sessionid
。 在其中,定義一個名為id
的頂級設置。 要設置您的 id,請import sessionid
和sessionid.id = 'some_id'
。 然后讓您的config
文件也導入sessionid
並根據需要使用sessionid.id
。
我花了一點時間才發現我必須像那樣訪問它; 使用from sessionid import id; id = 'some_id'
from sessionid import id; id = 'some_id'
僅保留在執行此操作的腳本中。
將id
變量放在config
文件中是有意義的,但前提是您不需要將其設置在同樣需要from config import logging
的腳本中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.