menu Chancel's blog
rss_feed
Chancel's blog
时来天地皆同力

Python3日志模块配置

作者:Chancel Yang, 时间:2022 May 26, 阅读:35

logging 支持YAML格式的日志配置文件,在项目入口main文件同一层添加logging.yaml文件,内容如下

version: 1
formatters:
  common:
    format: "%(asctime)s - %(levelname)s - %(threadName)s - %(message)s"
    datefmt: "%Y/%m/%d %H:%M:%S"
  console:
    format: "%(asctime)s - %(levelname)s - %(pathname)s - %(message)s"
    datefmt: "%Y/%m/%d %H:%M:%S"
handlers:
  # 不同会输出大于等于此级别的信息。
  common:
    class: logging.handlers.TimedRotatingFileHandler
    formatter: common
    level: INFO
    when: D
    interval: 1
    encoding: utf8
    filename: "logs/running.log"
    # suffix: "%Y-%m-%d.log"
    # 日志保留个数
    backupCount: 7
  console:
    class : logging.StreamHandler
    formatter: console
    level   : INFO
    stream  : ext://sys.stdout
loggers:
  main.common:
    level: INFO
    handlers: [common]
# 如果模块中没有使用 如logging.getLogger('main.common') 这样的配置来获取loggers中对应的配置,则默认会使用下面的root配置
root:
  level: DEBUG
  handlers: [console]

在main文件配置logging模块

import os
import yaml
import logging
import logging.config

os.chdir(os.path.abspath(os.path.dirname(os.path.abspath(__file__))))

# Logger config
if not os.path.exists('logs'):
    os.mkdir('logs')
# 日志配置
with open('logging.yaml', 'r', encoding='utf-8') as f:
    config = yaml.load(f, Loader=yaml.FullLoader)
    logging.config.dictConfig(config)
logger = logging.getLogger('main.common')

[[replyMessage== null?"发表评论":"发表评论 @ " + replyMessage.m_author]]

account_circle
email
web_asset
textsms

评论列表([[messageResponse.total]])

还没有可以显示的留言...
[[messageItem.m_author]] [[messageItem.m_author]]
[[messageItem.create_time]]
[[getEnviron(messageItem.m_environ)]]
[[subMessage.m_author]] [[subMessage.m_author]] @ [[subMessage.parent_message.m_author]] [[subMessage.parent_message.m_author]]
[[subMessage.create_time]]
[[getEnviron(messageItem.m_environ)]]