파이썬에서는 콘솔에 로그를 쓸 수 있지만 파일에는 기록되지 않습니다. (In python I can write a log to console but its not getting written into file)


문제 설명

파이썬에서는 콘솔에 로그를 쓸 수 있지만 파일에는 기록되지 않습니다. (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 .logfile. So try changing the extension of file from txt to log

(by Kishore Kumarpositive.definiteBhavinT)

참조 문서

  1. In python I can write a log to console but its not getting written into file (CC BY‑SA 2.5/3.0/4.0)

#Python #python-logging #logging






관련 질문

Python - 파일 이름에 특수 문자가 있는 파일의 이름을 바꿀 수 없습니다. (Python - Unable to rename a file with special characters in the file name)

구조화된 배열의 dtype을 변경하면 문자열 데이터가 0이 됩니다. (Changing dtype of structured array zeros out string data)

목록 목록의 효과적인 구현 (Effective implementation of list of lists)

for 루프를 중단하지 않고 if 문을 중지하고 다른 if에 영향을 줍니다. (Stop if statement without breaking for loop and affect other ifs)

기본 숫자를 10 ^ 9 이상으로 늘리면 코드가 작동하지 않습니다. (Code fails to work when i increase the base numbers to anything over 10 ^ 9)

사용자 지정 대화 상자 PyQT5를 닫고 데이터 가져오기 (Close and get data from a custom dialog PyQT5)

Enthought Canopy의 Python: csv 파일 조작 (Python in Enthought Canopy: manipulating csv files)

학생의 이름을 인쇄하려고 하는 것이 잘못된 것은 무엇입니까? (What is wrong with trying to print the name of the student?)

다단계 열 테이블에 부분합 열 추가 (Adding a subtotal column to a multilevel column table)

여러 함수의 변수를 다른 함수로 사용 (Use variables from multiple functions into another function)

리프 텐서의 값을 업데이트하는 적절한 방법은 무엇입니까(예: 경사하강법 업데이트 단계 중) (What's the proper way to update a leaf tensor's values (e.g. during the update step of gradient descent))

Boto3: 조직 단위의 AMI에 시작 권한을 추가하려고 하면 ParamValidationError가 발생합니다. (Boto3: trying to add launch permission to AMI for an organizational unit raises ParamValidationError)







코멘트