天天看点

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