Python 의 로깅 모듈을 사용하여 파일에 쓰는 방법은 무엇입니까? 내가 그것을 사용하려고 할 때마다 메시지를 인쇄합니다.
답변
logging.basicConfig
대신 사용의 예logging.fileHandler()
logging.basicConfig(filename=logname,
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.DEBUG)
logging.info("Running Urban Planning")
self.logger = logging.getLogger('urbanGUI')
순서대로 다섯 부분은 다음을 수행합니다.
- 출력 파일 설정 (
filename=logname
) - 덮어 쓰지 않고 추가하도록 설정 (
filemode='a'
) - 출력 메시지의 형식 결정 (
format=...
) - 출력 시간 형식 결정 (
datefmt='%H:%M:%S'
) - 수락 할 최소 메시지 수준을 결정합니다 (
level=logging.DEBUG
).
답변
# create logger with 'spam_application'
logger = logging.getLogger('spam_application')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
logger.addHandler(fh)
그리고 당신은 갈 수 있습니다.
추신 로깅 하우투 도 읽으십시오 .
답변
구성 파일을 선호합니다. 개발에서 릴리스로 이동할 때 코드를 변경하지 않고도 로깅 수준, 위치 등을 전환 할 수 있습니다. 동일한 이름과 동일한 정의 된 로거를 사용하여 다른 구성 파일을 단순히 패키지화합니다.
import logging.config
if __name__ == '__main__':
# Configure the logger
# loggerConfigFileName: The name and path of your configuration file
logging.config.fileConfig(path.normpath(loggerConfigFileName))
# Create the logger
# Admin_Client: The name of a logger defined in the config file
mylogger = logging.getLogger('Admin_Client')
msg='Bite Me'
myLogger.debug(msg)
myLogger.info(msg)
myLogger.warn(msg)
myLogger.error(msg)
myLogger.critical(msg)
# Shut down the logger
logging.shutdown()
다음은 로그 구성 파일의 코드입니다.
#These are the loggers that are available from the code
#Each logger requires a handler, but can have more than one
[loggers]
keys=root,Admin_Client
#Each handler requires a single formatter
[handlers]
keys=fileHandler, consoleHandler
[formatters]
keys=logFormatter, consoleFormatter
[logger_root]
level=DEBUG
handlers=fileHandler
[logger_Admin_Client]
level=DEBUG
handlers=fileHandler, consoleHandler
qualname=Admin_Client
#propagate=0 Does not pass messages to ancestor loggers(root)
propagate=0
# Do not use a console logger when running scripts from a bat file without a console
# because it hangs!
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=consoleFormatter
args=(sys.stdout,)# The comma is correct, because the parser is looking for args
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=logFormatter
# This causes a new file to be created for each script
# Change time.strftime("%Y%m%d%H%M%S") to time.strftime("%Y%m%d")
# And only one log per day will be created. All messages will be amended to it.
args=("D:\\Logs\\PyLogs\\" + time.strftime("%Y%m%d%H%M%S")+'.log', 'a')
[formatter_logFormatter]
#name is the name of the logger root or Admin_Client
#levelname is the log message level debug, warn, ect
#lineno is the line number from where the call to log is made
#04d is simple formatting to ensure there are four numeric places with leading zeros
#4s would work as well, but would simply pad the string with leading spaces, right justify
#-4s would work as well, but would simply pad the string with trailing spaces, left justify
#filename is the file name from where the call to log is made
#funcName is the method name from where the call to log is made
#format=%(asctime)s | %(lineno)d | %(message)s
#format=%(asctime)s | %(name)s | %(levelname)s | %(message)s
#format=%(asctime)s | %(name)s | %(module)s-%(lineno) | %(levelname)s | %(message)s
#format=%(asctime)s | %(name)s | %(module)s-%(lineno)04d | %(levelname)s | %(message)s
#format=%(asctime)s | %(name)s | %(module)s-%(lineno)4s | %(levelname)-8s | %(message)s
format=%(asctime)s | %(levelname)-8s | %(lineno)04d | %(message)s
#Use a separate formatter for the console if you want
[formatter_consoleFormatter]
format=%(asctime)s | %(levelname)-8s | %(filename)s-%(funcName)s-%(lineno)04d | %(message)s
답변
http://docs.python.org/library/logging.html#logging.basicConfig
logging.basicConfig(filename='/path/to/your/log', level=....)
답변
여기에 더 간단한 방법이 있습니다. 이 솔루션은 구성 사전을 사용하지 않고 다음과 같이 회전 파일 처리기를 사용합니다.
import logging
from logging.handlers import RotatingFileHandler
logging.basicConfig(handlers=[RotatingFileHandler(filename=logpath+filename,
mode='w', maxBytes=512000, backupCount=4)], level=debug_level,
format='%(levelname)s %(asctime)s %(message)s',
datefmt='%m/%d/%Y%I:%M:%S %p')
logger = logging.getLogger('my_logger')
또는 그렇게 :
import logging
from logging.handlers import RotatingFileHandler
handlers = [
RotatingFileHandler(filename=logpath+filename, mode='w', maxBytes=512000,
backupCount=4)
]
logging.basicConfig(handlers=handlers, level=debug_level,
format='%(levelname)s %(asctime)s %(message)s',
datefmt='%m/%d/%Y%I:%M:%S %p')
logger = logging.getLogger('my_logger')
핸들러 변수는 반복 가능해야합니다. logpath + filename 및 debug_level은 해당 정보를 보유하는 변수 일뿐입니다. 물론 함수 매개 변수의 값은 귀하에게 달려 있습니다.
로깅 모듈을 처음 사용했을 때 OS 파일 잠금 오류가 발생하는 다음을 작성하는 실수를 저질렀습니다 (위가 이에 대한 해결책입니다).
import logging
from logging.handlers import RotatingFileHandler
logging.basicConfig(filename=logpath+filename, level=debug_level, format='%(levelname)s %(asctime)s %(message)s', datefmt='%m/%d/%Y
%I:%M:%S %p')
logger = logging.getLogger('my_logger')
logger.addHandler(RotatingFileHandler(filename=logpath+filename, mode='w',
maxBytes=512000, backupCount=4))
그리고 밥은 당신의 삼촌입니다!
답변
http://docs.python.org/library/logging.handlers.html#filehandler
FileHandler
핵심에있는 클래스,logging
패키지는 디스크 파일에 로그 출력을 보냅니다.
답변
import sys
import logging
from util import reducer_logfile
logging.basicConfig(filename=reducer_logfile, format='%(message)s',
level=logging.INFO, filemode='w')
