<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Python 日志教程 > 原文: [http://zetcode.com/python/logging/](http://zetcode.com/python/logging/) Python 日志教程展示了如何使用日志模塊在 Python 中進行日志。 ## 日志 日志是將信息寫入日志文件的過程。 日志文件包含有關在操作系統,軟件或通信中發生的各種事件的信息。 ## 記錄目的 完成記錄是出于以下目的: * 信息收集 * 故障排除 * 產生統計數據 * 審計 * 性能分析 記錄不僅限于識別軟件開發中的錯誤。 它還可用于檢測安全事件,監視策略違規,在出現問題時提供信息,查找應用瓶頸或生成使用情況數據。 ## 要記錄哪些事件 應記錄的事件包括輸入驗證失敗,認證和授權失敗,應用錯誤,配置更改以及應用啟動和關閉。 ## 哪些事件不記錄 不應記錄的事件包括應用源代碼,會話標識值,訪問令牌,敏感的個人數據,密碼,數據庫連接字符串,加密鍵,銀行帳戶和持卡人數據。 ## 記錄最佳做法 以下是進行日志的一些最佳做法: * 日志應該有意義。 * 日志應包含上下文。 * 日志應在不同級別進行結構化和完成。 * 日志應保持平衡; 它不應包含過多或過多的信息。 * 記錄消息應該是人類可以理解的,并且可以被機器解析。 * 記錄更復雜的應用應產生幾個日志文件。 * 日志應適應開發和生產。 ## 日志模塊 Python 日志模塊定義了實現用于應用和庫的靈活事件日志系統的函數和類。 ## 日志模塊組件 日志模塊具有四個主要組件:記錄器,處理器,過濾器和格式化程序。 記錄器公開了應用代碼直接使用的接口。 處理器將日志(由記錄器創建)發送到適當的目的地。 過濾器提供了更細粒度的功能,用于確定要輸出的日志。 格式化程序在最終輸出中指定日志的布局。 ## Python 日志層次結構 Python 記錄器形成一個層次結構。 名為`main`的記錄器是`main.new`的父級。 子記錄器將消息傳播到與其祖先記錄器關聯的處理器。 因此,不必為應用中的所有記錄器定義和配置處理器。 為頂級記錄器配置處理器并根據需要創建子記錄器就足夠了。 ## Python 日志級別 級別用于標識事件的嚴重性。 有六個日志級別: * `CRITICAL` * `ERROR` * `WARNING` * `INFO` * `DEBUG` * `NOTSET` 如果日志級別設置為`WARNING`,則所有`WARNING`,`ERROR`和`CRITICAL`消息都將寫入日志文件或控制臺。 如果將其設置為`ERROR`,則僅記錄`ERROR`和`CRITICAL`消息。 記錄器的概念是有效級別。 如果未在記錄器上顯式設置級別,則將其父級別用作其有效級別。 如果父級沒有顯式設置的級別,則檢查其父級,依此類推-搜索所有祖先,直到找到顯式設置的級別。 使用`getLogger()`創建記錄器時,級別設置為`NOTSET`。 如果未使用`setLevel()`顯式設置日志級別,則消息將傳播到記錄器父級。 遍歷記錄器的祖先記錄器鏈,直到找到具有`NOTSET`以外級別的祖先或到達根。 根記錄器具有默認的`WARNING`級別設置。 ## 根記錄器 所有記錄器都是根記錄器的后代。 每個記錄器將日志消息傳遞到其父級。 使用`getLogger(name)`方法創建新的記錄器。 調用不帶名稱的函數(`getLogger()`)將返回根記錄器。 根記錄器始終具有顯式級別集,默認情況下為`WARNING`。 根發信人位于層次結構的頂部,即使未配置,也始終存在。 通常,程序或庫不應直接登錄到根記錄器。 而是應配置該程序的特定記錄器。 根記錄器可用于輕松打開和關閉所有庫中的所有記錄器。 ## Python 日志簡單示例 `logging`模塊具有簡單的方法,可以立即使用而無需任何配置。 這可以用于簡單的日志。 `simple.py` ```py #!/usr/bin/env python import logging logging.debug('This is a debug message') logging.info('This is an info message') logging.warning('This is a warning message') logging.error('This is an error message') logging.critical('This is a critical message') ``` 該示例調用`logging`模塊的五個方法。 消息將寫入控制臺。 ```py $ simple.py WARNING:root:This is a warning message ERROR:root:This is an error message CRITICAL:root:This is a critical message ``` 請注意,使用了根記錄器,并且只寫入了三則消息。 這是因為默認情況下,僅寫入具有級別警告和更高級別的消息。 ## Python 設置日志級別 記錄級別由`setLevel()`設置。 它將此記錄器的閾值設置為`lvl`。 嚴重性不及`lvl`的日志消息將被忽略。 `set_level.py` ```py #!/usr/bin/env python import logging logger = logging.getLogger('dev') logger.setLevel(logging.DEBUG) logger.debug('This is a debug message') logger.info('This is an info message') logger.warning('This is a warning message') logger.error('This is an error message') logger.critical('This is a critical message') ``` 在示例中,我們將日志級別更改為`DEBUG`。 ```py logger = logging.getLogger('dev') ``` `getLogger()`返回具有指定名稱的記錄器。 如果名稱為`None`,則返回根記錄器。 名稱可以是點分隔的字符串,用于定義日志層次結構。 例如`"a"`,`"a.b"`或`"a.b.c"`。 請注意,有一個隱式根名,未顯示。 ```py $ set_level.py This is a warning message This is an error message This is a critical message ``` 現在,所有消息均已寫入。 ## Python 有效日志級別 有效日志級別是顯式設置的級別或由記錄器父級確定的級別。 `effective_level.py` ```py #!/usr/bin/env python import logging main_logger = logging.getLogger('main') main_logger.setLevel(5) dev_logger = logging.getLogger('main.dev') print(main_logger.getEffectiveLevel()) print(dev_logger.getEffectiveLevel()) ``` 在示例中,我們檢查了兩個記錄器的有效記錄級別。 ```py dev_logger = logging.getLogger('main.dev') ``` 未設置`dev_logger`的電平; 然后使用其父級。 ```py $ effective_level.py 5 5 ``` 這是輸出。 ## Python 日志處理器 處理器是一個對象,負責將適當的日志消息(基于日志消息的嚴重性)調度到處理器的指定目標。 處理器像級別一樣傳播。 如果記錄器未設置處理器,則其祖先鏈將搜索處理器。 `handlers.py` ```py #!/usr/bin/env python import logging logger = logging.getLogger('dev') logger.setLevel(logging.INFO) fileHandler = logging.FileHandler('test.log') fileHandler.setLevel(logging.INFO) consoleHandler = logging.StreamHandler() consoleHandler.setLevel(logging.INFO) logger.addHandler(fileHandler) logger.addHandler(consoleHandler) logger.info('information message') ``` 該示例為記錄器創建兩個處理器:文件處理器和控制臺處理器。 ```py fileHandler = logging.FileHandler('test.log') ``` `FileHandler`將日志發送到`test.log`文件。 ```py consoleHandler = logging.StreamHandler() ``` `StreamHandler`將日志發送到流。 如果未指定流,則使用`sys.stderr`。 ```py logger.addHandler(fileHandler) ``` 該處理器將通過`addHandler()`添加到記錄器。 ## Python 日志格式化程序 格式化程序是一個對象,用于配置日志的最終順序,結構和內容。 除消息字符串外,日志還包括日期和時間,日志名稱和日志級別嚴重性。 `formatter.py` ```py #!/usr/bin/env python import logging logger = logging.getLogger('dev') logger.setLevel(logging.INFO) consoleHandler = logging.StreamHandler() consoleHandler.setLevel(logging.INFO) logger.addHandler(consoleHandler) formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s: %(message)s') consoleHandler.setFormatter(formatter) logger.info('information message') ``` 該示例創建一個控制臺記錄器,并將格式化程序添加到其處理器。 ```py formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s: %(message)s') ``` 格式化程序已創建。 它包括日期時間,記錄器名稱,記錄級別名稱和記錄消息。 ```py consoleHandler.setFormatter(formatter) ``` 格式化程序通過`setFormatter()`設置為處理器。 ```py $ formatter.py 2019-03-28 14:53:27,446 dev INFO: information message ``` 具有定義格式的消息顯示在控制臺中。 ## Python 日志`basicConfig` `basicConfig()`配置根記錄器。 它通過使用默認格式化程序創建流處理器來為日志系統進行基本配置。 如果沒有為根記錄器定義處理器,則`debug()`,`info()`,`warning()`,`error()`和`critical()`自動調用`basicConfig()`。 `basic_config.py` ```py #!/usr/bin/env python import logging logging.basicConfig(filename='test.log', format='%(filename)s: %(message)s', level=logging.DEBUG) logging.debug('This is a debug message') logging.info('This is an info message') logging.warning('This is a warning message') logging.error('This is an error message') logging.critical('This is a critical message') ``` 該示例使用`basicConfig`配置根記錄器。 ```py logging.basicConfig(filename='test.log', format='%(filename)s: %(message)s', level=logging.DEBUG) ``` 使用`filename`,我們設置要寫入日志消息的文件。 `format`確定將什么內容記錄到文件中; 我們有文件名和消息。 使用`level`,設置記錄閾值。 ```py $ basic_config.py $ cat test.log basic_config.py: This is a debug message basic_config.py: This is an info message basic_config.py: This is a warning message basic_config.py: This is an error message basic_config.py: This is a critical message ``` 運行該程序后,我們將五條消息寫入`test.log`文件。 ## Python 日志文件配置 `fileConfig()`從`configparser`格式文件中讀取日志配置。 `log.conf` ```py [loggers] keys=root,dev [handlers] keys=consoleHandler [formatters] keys=extend,simple [logger_root] level=INFO handlers=consoleHandler [logger_dev] level=INFO handlers=consoleHandler qualname=dev propagate=0 [handler_consoleHandler] class=StreamHandler level=INFO formatter=extend args=(sys.stdout,) [formatter_extend] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s [formatter_simple] format=%(asctime)s - %(message)s ``` `log.conf`定義了記錄器,處理器和格式化程序。 `file_config.py` ```py #!/usr/bin/env python import logging import logging.config logging.config.fileConfig(fname='log.conf') logger = logging.getLogger('dev') logger.info('This is an information message') ``` 該示例從`log.conf`讀取日志配置文件。 ```py $ file_config.py 2019-03-28 15:26:31,137 - dev - INFO - This is an information message ``` 這是輸出。 ## Python 日志變量 通過使用字符串格式記錄動態數據。 `log_variable.py` ```py #!/usr/bin/env python import logging root = logging.getLogger() root.setLevel(logging.INFO) log_format = '%(asctime)s %(filename)s: %(message)s' logging.basicConfig(filename="test.log", format=log_format) # incident happens error_message = 'authentication failed' root.error(f'error: {error_message}') ``` 該示例將自定義數據寫入日志消息。 ```py 2019-03-21 14:17:23,196 log_variable.py: error: authentication failed ``` 這是日志消息。 ## Python 日志格式化日期時間 日期時間包含在`asctime`日志的日志消息中。 使用`datefmt`配置選項,我們可以格式化日期時間字符串。 `date_time.py` ```py #!/usr/bin/env python import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) log_format = '%(asctime)s %(filename)s: %(message)s' logging.basicConfig(filename="test.log", format=log_format, datefmt='%Y-%m-%d %H:%M:%S') logger.info("information message") ``` 該示例格式化日志消息的日期時間。 ```py log_format = '%(asctime)s %(filename)s: %(message)s' ``` 我們將日期時間字符串包含在`asctime`中。 ```py logging.basicConfig(filename="test.log", format=log_format, datefmt='%Y-%m-%d %H:%M:%S') ``` `datefmt`選項格式化日期時間字符串。 ```py 2019-03-21 14:17:23,196 log_variable.py: error: authentication failed 2019-03-21 14:23:33 date_time.py: information message ``` 注意日期時間字符串格式的不同。 ## Python 日志棧跟蹤 棧跟蹤是調用函數的棧,這些函數一直運行到引發異常時為止。 棧跟蹤包含在`exc_info`選項中。 `stack_trace.py` ```py #!/usr/bin/env python import logging log_format = '%(asctime)s %(filename)s: %(message)s' logging.basicConfig(filename="test.log", format=log_format) vals = [1, 2] try: print(vals[4]) except Exception as e: logging.error("exception occurred", exc_info=True) ``` 在該示例中,我們記錄了嘗試訪問不存在的列表索引時引發的異常。 ```py logging.error("exception occurred", exc_info=True) ``` 通過將`exc_info`設置為`True`,棧跟蹤將包含在日志中。 ```py 2019-03-21 14:56:21,313 stack_trace.py: exception occurred Traceback (most recent call last): File "C:\Users\Jano\Documents\pyprogs\pylog\stack_trace.py", line 11, in <module> print(vals[4]) IndexError: list index out of range ``` 棧跟蹤包含在日志中。 ## Python 日志`getLogger` `getLogger()`返回具有指定名稱的記錄器。 如果未指定名稱,則返回根記錄器。 在`__name__`中放置模塊名稱是一種常見的做法。 使用給定名稱對該函數的所有調用均返回相同的記錄器實例。 這意味著記錄器實例永遠不需要在應用的不同部分之間傳遞。 `get_logger.py` ```py #!/usr/bin/env python import logging import sys main = logging.getLogger('main') main.setLevel(logging.DEBUG) handler = logging.FileHandler('my.log') format = logging.Formatter('%(asctime)s %(name)s %(levelname)s: %(message)s') handler.setFormatter(format) main.addHandler(handler) main.info('info message') main.critical('critical message') main.debug('debug message') main.warning('warning message') main.error('error message') ``` 該示例使用`getLogger()`創建一個新的記錄器。 它有一個文件處理器和一個格式化程序。 ```py main = logging.getLogger('main') main.setLevel(logging.DEBUG) ``` 創建了一個名為`main`的記錄器; 我們將日志級別設置為`DEBUG`。 ```py handler = logging.FileHandler('my.log') ``` 創建一個文件處理器。 消息將被寫入`my.log`文件。 ```py format = logging.Formatter('%(asctime)s %(name)s %(levelname)s: %(message)s') handler.setFormatter(format) ``` 格式化程序已創建。 它包括時間,記錄器名稱,記錄級別以及要記錄的消息。 格式化程序通過`setFormatter()`設置為處理器。 ```py main.addHandler(handler) ``` 該處理器將通過`addHandler()`添加到記錄器。 ```py $ cat my.log 2019-03-21 14:15:45,439 main INFO: info message 2019-03-21 14:15:45,439 main CRITICAL: critical message 2019-03-21 14:15:45,439 main DEBUG: debug message 2019-03-21 14:15:45,439 main WARNING: warning message 2019-03-21 14:15:45,439 main ERROR: error message ``` 這些是書面的日志消息。 ## Python 日志 YAML 配置 日志詳細信息可以在 YAML 配置文件中定義。 YAML 是一種人類可讀的數據序列化語言。 它通常用于配置文件。 ```py $ pip install pyyaml ``` 我們需要安裝`pyyaml`模塊。 `config.yaml` ```py version: 1 formatters: simple: format: "%(asctime)s %(name)s: %(message)s" extended: format: "%(asctime)s %(name)s %(levelname)s: %(message)s" handlers: console: class: logging.StreamHandler level: INFO formatter: simple file_handler: class: logging.FileHandler level: INFO filename: test.log formatter: extended propagate: false loggers: dev: handlers: [console, file_handler] test: handlers: [file_handler] root: handlers: [file_handler] ``` 在配置文件中,我們定義了各種格式化程序,處理器和記錄器。 `propagate`選項可防止將日志消息傳播到父級記錄器。 就我們而言,是根記錄器。 否則,消息將被復制。 `log_yaml.py` ```py #!/usr/bin/env python import logging import logging.config import yaml with open('config.yaml', 'r') as f: log_cfg = yaml.safe_load(f.read()) logging.config.dictConfig(log_cfg) logger = logging.getLogger('dev') logger.setLevel(logging.INFO) logger.info('This is an info message') logger.error('This is an error message') ``` 在示例中,我們讀取配置文件并使用`dev`記錄器。 ```py $ log_yaml.py 2019-03-28 11:36:54,854 dev: This is an info message 2019-03-28 11:36:54,855 dev: This is an error message ``` 當我們運行程序時,控制臺上有兩條消息。 控制臺處理器使用帶有較少信息的簡單格式化程序。 ```py ... 2019-03-28 11:36:54,854 dev INFO: This is an info message 2019-03-28 11:36:54,855 dev ERROR: This is an error message ``` `test.log`文件中有日志消息。 它們由擴展的格式化程序提供,具有更多信息。 在本教程中,我們使用了 Python 日志庫。 您可能也對相關教程感興趣: [Python Jinja 教程](/python/jinja/), [Bottle 教程](/python/bottle/), [Python 教程](/lang/python/)或列表 [Python 教程](/all/#python)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看