zoukankan      html  css  js  c++  java
  • python之log

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    '''
    
    '''
    import logging
    
    # 设置输出文件、文件格式和日志级别
    logging.basicConfig(filename='example.log', level=logging.INFO,
                        format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
    
    # 开始打印日志信息
    logging.debug('This message should go to the log file')
    logging.info('So should this')
    logging.warning('And this, too')
    logging.warning("user [kobe] attempted wrong password more than 3 times")
    logging.critical("Server is down...")
    
    
    # 1、创建logger 谁去发日志
    logger = logging.getLogger('TEST-LOG')  # 先获取logger对象
    logger.setLevel(logging.DEBUG)  # 设置全局日志级别
    
    # 2、创建Handler 发给屏幕
    ch = logging.StreamHandler()  # 在屏幕上打印
    ch.setLevel(logging.DEBUG)  # 设置在屏幕上打印日志的全局级别
    
    # 3、创建Handler 文件
    fh = logging.FileHandler("access.log")
    fh.setLevel(logging.WARNING)  # 日志局部级别
    fh_err = logging.FileHandler("error.log")
    fh_err.setLevel(logging.ERROR)
    
    # 4、创建formatter输出格式
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    formatter_for_file = logging.Formatter('%(asctime)s - %(filename)s - %(levelname)s - %(message)s')
    
    # 5、分别设置格式
    ch.setFormatter(formatter)
    fh.setFormatter(formatter_for_file)
    fh_err.setFormatter(formatter)
    
    # 6、向logger注册
    logger.addHandler(ch)
    logger.addHandler(fh)
    logger.addHandler(fh_err)
    
    # 7、打印
    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')
    '''
    运行结果: 
    写入文件  (example.log)
    04/18/2019 10:44:22 AM So should this
    04/18/2019 10:44:22 AM And this, too
    04/18/2019 10:44:22 AM user [kobe] attempted wrong password more than 3 times
    04/18/2019 10:44:22 AM Server is down...
    
    写入文件(access.log)
    2019-04-18 10:51:21,851 - man.py - WARNING - warn message
    2019-04-18 10:51:21,851 - man.py - ERROR - error message
    2019-04-18 10:51:21,851 - man.py - CRITICAL - critical message
    
    写入文件(error.log)
    2019-04-18 10:51:21,851 - TEST-LOG - ERROR - error message
    2019-04-18 10:51:21,851 - TEST-LOG - CRITICAL - critical message
    
    
    '''
  • 相关阅读:
    在VS2010下,用QT,创建一个Opencv应用程序
    SNR(信噪比)与 特定分布噪声的关系初探
    Qt学习笔记_FindDialog
    关于reduced rank regression的一些看法
    实时摄像头人眼跟踪: RealTime Tracking Of Human Eyes Using a Webcam
    L1_APG_Tracker实现代码剖析
    CVPR2013 感兴趣论文汇总
    使用PowerDesigner 15对现有数据库进行反向工程(图解教程)(转)
    大数据量高并发的数据库优化
    rtmp和rtsp的区别
  • 原文地址:https://www.cnblogs.com/wanghuixi/p/10787101.html
Copyright © 2011-2022 走看看