문제 설명
파이썬에서는 콘솔에 로그를 쓸 수 있지만 파일에는 기록되지 않습니다. (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")
콘솔에서 이러한 모든 정보를 인쇄합니다. 파일에 기록된 적이 없습니다. 이 문제를 해결하는 데 도움을 주신 분들께 정말 감사드립니다. 아침부터 인터넷에서 검색하여 모든 가능성을 시도했지만 여전히 로그가 파일에 기록되지 않습니다
참조 솔루션
방법 1:
Create an new logger with desired stream & file handlers:
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)
And you're ready to take it for a spin:
print(logger.handlers)
logger.critical("critical")
logger.error("error")
logger.warning("warning")
logger.info("info")
logger.debug("debug")
With the following console output only showing WARNING and higher:
[<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
While test.log contains all levels:
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
The key is to understand how logging handlers work and checking whether they use correct levels (as in the code cells above, just print logger.handlers). Furthermore, overwriting basic configuration is a bad practice that can lead to problems when you run multiple loggers in the same python environment. I recommend this video, it sheds light on stream/file handlers in python logging.
방법 2:
I got this example from logging documentation
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')
and the examples that I have seen on the web they are all creating .log
file. So try changing the extension of file from txt to log
(by Kishore Kumar、positive.definite、BhavinT)