1. 程式人生 > >Python學習---重點模塊之logging

Python學習---重點模塊之logging

模塊名 for aps splay file 語句 添加 pre src

日誌級別

日誌級別 critical > error > warning > info > debug, 默認是從warning開始打印

import logging

# 日誌級別  critical > error > warning > info > debug
logging.debug(‘hello world‘)
logging.info(‘hello world‘)
logging.warning(‘hello world‘)
logging.error(‘hello world‘)
logging.critical(‘hello world‘)
技術分享圖片

日誌的配置

配置的 basicConfig文件只能輸出到文件中,但是配合stream參數可以達到屏幕/文件均輸出的效果

默認追加模式

默認是輸出到屏幕,有filename則輸出到文件

直接用logging配置
import logging
# 配置的 basicConfig文件只能輸出到文件中,但是配合stream參數可以達到屏幕/文件均輸出的效果
logging.basicConfig(level=logging.DEBUG,  ormat=‘%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s‘,
                    datefmt=‘%a, %d %b %Y %H:%M:%S‘,
                    #stream 輸出的流
                    filename=‘test.log‘, # 默認是輸出到屏幕,有filename則輸出到文件
                    filemode=‘a‘)   # 默認追加模式

logging.debug(‘debug message‘)
logging.info(‘info message‘)
logging.warning(‘warning message‘)
logging.error(‘error message‘)
logging.critical(‘critical message‘)
 

format參數中可能用到的格式化串:

%(name)s Logger的名字

%(levelno)s 數字形式的日誌級別

%(levelname)s 文本形式的日誌級別

%(pathname)s 調用日誌輸出函數的模塊的完整路徑名,可能沒有

%(filename)s 調用日誌輸出函數的模塊的文件名

%(module)s 調用日誌輸出函數的模塊名

%(funcName)s 調用日誌輸出函數的函數名

%(lineno)d 調用日誌輸出函數的語句所在的代碼行

%(created)f 當前時間,用UNIX標準的表示時間的浮 點數表示

%(relativeCreated)d 輸出日誌信息時的,自Logger創建以 來的毫秒數

%(asctime)s 字符串形式的當前時間。默認格式是 “2003-07-08 16:49:45,896”。逗號後面的是毫秒

%(thread)d 線程ID。可能沒有

%(threadName)s 線程名。可能沒有

%(process)d 進程ID。可能沒有

%(message)s用戶輸出的消息

logger對象:可以文件打印,也可以屏幕輸出

import logging
# 創建了一個logger對象,並且命名為
log = logging.Logger(‘user_logger‘, level=logging.INFO)
# 更改日誌級別,默認是warning級別
# log.setLevel(logging.DEBUG)
# 文件輸出對象
log_txt = logging.FileHandler(‘log.log‘)
# 屏幕輸出對象
log_str = logging.StreamHandler()
log_format = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s -[line:%(lineno)d]- %(message)s‘)
# 屏幕輸出
log_str.setFormatter(log_format)
# 文件輸出
log_txt.setFormatter(log_format)

# log 對象添加屏幕輸出
log.addHandler(log_str)
# log 對象添加文件輸出
log.addHandler(log_txt)
# 輸出內容,默認warning以上的log都可以打印
log.debug(‘log debug message‘)
log.info(‘log info message‘)
log.warning(‘log warning message‘)
log.error(‘log error message‘)
log.critical(‘log critical message‘)

技術分享圖片

Python學習---重點模塊之logging