Python日志简单使用
注意:
- logger传播或handler添加多个,导致log重复记录
# coding=utf-8
import logging
import os
import socket
import datetime
LOG_FORMAT = '[%(asctime)s] [%(levelname)s] %(filename)s [line:%(lineno)d]: %(message)s'
# LOG_FORMAT = "%(asctime)s {host} {app_key} [%(levelname)s] %(threadName)s %(filename)s[%(lineno)d] %(message)s"
DEFAULT_LOG_PATH = '/opt/logs'
def get_handler():
log_file = get_log_file()
handler = logging.FileHandler(log_file, encoding='UTF-8')
handler.setLevel(logging.INFO)
formatter = logging.Formatter(LOG_FORMAT)
handler.setFormatter(formatter)
return handler
def get_logger(log_name):
# 使用log_name避免模块导入导致重复打印 https://blog.csdn.net/nuaa_llf/article/details/89883293
logger = logging.getLogger(log_name)
logger.setLevel(logging.INFO)
# 避免root logger处理
logger.propagate = False
logger.addHandler(get_handler(log_type=log_type))
return logger
def get_log_file():
time = datetime.datetime.now()
log_path_prefix = os.environ.get('LOG_PATH', DEFAULT_LOG_PATH)
if not os.path.exists(log_path_prefix):
os.makedirs(log_path_prefix)
filename = time.strftime('%Y_%m_%d') + '.log'
return os.path.join(log_path_prefix, filename)
if __name__ == '__main__':
log = get_logger(__name__)
log.debug('一个debug信息')
log.info('一个info信息')
log.warning('一个warning信息')
log.error('一个error信息')
log.critical('一个critical信息')