zoukankan      html  css  js  c++  java
  • Python的log

    关键代码

    调用方:

     1 from Logger import MyLogger
     2 import logging
     3 import sys, os
     4 
     5 def getLogger():
     6     # get the file name
     7     fileUrl = sys.argv[0]
     8     filepath, tmpfilename = os.path.split(fileUrl)
     9     shotname, extension = os.path.splitext(tmpfilename)
    10     
    11     # get the logger object
    12     logger = MyLogger(logname='log.txt', loglevel=1, logger=shotname).getlog()
    13     return logger
    14 
    15 logger =getLogger()
    16 logger.debug("Hoory, show!")

    Logger.py

     1 #开发一个日志系统, 既要把日志输出到控制台, 还要写入日志文件  
     2 import logging
     3 
     4 class MyLogger():
     5     format_dict = {
     6         1 : logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'),
     7         2 : logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'),
     8         3 : logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'),
     9         4 : logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'),
    10         5 : logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    11     }
    12 
    13     def __init__(self, logname, loglevel, logger):
    14         '''
    15            指定保存日志的文件路径,日志级别,以及调用文件
    16            将日志存入到指定的文件中
    17         '''
    18 
    19         # 创建一个logger
    20         self.logger = logging.getLogger(logger)
    21         self.logger.setLevel(logging.DEBUG)
    22 
    23         # 创建一个handler,用于写入日志文件
    24         fh = logging.FileHandler(logname)
    25         fh.setLevel(logging.DEBUG)
    26 
    27         # 再创建一个handler,用于输出到控制台
    28         ch = logging.StreamHandler()
    29         ch.setLevel(logging.DEBUG)
    30 
    31         # 定义handler的输出格式
    32         formatter = logging.Formatter('%(asctime)s %(name)s %(thread)d %(levelname)s %(message)s')
    33         fh.setFormatter(formatter)
    34         ch.setFormatter(formatter)
    35 
    36         # only first time need to add the handler
    37         if(self.logger.hasHandlers() == False):
    38             self.logger.addHandler(fh)
    39             self.logger.addHandler(ch)
    40 
    41    
    42     def getlog(self):
    43         return self.logger

    Logger相关属性

    可以通过下面的代码来进行设置(基本上不需要这么设置,因为通过getlogger()获取的logger对象并没有集成root的相关配置):

    1 logging.basicConfig(filename="log2.txt", level=logging.WARNING)

     

    关于format

  • 相关阅读:
    SVN为什么比Git更好
    vim的高亮查找操作
    Mac利用PD虚拟机安装Centos7
    学习MapReduce的计算原理
    hadoop-HA高可用集群部署
    HDFS命令操作和高可用
    初识hadoop及伪集群部署
    初步学习nginx
    小记--------maxwell启动失败解决
    小记--------spark资源调度机制源码分析-----Schedule
  • 原文地址:https://www.cnblogs.com/xiashiwendao/p/11778072.html
Copyright © 2011-2022 走看看