카테고리 없음

python logger with timezone

sunshout 2024. 6. 4. 17:59
import logging
from datetime import datetime

def formatTime(self, record, datefmt=None):
    return datetime.fromtimestamp(record.created).astimezone().isoformat(timespec='milliseconds')
logging.Formatter.formatTime = formatTime

# Create a custom formatter with your desired time format
time_format = "%Y-%m-%d %H:%M:%S"
formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s', datefmt=time_format)

# Create a logger and set the custom formatter
logger = logging.getLogger('custom_logger')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)

# Set the log level (optional, can be DEBUG, INFO, WARNING, ERROR, CRITICAL)
logger.setLevel(logging.DEBUG)

# Now you can use the logger to log messages with your custom time format
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')

Output 

choonhoson@Choonhoui-MacBookAir test4 % python3 timezone-test.py
2024-06-04T17:49:05.753+09:00 - DEBUG - This is a debug message
2024-06-04T17:49:05.753+09:00 - INFO - This is an info message
2024-06-04T17:49:05.753+09:00 - WARNING - This is a warning message
2024-06-04T17:49:05.753+09:00 - ERROR - This is an error message
2024-06-04T17:49:05.753+09:00 - CRITICAL - This is a critical message