[TOC]
# 淺析python日志重復輸出問題
## 問題起源:
? 在學習了python的函數式編程后,又接觸到了logging這樣一個強大的日志模塊。為了減少重復代碼,應該不少同學和我一樣便迫不及待的寫了一個自己的日志函數,比如下面這樣:
```
# 這里為了便于理解,簡單的展示了一個輸出到屏幕的日志函數
def my_log():
logger = logging.getLogger('mysql.log')
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(fmt)
logger.addHandler(ch)
return logger
my_log().error('run one')
my_log().error('run two')
my_log().error('run three')
```
函數寫好了,看起來似乎也沒有問題,我們來運行一下!
結果如下:
```
> 2018-06-21 13:06:37,569 - mysql.log - ERROR - run one
> 2018-06-21 13:06:37,569 - mysql.log - ERROR - run two
> 2018-06-21 13:06:37,569 - mysql.log - ERROR - run two
> 2018-06-21 13:06:37,569 - mysql.log - ERROR - run three
> 2018-06-21 13:06:37,569 - mysql.log - ERROR - run three
> 2018-06-21 13:06:37,569 - mysql.log - ERROR - run three
```
日志居然重復輸出了,且數量遞增。
* * *
## 問題解析
* 實際上`logger = logging.getLogger('mysql.log')`在執行時,沒有每次生成一個新的logger,而是先檢查內存中是否存在一個叫做‘mysql.log’的logger對象,存在則取出,不存在則新建。
* 實例化的logger對象具有‘handlers’這樣一個屬性來存儲 Handler,代碼演示如下:
```
def my_log():
logger = logging.getLogger('mysql.log')
# 每次被調用后打印出logger的handlers列表
print(logger.handlers)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(fmt)
logger.addHandler(ch)
return logger
my_log().error('run one')
my_log().error('run two')
my_log().error('run three')
```
運行結果:
```
> \[\]
> 2018-06-21 13:26:14,059 - mysql.log - ERROR - run one
> \[ (ERROR)>\]
> 2018-06-21 13:26:14,060 - mysql.log - ERROR - run two
> 2018-06-21 13:26:14,060 - mysql.log - ERROR - run two
> \[ (ERROR)>, (ERROR)>\]
> 2018-06-21 13:26:14,060 - mysql.log - ERROR - run three
> 2018-06-21 13:26:14,060 - mysql.log - ERROR - run three
> 2018-06-21 13:26:14,060 - mysql.log - ERROR - run three
```
1. `logger.handlers`最初是一個空列表,執行‘logger.addHandler(ch)’添加一個‘StreamHandler’,輸出一條日志
2. 在第二次被調用時,`logger.handlers`已經存在一個‘StreamHandler’,再次執行‘logger.addHandler(ch)’就會再次添加一個‘StreamHandler’,此時的logger有兩個個‘StreamHandler’,輸出兩條重復的日志
3. 在第三次被調用時,`logger.handlers`已經存在兩個‘StreamHandler’,再次執行‘logger.addHandler(ch)’就會再次添加一個,此時的logger有三個‘StreamHandler’,輸出三條重復的日志
## 解決辦法
### 1.改名換姓
```
# 為日志函數添加一個name,每次調用時傳入不同的日志名
def my_log(name):
logger = logging.getLogger(name)
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(fmt)
logger.addHandler(ch)
return logger
my_log('log1').error('run one')
my_log('log2').error('run two')
my_log('log3').error('run three')
```
運行結果:
```
> 2018-06-21 13:40:51,685 - log1 - ERROR - run one
> 2018-06-21 13:40:51,685 - log2 - ERROR - run two
> 2018-06-21 13:40:51,685 - log3 - ERROR - run three
```
### 2.及時清理(logger.handlers.clear)
```
def my_log():
logger = logging.getLogger()
# 每次被調用后,清空已經存在handler
logger.handlers.clear()
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(fmt)
logger.addHandler(ch)
return logger
my_log().error('run one')
my_log().error('run two')
my_log().error('run three')
```
### 3.用前判斷
```
import logging
def my_log():
logger = logging.getLogger('mysql.log')
# 判斷logger是否已經添加過handler,是則直接返回,否則才執行
if not logger.handlers:
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
fmt = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(fmt)
logger.addHandler(ch)
return logger
my_log().error('run one')
my_log().error('run two')
my_log().error('run three')
```
* * *
- 基礎部分
- 基礎知識
- 變量
- 數據類型
- 數字與布爾詳解
- 列表詳解list
- 字符串詳解str
- 元組詳解tup
- 字典詳解dict
- 集合詳解set
- 運算符
- 流程控制與循環
- 字符編碼
- 編的小程序
- 三級菜單
- 斐波那契數列
- 漢諾塔
- 文件操作
- 函數相關
- 函數基礎知識
- 函數進階知識
- lambda與map-filter-reduce
- 裝飾器知識
- 生成器和迭代器
- 琢磨的小技巧
- 通過operator函數將字符串轉換回運算符
- 目錄規范
- 異常處理
- 常用模塊
- 模塊和包相關概念
- 絕對導入&相對導入
- pip使用第三方源
- time&datetime模塊
- random隨機數模塊
- os 系統交互模塊
- sys系統模塊
- shutil復制&打包模塊
- json&pickle&shelve模塊
- xml序列化模塊
- configparser配置模塊
- hashlib哈希模塊
- subprocess命令模塊
- 日志logging模塊基礎
- 日志logging模塊進階
- 日志重復輸出問題
- re正則表達式模塊
- struct字節處理模塊
- abc抽象類與多態模塊
- requests與urllib網絡訪問模塊
- 參數控制模塊1-optparse-過時
- 參數控制模塊2-argparse
- pymysql數據庫模塊
- requests網絡請求模塊
- 面向對象
- 面向對象相關概念
- 類與對象基礎操作
- 繼承-派生和組合
- 抽象類與接口
- 多態與鴨子類型
- 封裝-隱藏與擴展性
- 綁定方法與非綁定方法
- 反射-字符串映射屬性
- 類相關內置方法
- 元類自定義及單例模式
- 面向對象的軟件開發
- 網絡-并發編程
- 網絡編程SOCKET
- socket簡介和入門
- socket代碼實例
- 粘包及粘包解決辦法
- 基于UDP協議的socket
- 文件傳輸程序實戰
- socketserver并發模塊
- 多進程multiprocessing模塊
- 進程理論知識
- 多進程與守護進程
- 鎖-信號量-事件
- 隊列與生產消費模型
- 進程池Pool
- 多線程threading模塊
- 進程理論和GIL鎖
- 死鎖與遞歸鎖
- 多線程與守護線程
- 定時器-條件-隊列
- 線程池與進程池(新方法)
- 協程與IO模型
- 協程理論知識
- gevent與greenlet模塊
- 5種網絡IO模型
- 非阻塞與多路復用IO實現
- 帶著目標學python
- Pycharm基本使用
- 爬蟲
- 案例-爬mzitu美女
- 案例-爬小說
- beautifulsoup解析模塊
- etree中的xpath解析模塊
- 反爬對抗-普通驗證碼
- 反爬對抗-session登錄
- 反爬對抗-代理池
- 爬蟲技巧-線程池
- 爬蟲對抗-圖片懶加載
- selenium瀏覽器模擬