参考修改:https://www.jianshu.com/p/ca192138806e

 

  • 日志要能够以 json 格式写入文件,且日志文件能够通过文件大小或是时间截断
  • 调试过程,日志能够清晰漂亮的格式打印到控制台,即标准输出

依赖

 python 本身的 logging 模块,还依赖了 python-json-logger 模块,需要     pip install python-json-logger 

 

# -*- coding:utf-8 -*-
# Logger.py
import logging
from logging.handlers import RotatingFileHandler
import os
import re
import string
import time
#from pip._internal.utils.logging import ColorizedStreamHandler

aplication_name="sea-test"
log_path="/tmp/"
time_value = time.strftime('%Y%m%d', time.localtime(time.time()))
# #create logger name
log_file_name =application_name  + "_" +time_value +'.log'
log_file_str="./"+log_path+log_file_name
 
if not os.path.exists(log_path):
    os.mkdir(log_path)
#---------------------------------------


def _getLogger(clsname="my_class"):
    _logger = logging.getLogger(clsname)
    _logger.setLevel(logging.DEBUG)  #  此处要整体设置 logger level = DEBUG,否则后面在不同的 handler 中设置 level 无效
    
    # 创建一个handler,用于写入日志文件
    fileHandler = RotatingFileHandler(filename=log_file_str, mode='a', maxBytes=10 * 1024 * 1024,encoding='utf8', backupCount=100)
#     fileHandler = logging.handlers.TimedRotatingFileHandler(log_file_str, when='D', interval=1, backupCount=30, encoding='UTF-8')
    # to avoid missing date for print daily log
    fileHandler.suffix = "%Y-%m-%d"
    fileHandler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}$")
    logging_format = logging.Formatter('%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
    fileHandler.setFormatter(logging_format)
    _logger.addHandler(fileHandler)
    
    
    # 不同 level, 颜色不同
    #consoleHandler = ColorizedStreamHandler()
consoleHandler = logging.StreamHandler() consoleHandler.setLevel(logging.DEBUG)
# 标准输出没必要 json 了,只打印 message 就好了 consoleFormatter = logging.Formatter('%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s') consoleHandler.setFormatter(consoleFormatter) _logger.addHandler(consoleHandler) return _logger # def getLogger(clsname): # return _getLogger(clsname) logger = _getLogger() def info(formatStr:string, *objs): logger.info(formatStr.format(*objs)) def debug(formatStr:string, *objs): logger.debug(formatStr.format(*objs)) def error(formatStr:string, *objs): logger.error(formatStr.format(*objs)) def warning(formatStr:string, *objs): logger.warning(formatStr.format(*objs)) def critical(formatStr:string, *objs): logger.critical(formatStr.format(*objs)) if __name__ == '__main__': i = 0 while True: info("{} level debug:{}","我的级别","是debug") info("{} level info {}" ,"我的级别","是info") warning('{} level warning {}',"我想打印数字",1111) i += 1 if i == 100: break

 

 

使用 :

#encoding=utf-8
# from  import  com.sea.logger.Logger
from com.sea.logger import Logger


Logger.info("1111")
Logger.error("nihai 我是 {} 你好吗? " ,1111)

 

posted on 2019-10-09 15:37  lshan  阅读(340)  评论(0编辑  收藏  举报