programing

로깅 Python 모듈을 사용하여 파일에 쓰는 방법은 무엇입니까?

yoursource 2022. 9. 16. 21:12
반응형

로깅 Python 모듈을 사용하여 파일에 쓰는 방법은 무엇입니까?

Python의 로깅 모듈을 사용하여 파일에 쓰려면 어떻게 해야 합니까?사용하려고 할 때마다 메시지가 출력됩니다.

「」의 예logging.basicConfiglogging.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")

logger = logging.getLogger('urbanGUI')

5개의 파트는 순서대로 다음 작업을 수행합니다.

  1. 파일을filename=logname)
  2. filemode='a')
  3. 메시지 합니다.format=...)
  4. 시간의 을 datefmt='%H:%M:%S')
  5. 합니다(메시지레벨은 다음과 같습니다).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)

이제 가도 돼

추신: 로그 하우토도 꼭 읽어주세요.

다음은 로그(stdout)를 인쇄하는 경우와 파일에 로그를 쓰는 경우의 두 가지 예입니다.

import logging
import sys

logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')

stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.DEBUG)
stdout_handler.setFormatter(formatter)

file_handler = logging.FileHandler('logs.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)


logger.addHandler(file_handler)
logger.addHandler(stdout_handler)

이 예에서는 모든 로그가 인쇄되고 logs.log라는 이름의 파일에 기록됩니다.

사용 예:

logger.info('This is a log message!')
logger.error('This is an error message.')

내장된 모든 로깅 핸들러 목록 https://docs.python.org/3/library/logging.handlers.html

컨피규레이션파일을 사용하는 것을 선호합니다.개발에서 릴리스로 이동할 때 코드를 변경하지 않고 로깅 수준, 위치 등을 전환할 수 있습니다.같은 이름과 정의된 로거로 다른 설정 파일을 패키징하기만 하면 됩니다.

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+syslog 및 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

FileHandlerclass, core class에 되어 있습니다.logging출력을 에 송신합니다.

이 예에서는 정상적으로 동작합니다.콘솔용 스트림 핸들러를 추가했습니다.콘솔 로그 및 파일 핸들러 데이터는 유사해야 합니다.

    # MUTHUKUMAR_TIME_DATE.py #>>>>>>>> file name(module)

    import sys
    import logging
    import logging.config
    # ================== Logger ================================
    def Logger(file_name):
        formatter = logging.Formatter(fmt='%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s',
                                      datefmt='%Y/%m/%d %H:%M:%S') # %I:%M:%S %p AM|PM format
        logging.basicConfig(filename = '%s.log' %(file_name),format= '%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s',
                                      datefmt='%Y/%m/%d %H:%M:%S', filemode = 'w', level = logging.INFO)
        log_obj = logging.getLogger()
        log_obj.setLevel(logging.DEBUG)
        # log_obj = logging.getLogger().addHandler(logging.StreamHandler())

        # console printer
        screen_handler = logging.StreamHandler(stream=sys.stdout) #stream=sys.stdout is similar to normal print
        screen_handler.setFormatter(formatter)
        logging.getLogger().addHandler(screen_handler)

        log_obj.info("Logger object created successfully..")
        return log_obj
    # =======================================================


MUTHUKUMAR_LOGGING_CHECK.py #>>>>>>>>>>> file name
# calling **Logger** function
file_name = 'muthu'
log_obj =Logger(file_name)
log_obj.info("yes   hfghghg ghgfh".format())
log_obj.critical("CRIC".format())
log_obj.error("ERR".format())
log_obj.warning("WARN".format())
log_obj.debug("debug".format())
log_obj.info("qwerty".format())
log_obj.info("asdfghjkl".format())
log_obj.info("zxcvbnm".format())
# closing file
log_obj.handlers.clear()

OUTPUT:
2019/07/13 23:54:40 MUTHUKUMAR_TIME_DATE,line: 17     INFO | Logger object created successfully..
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 8     INFO | yes   hfghghg ghgfh
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 9 CRITICAL | CRIC
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 10    ERROR | ERR
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 11  WARNING | WARN
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 12    DEBUG | debug
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 13     INFO | qwerty
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 14     INFO | asdfghjkl
2019/07/13 23:54:40 MUTHUKUMAR_LOGGING_CHECK,line: 15     INFO | zxcvbnm

Thanks, 
import logging

from datetime import datetime

filename = datetime.now().strftime("%d-%m-%Y %H-%M-%S")#Setting the filename from current date and time
logging.basicConfig(filename=filename, filemode='a',
                    format="%(asctime)s, %(msecs)d %(name)s %(levelname)s [ %(filename)s-%(module)s-%(lineno)d ]  : %(message)s",
                    datefmt="%H:%M:%S",
                    level=logging.DEBUG)
  • asctime

    %(시간)초

    LogRecord가 작성된 시각.기본적으로는 '2003-07-08 16:49:45,896' 형식입니다(쉼표 뒤의 숫자는 시간의 밀리초 부분임).

  • 창조했다

    %(작성)f

    LogRecord가 생성된 시각(time.time()에 의해 반환됨).

  • exc_info

    직접 포맷할 필요는 없습니다.

    예외 태플(일명 시스템).exc_info) 또는 예외가 발생하지 않은 경우 [None]를 선택합니다.

  • 파일명

    %(표준)s

    패스명의 파일명 부분.

  • 기능명

    %(funcName)s

    로깅 콜을 포함하는 함수 이름.

  • 레벨명

    %(레벨명)s

    메시지의 텍스트 로깅 수준('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITIAL').

  • 레벨 번호

    %(레벨 번호)초

    메시지의 수치 로깅 수준(DEBUG, INFO, WARNING, ERROR, CRITIAL).

  • 리네노

    %(lineno)d

    로깅 콜이 발행된 소스 회선 번호(사용 가능한 경우).

  • 메세지

    %(메시지)s

    로그 메시지(msg % args로 계산).이것은 Formatter에서 설정됩니다.format()이 호출됩니다.

  • 모듈

    %(표준)s

    모듈(파일명의 이름 부분).

  • 밀리초

    %(밀리초)d

    LogRecord가 생성된 시간의 밀리초 단위.

  • 메시지

    직접 포맷할 필요는 없습니다.

    원래 로깅 호출로 전달된 형식 문자열입니다.메시지를 생성하기 위해 arg 또는 임의 개체와 병합됨(임의 개체를 메시지로 사용 참조).

  • 이름.

    %(이름)s

    콜 로깅에 사용되는 로거 이름.

  • 패스명

    %(패스명)s

    로깅 콜이 발행된 소스 파일의 풀패스명(사용 가능한 경우).

  • 과정

    %(프로세스)d

    프로세스 ID(사용 가능한 경우).

  • 프로세스명

    %(프로세스명)s

    프로세스명(사용 가능한 경우).

  • relative Created

    %(relative Created)d

    LogRecord 생성 시 로깅모듈이 로드된 시간에 상대적인 밀리초 단위.

  • stack_info

    직접 포맷할 필요는 없습니다.

    현재 스레드의 스택 하단에서 이 레코드를 작성한 로깅콜의 스택프레임까지 스택프레임 정보(사용 가능한 경우).

  • %(표준)d

    스레드 ID(사용 가능한 경우).

  • 스레드명

    %(스레드명)s

    스레드 이름(사용 가능한 경우).

로깅에 대한 자세한 내용은 공식 python3 페이지로 이동하십시오.

import sys
import logging

from util import reducer_logfile
logging.basicConfig(filename=reducer_logfile, format='%(message)s',
                    level=logging.INFO, filemode='w')

오래된 질문이지만, 요즘 이 질문을 받고 있는 사람에게는 dictConfig를 사용할 수도 있습니다.예를 들어 info level 이상의 파일의 경우:

logging.config.dictConfig({
    'version': 1,
    'formatters': {
        'default': {
            'format': '[%(asctime)s] %(message)s',
        }
    },
    'handlers': {
        'info': {
            'level': logging.INFO,
            'class': 'logging.FileHandler',
            'filename': 'info.log',
        },
    },
    "root": {
        "level": logging.INFO,
        "handlers": ["info"]
    }
})

또는, 보다 구체적인 예를 들면, 회전하는 파일과 특정의 디렉토리에 있습니다.

today = datetime.date.today()
folder = './log'
Path(folder).mkdir(parents=True, exist_ok=False) # Create folder if not exists
logging.config.dictConfig({
        ...
        'info': {
            'level': logging.INFO,
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': f'{folder}/info-{today.month:02}-{today.year}.log',
            # Roll over on the first day of the weekday
            'when': 'W0',
            # Roll over at midnight
            'atTime': datetime.time(hour=0),
            # Number of files to keep.
            'backupCount': 8
        },
        ...

최선의 깨끗한 방법.

    ds = datetime.now().strftime("%Y%m%d_%H%M%S")
    try:
        # py39 有force参数指定可能强制除去之前的handler,这里使用兼容写法,0708
        logging.getLogger().removeHandler(logging.getLogger().handlers[0])
        logging.getLogger().removeHandler(logging.getLogger().handlers[0])
    except:
        pass
    logging.basicConfig(
        # force=
        level=logging.INFO,
        format="%(asctime)s [%(levelname)s] %(message)s",
        handlers=[
            logging.FileHandler('log_%s_%s_%s.log' % (ds, create_net, os.path.basename(dataset_path))),
            logging.StreamHandler(sys.stdout)
        ]
    )
    logging.info('start train')

언급URL : https://stackoverflow.com/questions/6386698/how-to-write-to-a-file-using-the-logging-python-module

반응형