亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

調用另一個模塊時顯示原始模塊的名稱

調用另一個模塊時顯示原始模塊的名稱

千萬里不及你 2022-07-19 10:36:35
我正在創建集中式日志記錄。這基本上看起來像下面的腳本。logit 模塊將根據調用它的腳本名稱創建一個文件。在這種情況下 apiCaller。最初我在調用 logit 時手動定義了這個,但是我正在尋找 logit 以確定日志本身的來源。這里有 3 個模塊在起作用:main.py:def runAnalytic(script):    importlib.import_module("monitoringScripts."+script["package"]+"."+script["module"], package=None)packageModule = [{"package":"awesome","module":"apiCaller"}]with concurrent.futures.ThreadPoolExecutor() as executor:    results = executor.map(runAnalytic, packageModule)apiCaller.py(上面的模塊)from adminTools.logger import logitlogit.create(results[i]["items"][r]["userId"],"apiCaller") #How i currently pass the script name, i want to get rid of this.logit.py 處理我所有其他腳本的所有日志要求(集中式日志記錄)import sys, logging, logging.handlers, pathlib#Path for all log files for scriptHublogdir = str(pathlib.Path(__file__).parent.absolute())#Creates the log file based on a given name from the scriptdef create(logMessage,scriptName, level="DEBUG"):    #create filename    log_filename = logdir+"/sysLogs/"+scriptName+".logs"    #Creates the logging object    my_logger = logging.getLogger(scriptName)    my_logger.setLevel(logging.DEBUG)    #Formats the log:    formatter = logging.Formatter('%(asctime)s - %(message)s - %(name)s')    #Gives the log file a limit for 100mb if it goes bigger than this, it will create another file, but keep the old one    handler = logging.handlers.RotatingFileHandler(log_filename, maxBytes=100000000, backupCount=1)    handler.setFormatter(formatter)    #Handlers need to be cleared to stop duplicated logs.    if (my_logger.hasHandlers()):        my_logger.handlers.clear()    my_logger.addHandler(handler)    #creates the log message    my_logger.debug(logMessage)所以,我不確定這是否會幫助或阻礙你們所有人哈哈本質上,我不想為 logit 提供腳本名稱,而是希望 logit 從調用它的模塊中獲取它。例如,在這種情況下,“apiCaller”將是傳遞給 logit 的名稱。
查看完整描述

2 回答

?
胡子哥哥

TA貢獻1825條經驗 獲得超6個贊

這個問題不是很清楚,但你可以使用inspect.stack().


loggy.py

import inspect


def log(s):

    caller = inspect.stack()[1]

    print(f"{caller.filename} line {caller.lineno} says: {s}")

thing.py

import loggy


loggy.log("Hey!")

/v/f/n/8/T/tmp.ZiRzgsqi $ python3 thing.py

thing.py line 3 says: Hey!

/v/f/n/8/T/tmp.ZiRzgsqi $


查看完整回答
反對 回復 2022-07-19
?
慕無忌1623718

TA貢獻1744條經驗 獲得超4個贊

好的,重寫后的問題:


我已經看到它以與您相反的方式完成 - 獲取一個記錄器,然后設置它(模塊中有兩行,而不是一個)。記錄器是每個模塊的東西,并且總是在那里。


在您的情況下,您每次都重新獲取記錄器并重新制作處理程序。


這樣你就不能利用美麗的可能性logging模塊提供!


所以基本上,另一種方法是:


在您執行的每個腳本中logger = logging.getLogger(__name__),通常在頂部附近的某個地方,在導入下方。


+你只需打電話logit.setupLogger(logger)。(在你的情況下,在下一行。如果是腳本,我將它保存在 main 函數中 - 這樣,如果我將腳本作為模塊導入,我將調用我需要的任何日志記錄設置,imported_module.logger這樣它就不會向錯誤的日志文件。:D)


重寫logit.py:


import sys, logging, logging.handlers, pathlib

#Path for all log files for scriptHub

logdir = str(pathlib.Path(__file__).parent.absolute())


#Creates the log file based on a given name from the script

def create(my_logger, level=logging.DEBUG):

    #create filename

    log_filename = logdir+"/sysLogs/"+logger.name+".logs"


    my_logger.setLevel(level)

    #Formats the log:

    formatter = logging.Formatter('%(asctime)s - %(message)s - %(name)s')

    #Gives the log file a limit for 100mb if it goes bigger than this, it will create another file, but keep the old one

    handler = logging.handlers.RotatingFileHandler(log_filename, maxBytes=100000000, backupCount=1)

    handler.setFormatter(formatter)

    #Handlers need to be cleared to stop duplicated logs.

    if (my_logger.hasHandlers()):

        my_logger.handlers.clear()

    my_logger.addHandler(handler)

這樣,您只需在 中設置記錄器的內部 - 包括文件處理程序 - logit,您可以使用標準的logging東西:


您可以在模塊中使用任何級別的日志記錄:

logger.info("like")

logger.warning("this")

您在上面的代碼中編寫每條日志消息 - 使代碼充滿日志消息!- 請記住調試消息應該包含調試所需的一切,這有時包括大量信息 + 請記住調試消息可能存在于信息消息旁邊,只是具有不同的詳細信息(例如,“從 X 獲取信息”是信息,“已發送請求” some/address/here' 并收到 '''這里的數據塊'''" 是調試)。

當您需要降低級別時 - 例如,您調試了您的消息并且厭倦了看到 so.much.info (或者只是從開發人員到生產人員) - 您只需更改logit.setupLogger(logger)到logit.setupLogger(logger, logging.INFO)您需要的任何級別。

日志記錄似乎是一個好主意,但是logging當您學習如何使用它時,模塊非常強大。:)這是來自 Python 文檔的 How-To,但它包含很多信息,因此更簡單的有關 python 日志記錄的教程是更好的開始。


即使在閱讀了文檔和教程之后,我也開始使用自己的日志記錄實踐,因為我根本沒有得到它。當我看到它在我正在使用的庫中使用時,我才切換到上面的方法。:)


查看完整回答
反對 回復 2022-07-19
  • 2 回答
  • 0 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號