이 코드는 로그 파일과 콘솔에 동시에 기록합니까?동시에 로그 파일과 콘솔에 로그 메시지를 쓰려면 어떻게합니까?
logFile = open("logfile.log",a)
print >>logFile,message
logFile.close()
이 코드는 로그 파일과 콘솔에 동시에 기록합니까?동시에 로그 파일과 콘솔에 로그 메시지를 쓰려면 어떻게합니까?
logFile = open("logfile.log",a)
print >>logFile,message
logFile.close()
아니요, 둘 다 쓰지는 않습니다. print()
은 콘솔에만 씁니다. 원래 코드에 대한 간단한 노트. 나는 당신이 어딘가에 message
을 정의한다고 생각하지만, 코드는 여전히 올바르지 않습니다. 이처럼 open
문에서 a
따옴표가 필요합니다
open("logfile.log", "a")
난 당신이 파일에 추가하는 것을 의미 추정하기 때문이다. 그렇지 않으면 a
이 정의 된 변수가 아니기 때문에 코드는 NameError
을 던집니다.
그러나 다른 사람들이 말했듯이 logging 모듈을 사용하는 것이 좋습니다. 다음은 콘솔과 로그 파일 모두에 쓰는 간단한 예제입니다. 코드는 부분적으로 here 및 here에서 파생 : 로거 객체는 하나 이상의 핸들러를 가질 수
import inspect
import logging
def function_logger(file_level, console_level = None):
function_name = inspect.stack()[1][3]
logger = logging.getLogger(function_name)
logger.setLevel(logging.DEBUG) #By default, logs all messages
if console_level != None:
ch = logging.StreamHandler() #StreamHandler logs to console
ch.setLevel(console_level)
ch_format = logging.Formatter('%(asctime)s - %(message)s')
ch.setFormatter(ch_format)
logger.addHandler(ch)
fh = logging.FileHandler("{0}.log".format(function_name))
fh.setLevel(file_level)
fh_format = logging.Formatter('%(asctime)s - %(lineno)d - %(levelname)-8s - %(message)s')
fh.setFormatter(fh_format)
logger.addHandler(fh)
return logger
def f1():
f1_logger = function_logger(logging.DEBUG, logging.ERROR)
f1_logger.debug('debug message')
f1_logger.info('info message')
f1_logger.warn('warn message')
f1_logger.error('error message')
f1_logger.critical('critical message')
def f2():
f2_logger = function_logger(logging.WARNING)
f2_logger.debug('debug message')
f2_logger.info('info message')
f2_logger.warn('warn message')
f2_logger.error('error message')
f2_logger.critical('critical message')
def main():
f1()
f2()
logging.shutdown()
main()
때문에, 우리는 다른 장소에 쓰기 여러 핸들러를 만들 수 있습니다. 내 코드에서 function_logger
함수는 호출 된 함수에 특정한 로거 객체를 만듭니다.
기능 f1()
로그 각각에 대해 서로 다른 서식 ERROR
수준 메시지를 작성하는 동안 위의 콘솔에 파일 f1.log
에 DEBUG
수준의 메시지와 위.
그러나 기능 f2()
은 콘솔에 아무 것도 기록하지 않고 WARNING
레벨 메시지 만 로그 파일 f2.log
에 기록합니다.
2012-07-20 10:46:38,950 - f1 - error message
2012-07-20 10:46:38,953 - f1 - critical message
및 f1.log
및 f2.log
에서이 출력, 각각 : 콘솔에서이 출력 한 번이 스크립트를 산출 실행
f1.log :
2012-07-20 10:46:38,950 - 26 - DEBUG - debug message
2012-07-20 10:46:38,950 - 27 - INFO - info message
2012-07-20 10:46:38,950 - 28 - WARNING - warn message
2012-07-20 10:46:38,950 - 29 - ERROR - error message
2012-07-20 10:46:38,953 - 30 - CRITICAL - critical message
f2.log
2012-07-20 10:46:38,960 - 36 - WARNING - warn message
2012-07-20 10:46:38,960 - 37 - ERROR - error message
2012-07-20 10:46:38,960 - 38 - CRITICAL - critical message
의 첫 번째 예를 참조하십시오. 한 가지 세부 정보 : Py27부터는 "logger.setLevel (logging.DEBUG)"행이 모든 메시지를 기록합니다. " 필수적이다. 이를 사용하지 않으면 핸들러에 대한 setLevel() 호출이 작동하지 않습니다. 세부 수준은 logging.warning에서 잠길 수 있습니다. – kakyo
아니요. 파일에만 씁니다. logging
모듈을 사용해야합니다. http://docs.python.org/library/logging.html
시도했을 때 무엇을 했는가 .... – avasal
가능한 여러 핸들러를 사용. 하나는 파일 처리 (logging.FileHandler ('mylog.log')')이고 다른 하나는 콘솔 처리 ('logging.StreamHandler()')입니다. https://docs.python.org/2/howto/logging-cookbook.html –