> For the complete documentation index, see [llms.txt](https://stb11816.gitbook.io/python_note/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://stb11816.gitbook.io/python_note/web/logging.md).

# logging

Log層級(輕至重)：debug --> info --> warning --> error --> critical

```python
import logging

# 輸出log檔案
log_file = 'log_file.log'
level = logging.INFO
logging.basicConfig(level=level,
                        format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        handlers=[logging.FileHandler(log_file, 'a', 'utf-8')])


# 在cmd中顯示
console = logging.StreamHandler()
console.setLevel(level)
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')  # 設定輸出格式
console.setFormatter(formatter)  # handler 設定輸出格式
logging.getLogger('').addHandler(console)  # 加入 handler 到 root logger


# 設定新的name，否則全部都會是root
logger_ = logging.getLogger(os.path.basename(__file__).replace('.py', ''))  # 將檔案名稱設定為name
```

參考資料：\
<http://zwindr.blogspot.com/2016/08/python-logging.html>

multiprocessing-logging

<https://hant.helplib.com/GitHub/article_124489>

如果在multiprocessing時使用logging，需在全域位置宣告logger

<http://hk.voidcc.com/question/p-voslmrpl-ru.html>

或者用queue來存放訊息，然後統一輸出

<https://stackoverflow.com/questions/11515944/how-to-use-multiprocessing-queue-in-python>

<https://morvanzhou.github.io/tutorials/python-basic/multiprocessing/3-queue/>
