簡體   English   中英

在 python 中,我可以將日志寫入控制台,但沒有寫入文件

[英]In python I can write a log to console but its not getting written into file

import logging 
#Create and configure logger 
logging.basicConfig(filename="newfile.txt", format='%(asctime)s %(message)s',filemode='w') 
logging.debug("Harmless debug Message") 
logging.info("Just an information") 
logging.warning("Its a Warning") 
logging.error("Did you try to divide by zero") 
logging.critical("Internet is down") 

在控制台中打印所有這些信息。 它從未寫入文件。 真的很感謝那些幫助我解決這個問題的人。 從早上開始在互聯網上搜索嘗試了所有可能性,但日志仍然沒有寫入文件

使用所需的 stream 和文件處理程序創建一個新記錄器:

import logger, sys
logger = logging.Logger('AmazeballsLogger')
#Stream/console output
logger.handler = logging.StreamHandler(sys.stdout)
logger.handler.setLevel(logging.WARNING)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
logger.handler.setFormatter(formatter)
logger.addHandler(self.handler)
#File output
fh = logging.FileHandler("test.log")
fh.setLevel(logging.DEBUG)
fh.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
logger.addHandler(fh)

你已經准備好試一試了:

print(logger.handlers)

logger.critical("critical")
logger.error("error")
logger.warning("warning")
logger.info("info")
logger.debug("debug")

使用以下控制台 output 僅顯示 WARNING 及更高版本:

[<StreamHandler stdout (WARNING)>, <FileHandler C:\Users\...\test.log (DEBUG)>]
2020-04-13 17:52:57,729 - CRITICAL - critical
2020-04-13 17:52:57,731 - ERROR - error
2020-04-13 17:52:57,734 - WARNING - warning

雖然 test.log 包含所有級別:

2020-04-13 17:52:57,729 - AmazeballsLogger - CRITICAL - critical
2020-04-13 17:52:57,731 - AmazeballsLogger - ERROR - error
2020-04-13 17:52:57,734 - AmazeballsLogger - WARNING - warning
2020-04-13 17:52:57,736 - AmazeballsLogger - INFO - info
2020-04-13 17:52:57,736 - AmazeballsLogger - DEBUG - debug

關鍵是要了解日志處理程序如何工作並檢查它們是否使用正確的級別(如上面的代碼單元中,只需打印 logger.handlers)。 此外,覆蓋基本配置是一種不好的做法,當您在同一個 python 環境中運行多個記錄器時,可能會導致問題。 我推薦這個視頻,它揭示了 python 日志記錄中的流/文件處理程序。

我從日志記錄文檔中得到了這個例子

import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename='myapp.log',
                    filemode='w')
logging.debug('A debug message')
logging.info('Some information')
logging.warning('A shot across the bows')

以及我在 web 上看到的示例它們都在創建.log文件。 所以嘗試將文件的擴展名從txt更改為log

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM