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...')

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

  • 相关阅读:
    linux离线安装mysql
    SpringBoot配置SSL证书
    java在liunx下备份mysql数据,恢复数据
    Redis的缓存穿透,缓存击穿,缓存雪崩
    Spring缓存注解
    Advanced Algorithm Scripting
    Arguments Optional
    Everything Be True
    Binary Agents
    Steamroller
  • 原文地址:https://www.cnblogs.com/cero/p/5108786.html
Copyright © 2011-2022 走看看