天天看點

Python 中日志的使用和中文亂碼問題解決

前言

一、依賴版本

二、相關配置和參數代碼示例

from pathlib import Path
import logging
'''
(function) basicConfig: (*, filename: StrPath 存儲路徑
 | None = ..., filemode: str = ..., 
 format: str = ..., 格式化 
    %(asctime)s 時間
    %(created)f 建立時間
    %(filename)s 檔案名 日志記錄所在的檔案
    %(funcName)s 日志記錄調用的函數的名稱
    %(name)s 用于記錄調用的日志記錄器的名稱 
    %(levelname)s 日志等級 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'
    %(levelno)s 日志等級對應的數字 DEBUG, INFO, WARNING, ERROR, CRITICAL
    %(message)s 日志列印的消息内容
    %(module)s 對應的子產品名稱
    %(msecs)d 日志記錄時時間的毫秒部分
    %(pathname)s 目前運作檔案對應的路徑
    %(process)d 隊列号
    %(processName)s 隊列名稱
    %(relativeCreated)d 建立日志記錄的時間,相對于加載日志子產品的時間
    %(thread)d 線程
    %(threadName)s 線程名稱

 datefmt: str | None = ..., 
 style: _FormatStyle = ..., 
 level: _Level | None = ...,日志級别
  stream: SupportsWrite[str] | None = ..., handlers: Iterable[Handler] | None = ..., force: bool = ...
'''
d = {'clientip': '192.168.10.222', 'user': 'julong'}
#  %(clientip)s - %(user)s 
format="%(asctime)s -%(process)d - %(processName)s - %(thread)d - %(threadName)s - %(relativeCreated)d - %(filename)s - %(funcName)s - %(created)f- %(name)s - %(levelno)s - %(levelname)s - %(module)s -%(pathname)s- %(msecs)d - %(message)s"
## 設定中文亂碼問題 并且輸入到檔案
fileHandler = logging.FileHandler(filename="第十章:檔案和異常\\logging\\python.log",encoding="utf-8")
## 設定日志輸出到控制台
streamHandler = logging.StreamHandler(stream=None)
logging.basicConfig(level=logging.DEBUG,format=format,handlers=[fileHandler,streamHandler])

home = Path.home()
logging.info(home)
logging.debug(home)
logging.error(home)
logging.warning(home)
logging.critical(home)


def info():
    logging.info(home)
def debug():
    logging.debug(home)
def error():
    logging.error(home)
def warning():
    logging.warning(home)
def critical():
    logging.critical(home)


info()
debug()
error()
warning()
critical()      
logging_test -d:\python_work\��ʮ�£��ļ����쳣\logging\logging_test.py- 368 - C:\Users\julong
2022-07-14 13:52:04,368 - 192.168.10.222 - julong -7288 - MainProcess - 7640 - MainThread - 3 - logging_test.py - <module> - 1657777924.368816- root - 50 - CRITICAL - logging_test -d:\python_work\��ʮ�£��ļ����쳣\logging\logging_test.py- 368 - C:\Users\julong
2022-07-14 13:53:49,246 - 192.168.10.222 - julong -7512 - MainProcess - 368 - MainThread - 4 - logging_test.py - <module> - 1657778029.246815- root - 20 - INFO - logging_test -d:\python_work\��ʮ�£��ļ����쳣\logging\logging_test.py- 246 - C:\Users\julong
2022-07-16 18:51:16,476 -10172 - MainProcess - 6620 - MainThread - 2 - logging_test.py - <module> - 1657968676.476577- root - 20 - INFO - logging_test -d:\python_work\第十章:檔案和異常\logging\logging_test.py- 476 - C:\Users\julong