python logging使用封装

1,518 阅读2分钟

log文件路径在初始化时更换为绝对路径,可避免在win32services中使用时为pythonservices所在路径而非.py文件所在路径导致错误而无法写日志。

使用: import myloger.py

#logger = logging.getLogger()

#logger.info('aaaaaaq')

#或import logging后直接使用

logging.info('5555555555')

1、log.yaml配置文件:

# version must be 1
# logger配置文件
#################################### logging yaml content #############################################

version: 1
disable_existing_loggers: True
formatters:
    simple:
        format: "%(asctime)s - %(filename)s - %(levelname)s - %(message)s"
    simple1:
        format: "%(asctime)s - %(thread)d - [%(levelname)s] %(pathname)s - %(module)s - %(funcName)s: %(message)s"
#filters:
handlers:
    console:
        class: logging.StreamHandler
        level: DEBUG
        formatter: simple
        stream: ext://sys.stdout
    info_file_timedRotatingFileHandler:
        class: logging.handlers.TimedRotatingFileHandler
        level: INFO
        formatter: simple
        filename: info.log
        when: 'midnight'
        backupCount: 7
        encoding: utf8
    error_file_timedRotatingFileHandler:
        class: logging.handlers.TimedRotatingFileHandler
        level: ERROR
        formatter: simple
        filename: error.log
        when: 'midnight'
        backupCount: 7
        encoding: utf8
    warn_file_timedRotatingFileHandler:
        class: logging.handlers.TimedRotatingFileHandler
        level: WARN
        formatter: simple
        filename: warn.log
        when: 'midnight'
        backupCount: 7
        encoding: utf8
loggers:
    console:
        level: DEBUG
        handlers: [console,warn_file_timedRotatingFileHandler]
        propagate: 0 #默认值为1,表示将消息传递给父logger的handler进行处理
        qualname: csl #代码中使用logging.getLogger()时,读取的就是qualname这个选项。
    info: #logger = logging.getLogger('info')时选用
        level: INFO
        propagate: False
        handlers: [console,info_file_timedRotatingFileHandler]
    warn: #logger = logging.getLogger('warn')
        level: WARNING
        handlers: [console,warn_file_timedRotatingFileHandler]
        propagate: 0 #默认值为1,表示将消息传递给父logger的handler进行处理
        qualname: cslinfo
    error: #logger = logging.getLogger('error')
        level: ERROR
        handlers: [console,error_file_timedRotatingFileHandler]
        propagate: 0 #默认值为1,表示将消息传递给父logger的handler进行处理
        qualname: cslerror
root: # 直接logging.info('atest') 选用
    level: INFO
    propagate: False
    handlers: [console,info_file_timedRotatingFileHandler]


2、myloger.py

import yaml
import logging.config
import os
#import inspect


def setup_logging(yamlcfg_path='./config/log.yaml', default_level=logging.INFO):
    """
    Setup logging configuration
    """
    #更换为绝对路径,可避免在win32services中使用时为pythonservices所在路径而非.py文件所在路径导致错误而无法写日志。
    '''cur_path=os.path.abspath(os.curdir)#如何在win32servers中调用则为pythonservices路径
    logf_file=os.path.join(cur_path,'logs','info.log')
    log_path=os.path.abspath(os.path.split(logf_file)[0])
    
    this_file = inspect.getfile(inspect.currentframe())
    log_path = os.path.abspath(os.path.dirname(this_file))'''
    log_path1 = os.path.dirname(os.path.abspath(__file__))
    log_path=os.path.join(log_path1,'logs')
    print(log_path)
    if os.path.exists(log_path):
        pass
    else:
        os.makedirs(log_path)
        
    path = yamlcfg_path
        
    if os.path.exists(path):
        with open(path, 'rt',encoding='utf-8') as f:
            config = yaml.safe_load(f.read())
            hdl=config['handlers']
            #print(hdl['console'])
            for k,v in hdl.items():
                if isinstance(v,dict):
                    #print(k+':')
                    if  'filename' in config['handlers'][k].keys():
                        fname=config['handlers'][k]['filename']
                        #fname.replace('\\','/')
                        fname=fname.lstrip('./').lstrip('.\\')
                        config['handlers'][k]['filename']=os.path.join(log_path,fname)
                        #print(config['handlers'][k]['filename'])
            
        logging.config.dictConfig(config)
    else:
        logging.basicConfig(level=default_level)
        print('the input yaml path doesn\'t exist')

#if __name__ == '__main__':
curr_path = os.path.dirname(os.path.abspath(__file__))
cfg_path=os.path.join(curr_path,'config/logging.yaml')#获取文件所在路径,否则如是在win32services 中调用路径不对
setup_logging(yamlcfg_path=cfg_path)

# 获取当前文件夹路径
#os.path.dirname(os.path.abspath(__file__))
#使用:
#logger = logging.getLogger()
#logger.info('aaaaaaq')
#或import logging后直接使用
#logging.info('5555555555')