programing

Python에서 로깅을 위한 타임스탬프 인쇄

starjava 2023. 8. 15. 09:40
반응형

Python에서 로깅을 위한 타임스탬프 인쇄

내 파이썬 스크립트에서 이벤트가 성공했는지 여부를 나타내는 현재 타임스탬프를 인쇄하고 싶습니다.추가하기만 하면...

datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")

각 라인의 시작 부분에 모든 라인에 동일한 날짜가 표시됩니다.

[INFO] 04.Feb 2015 20:49:41: cl1
[ OK ] 04.Feb 2015 20:49:41: 8.8.8.8 ONLINE!
[INFO] 04.Feb 2015 20:49:41: cl2
[ OK ] 04.Feb 2015 20:49:41: 8.8.8.8 ONLINE!
[INFO] 04.Feb 2015 20:49:41: cl3
[ OK ] 04.Feb 2015 20:49:41: 8.8.8.8 ONLINE!

(추가했습니다.time.sleep(5)중간에

제 다음 아이디어는 현재 시간을 호출하는 함수를 만드는 것이었지만, 이 함수를 다음에 포함시키는 데 실패했습니다.print지휘권

파일 rs.py

OK =   "[" + bc.OKGREEN + " OK "  + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
INFO = "[" + bc.OKBLUE  + "INFO"  + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
WARN = "[" + bc.WARN    + "WARN"  + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
ERR =  "[" + bc.ERR     + "FAIL"  + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
DEB =  "[" + bc.HEADER  + "DEBUG" + bc.ENDC + "] " + datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")

파일 myapp.py

import rs # importing rs.py

print rs.OK + hostname + "is up!"
time.sleep(3)
print rs.ERR+ hostname + "is down!"

인쇄 중:

>>> [INFO] 04.Feb 2015 20:49:41: xxx is up!
>>> [ERR ] 04.Feb 2015 20:49:41: xxx is down!

처음 기록하기 전에 다음 작업을 수행합니다.

logging.basicConfig(
    format='%(asctime)s %(levelname)-8s %(message)s',
    level=logging.INFO,
    datefmt='%Y-%m-%d %H:%M:%S')

REPL의 예:

>>> import logging
>>> logging.basicConfig(
...         format='%(asctime)s %(levelname)-8s %(message)s',
...         level=logging.INFO,
...         datefmt='%Y-%m-%d %H:%M:%S')
>>> 
>>> logging.info('an info messge')
2017-05-25 00:58:28 INFO     an info messge
>>> logging.debug('a debug messag is not shown')
>>> 

아래와 같은 방법으로 수행할 수 있습니다.

formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
                              datefmt='%Y-%m-%d %H:%M:%S')

다음을 살펴 보십시오.loggingPython용 모듈입니다.날짜를 작성하는 데 번거롭게 할 필요는 없습니다. 로깅 모듈이 대신 날짜를 작성하도록 하십시오.해당 포메터 개체를 로깅 핸들러에 적용할 수 있으므로 다음을 사용하여 로그할 수 있습니다.logger.info('This is an info message.')인쇄문이 필요하지 않습니다.

제가 사용하는 상용 절차는 다음과 같습니다.

import logging
import sys

def setup_custom_logger(name):
    formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
                                  datefmt='%Y-%m-%d %H:%M:%S')
    handler = logging.FileHandler('log.txt', mode='w')
    handler.setFormatter(formatter)
    screen_handler = logging.StreamHandler(stream=sys.stdout)
    screen_handler.setFormatter(formatter)
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(handler)
    logger.addHandler(screen_handler)
    return logger

>>> logger = setup_custom_logger('myapp')
>>> logger.info('This is a message!')
2015-02-04 15:07:12 INFO     This is a message!
>>> logger.error('Here is another')
2015-02-04 15:07:30 ERROR    Here is another

날짜 시간은 문자열이 형성될 때 계산됩니다.즉, 초기화 시 한 번만 가능합니다.대신 다음과 같은 작업을 수행해야 합니다.

def ok(hostname=None, status=None):
    output = (
        "[" + bc.OKGREEN + " OK "  + bc.ENDC + "] " +
        datetime.datetime.now().strftime("%d.%b %Y %H:%M:%S")
    )
    if hostname is not None:
        output += ' ' + hostname
    if status is not None:
        output += ' ' + status
    print output

기록하려면 , 그냥 사용합니다.ok()매번 날짜 시간을 재평가합니다.

@paydima 제안도 좋습니다.

언급URL : https://stackoverflow.com/questions/28330317/print-timestamp-for-logging-in-python

반응형