在使用Python的log函數時,需要注意以下事項:
import logging
basicConfig
或者手動創建Logger
對象來配置。logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
log
函數記錄日志信息。可以指定不同的日志級別(DEBUG、INFO、WARNING、ERROR、CRITICAL)。logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
exception
方法記錄異常信息。try:
# some code that may raise an exception
except Exception as e:
logging.exception('An error occurred: %s', e)
StreamHandler
、FileHandler
等處理器來實現不同的輸出方式。console_handler = logging.StreamHandler()
file_handler = logging.FileHandler('log.txt')
logging.getLogger().addHandler(console_handler)
logging.getLogger().addHandler(file_handler)
logging.basicConfig(level=logging.DEBUG)
import queue
import threading
log_queue = queue.Queue()
def log_worker():
while True:
record = log_queue.get()
logger = logging.getLogger(record.name)
logger.handle(record)
log_queue.task_done()
thread = threading.Thread(target=log_worker)
thread.daemon = True
thread.start()
handler = logging.Handler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(message)s'))
handler.set_name('my_logger')
logger = logging.getLogger('my_logger')
logger.addHandler(handler)
logger.info('Hello, world')
總之,在使用Python的log函數時,需要注意以上事項來確保正確記錄和管理日志信息。