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


'''
相關文章
相關標籤/搜索