随笔都是学习笔记
随笔仅供参考,为避免笔记中可能出现的错误误导他人,请勿转载。
posts - 398,comments - 0,views - 13万

日志模块配置文件logging.yaml

复制代码
version: 1
formatters:
  simple:
    format: '[%(asctime)s %(thread)d] [%(levelname)s] %(message)s'  # 日志内容的格式化,具体参数问GPT或百度
    dateformat: '%Y-%m-%d %H:%M:%S.%f'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout
  console_err:
    class: logging.StreamHandler
    level: ERROR
    formatter: simple
    stream: ext://sys.stderr
  file:
    class: logging.FileHandler  # 文件
    level: DEBUG
    formatter: simple
    mode: a # 追加写入,每次记录日志都在文件后面追加内容
    encoding: utf-8 # 编码
    filename: my_log.log  # 将日志写入的文件,指定路径,只有文件名则是当前路径
loggers:
  simpleExample: # 代码中获取的日志名
    level: DEBUG  # 该日志记录器的级别,从下往上包含
    handlers: [console,file]  # 与上面handlers的自己关联
    propagate: no
#root:
#  level: DEBUG
#  handlers: [file]
复制代码

 

日志工具类:

复制代码
#! /usr/bin/env python
# coding=gbk
import datetime
import logging, os
import ctypes
import logging.config

import yaml

from config.pathconfig import PathConfig

FOREGROUND_WHITE = 0x0007
FOREGROUND_BLUE = 0x01  # text color contains blue.
FOREGROUND_GREEN = 0x02  # text color contains green.
FOREGROUND_RED = 0x04  # text color contains red.
FOREGROUND_YELLOW = FOREGROUND_RED | FOREGROUND_GREEN

STD_OUTPUT_HANDLE = -11
std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)


def set_color(color, handle=std_out_handle):
    bool = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
    return bool


class Logger:

    def __init__(self):
        # 路径配置文件类,管理项目根目录下的文件夹路径
        sp = PathConfig()
        # 从路径config中读取日志文件夹logs的路径,使用当前年月日作为文件名
        path = sp.logs + '/%s.log' % datetime.datetime.now().strftime("%Y-%m-%d")
        self.__create_log_file(path)
        # 读取日志配置文件配置
        with open(sp.config + '/logging.yaml', 'r') as f:
            # 使用Yaml模块加载配置文件内容到字典中
            # yaml.load(f,Loader=yaml.FullLoader)方法是使用PyYAML库加载YAML文件的一种常见方式,使用FullLoader类作为加载器,以确保安全加载YAML数据
            dict_conf = yaml.load(f, Loader=yaml.FullLoader)
        # 将日志的yaml配置文件中文件路径改为自定义
        dict_conf['handlers']['file']['filename'] = path
        # 使用修改后的配置字典来配置日志系统
        logging.config.dictConfig(dict_conf)
        # 获取名为'simpleExample'的日志记录器
        self.logger = logging.getLogger('simpleExample')

    def __create_log_file(self, path):
        file_name = os.path.basename(path)
        file_path = path.replace("/" + file_name, "")
        if not os.path.exists(file_path):
            os.makedirs(file_path)
            # 在指定目录下创建文件
            with open(path, 'w', encoding="utf-8") as f:
                f.write(
                    "############################# %s CREATE NEW LOG FILE #############################\n" % datetime.datetime.now().strftime(
                        "%Y-%m-%d %H:%M:%S"))

    def debug(self, message):
        self.logger.debug(message)

    def info(self, message):
        self.logger.info(message)

    def war(self, message, color=FOREGROUND_YELLOW):
        set_color(color)
        self.logger.warning(message)
        set_color(FOREGROUND_WHITE)

    def error(self, message, color=FOREGROUND_RED):
        set_color(color)
        self.logger.error(message)
        set_color(FOREGROUND_WHITE)

    def cri(self, message):
        self.logger.critical(message)
复制代码

创建日志文件前需要判断这个文件及其路径是否存在,不存在先创建文件。

 

posted on   时间完全不够用啊  阅读(13)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2021-12-03 IntelliJ Idea之增强for快捷键
2021-12-03 Java之迭代器
2021-12-03 Java之集合
2021-12-03 键盘使用体验
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示