zoukankan      html  css  js  c++  java
  • python自定义logger handler

     1 _filefmt=os.path.join("logs","%Y-%m-%d.log")
     2 class MyLoggerHandler(logging.Handler):
     3     def __init__(self,filefmt=None):
     4         self.filefmt=filefmt
     5         if filefmt is None:
     6             self.filefmt=_filefmt
     7         logging.Handler.__init__(self)
     8     def emit(self,record):
     9         msg=self.format(record)
    10         _filePath=datetime.datetime.now().strftime(self.filefmt)
    11         _dir=os.path.dirname(_filePath)
    12         try:
    13             if os.path.exists(_dir) is False:
    14                 os.makedirs(_dir)
    15         except Exception:
    16             print("can not make dirs")
    17             print("filepath is "+_filePath)
    18             pass
    19         try:
    20             _fobj=open(_filePath,'a') 
    21             _fobj.write(msg)
    22             _fobj.write("
    ")
    23             _fobj.flush()
    24             _fobj.close()
    25         except Exception:
    26             print("can not write to file")
    27             print("filepath is "+_filePath)
    28             pass
    29 if __name__ == '__main__':
    30     logging.basicConfig()
    31     logger = logging.getLogger("logger")
    32     logger.setLevel(logging.INFO)
    33     filehandler = MyLoggerHandler()
    34     logger.addHandler(filehandler)
    35     logger.info('log...')

    如上,实现每天一个日志文件。

  • 相关阅读:
    Java使用printf格式化日期
    Java时间Date类
    Java数组
    Spring Cloud Stream
    Spring Cloud Bus
    Spring Cloud Config
    api服务网关?
    SPRINGBOOT集成SWAGGER2
    MySQL锁(一)全局锁:如何做全库的逻辑备份?
    Spring的FactoryBean
  • 原文地址:https://www.cnblogs.com/cero/p/5108786.html
Copyright © 2011-2022 走看看